Problem Because of the Context

0

I have a custom ListView and a button that when I press it saves a data, in this button I use "SharedPreferences" the shared preferences, the problem is that the adapter (Java Code) is like this:

public class Adaptador extends BaseAdapter{

Then I can not call the SharedPreferences method to save the data so what I did create a Java file called 'datos.java' and create the function 'SaveData' to save the data that would be like this:

 public  void GuardarDatos(String posicion, boolean valor)
{

    SharedPreferences prefs = getSharedPreferences("settingAlarmas", this.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putBoolean(posicion, valor); //ID - ESTADO
    editor.apply();
}

The function 'SaveData' is being called from the adapter in this way:

Datos d = new Datos();
d.GuardarDatos("valor",true); //ID- Y Valor

The problem is because of the context in which it is called by the this in which this only serves for the current activity but I do not know what context to use to make the application because other methods of other classes are being called to operate the custom adapter

    
asked by Diego 13.05.2018 в 20:54
source

2 answers

1

1.-From your activity when you create the Adapter, pass the context as parameter so Adaptador miAdaptador = new Adaptador(this); then in the Adapter class create an attribute of type Context so that you can use it in the whole class.

2.-Add the context as a parameter to your SaveData method like this:

public  void GuardarDatos(Context context, String posicion, boolean valor) {}

3.-inside the method calls the mode: context.MODE_PRIVATE .

4.- Pass the context when you call the SaveData method:

Datos d = new Datos();
d.GuardarDatos(contexto, "valor",true); 

The context is what you pass from the activity to the Adapter. ( new Adaptador(this) ) and that should be an attribute in the Adapter class.

    
answered by 13.05.2018 / 22:14
source
0

Hello sorry the incomplete answer I have not touched Android in a long time. So you can pass the context, because it has worked perfect in my apps.

SharedPreferences prefs = this.getSharedPreferences("settingAlarmas", Context.MODE_PRIVATE);

However you could also use getApplicationContext () because I understand you need the context not in the activity but in the application.

    
answered by 14.05.2018 в 05:08