2
public static void GetAllPoints(final IGetAllPointsCallBack callBack) {    
    SharedPreferences entity =  getSharedPreferences("settings",MODE_PRIVATE);
    String savedValue = entity.getString("entityGUID",null);
}

getSharedPreferences is not working here, is there a way to call it inside my method while I save its value in another class ?

I am saving my preferences like this:

EntityType selectedItem = ApplicationController.entities.get(which);
SharedPreferences.Editor savedValue = getSharedPreferences("settings",MODE_PRIVATE).edit();
savedValue.putString("entityGUID", String.valueOf(selectedItem.EntityGUID));
savedValue.apply();

I needed to make my method static is because I am accessing it from another class:

    public void showAllSpots()
    {
     DataService.GetAllPoints(newDataService.IGetAllChargingPointsCallBack() {
     @Override
     public void Success(ArrayList<ChargingSpot> chargingSpots) {
      //
     }

     });
    }
Nikhil PV
  • 1,014
  • 2
  • 16
  • 29

2 Answers2

2

You need to either change your method so that it is not static OR you need to supply Context as one of the arguments to this method and then your method will look like:

public static void GetAllPoints(final Context context, final IGetAllPointsCallBack callBack) {    
    SharedPreferences entity =  context.getSharedPreferences("settings",Context.MODE_PRIVATE);
    String savedValue = entity.getString("entityGUID",null);
}

I hope this helps.

ishmaelMakitla
  • 3,784
  • 3
  • 26
  • 32
0

As per the official docs for Context, getSharedPreferences(...) is NOT static. Therefore you won't be able to access it within a static method.

Try defining your method like below and it should work:

public void GetAllPoints(final IGetAllPointsCallBack callBack) {    
    SharedPreferences entity =  getSharedPreferences("settings",MODE_PRIVATE);
    String savedValue = entity.getString("entityGUID",null);
}

EDIT: Upon examining your comment reply, I noticed your requirement of keeping GetAllPoints(...) static. A workaround would be passing the calling Context and call getSharedPreferences(...) from it:

public void GetAllPoints(final Context context, final IGetAllPointsCallBack callBack) {    
    SharedPreferences entity =  context.getSharedPreferences("settings",MODE_PRIVATE);
    String savedValue = entity.getString("entityGUID",null);
}
Hadi Satrio
  • 4,272
  • 2
  • 24
  • 45