Search code examples
androidsharedpreferences

Access shared preferences from a helper class


I have a fragment that calls a helper class in order to make a jsonRequest with Volley.

Upon response, the helper class creates a custom object, but in order to set it up, it needs to check some values stored in Shared Preferences.

The problem is that I can't access getSharedPreferences inside the helper class.

public class MyDataHandler {
ArrayList<MyItem> itemsArrayList = new ArrayList<>();

public List<MyItem> getAll(Boolean completed, String current, final MyAsyncResponse callBack) {

    String url = "https://my.api/" + current;

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
            Request.Method.GET,
            url,
            null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    for (int i = 0; i < response.length(); i++) {

                        try {
                            JSONObject jsonObject = response.getJSONObject(i);

                            MyItem myItem = new MyItem();

                            if (!completed) {
                                SharedPreferences sharedPreferences = getSharedPreferences("MyApp", MODE_PRIVATE); // this doesn't work
                                if (sharedPreferences.getBoolean("someKey", false)) {
                                     // set properties in MyItem
                                }
                            }

                            itemsArrayList.add(myItem);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    if (null != callBack) callBack.processFinished(itemsArrayList);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }
    );

    AppController.getInstance().addToRequestQueue(jsonArrayRequest);

    return itemsArrayList;
}

How can I access Shared Preferences if this class isn't attached to any particular activity?


Solution

  • I assume that you are instantiating MyDataBaseHandler as "getAll" is a non static function create a constructor and a member variable like this :-

     MyDataBaseHandler{
       
     Context context;
    
    public MyDataHandler(Context context){ //pass your activity here
        this.context=context;
     }
    // write rest of your code
    
    }
    

    now you can use this context member variable and access your shared perefrence using context.getSharedPreference("MyApp", Context.MODE_PRIVATE).