Abdelrahman Manna Abdelrahman Manna - 4 months ago 17
Android Question

Android getSharedPreferences is not working inside a method

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) {
//
}

});
}

Answer

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);
}