Zahidul
Zahidul

Reputation: 399

Is it save to store server response in SharedPreferences

I would like to store my server response as a string in Shared Preferences so that I can use this response later without fetching from server. But when I saved the data in Shared Preferences and later I use I miss the whole response. I have no security issue and any other cause like uninstall app etc. My question is whether the response will be lost in Shared Preferences so that the response contain multiple JSONObject and JSONArray.

private void productListApi(String url){
    final ProgressDialog pDialog = new ProgressDialog(mContext);
    pDialog.setMessage(mContext.getResources().getString(R.string.loading_message));
    pDialog.show();
    System.out.println("product list urlllllllllllllllllllll:" + url);

    RequestQueue mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());

    StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("response of product list data is:"
                            + response);
                    apiResponse = response ;
                    pDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(response);
                        if (json.has("code")) {

                            if (code.equalsIgnoreCase("200")) {

                                //set response to shared preference
                                SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);

                                parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));


                            }else {
                                UserDialog
                                        .showUserAlert(mContext,
                                                mContext.getResources().getString(R.string.product_list_failed));
                            }
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }


                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            pDialog.dismiss();
            UserDialog.showUserAlert(mContext,
                    mContext.getResources().getString(R.string.no_response));
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            // the POST parameters:

            params.put("user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.USER_ID));
            params.put("temp_user_id", SharedPreference.getStringValue(getActivity(), SharedPreference.TEMP_USER_ID));
            params.put("version", Utilities.getVersionCode(mContext));
            params.put("device_token", SharedPreference.getStringValue(getActivity(), SharedPreference.DEVICE_TOKEN));
            return params;
        }
    };

    int socketTimeout = Constant.socketTimeout
            ;//30 seconds - change to what you want
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    //RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    postRequest.setRetryPolicy(policy);
    mRequestQueue.add(postRequest);

}
public class SharedPreference {

SharedPreferences preferences;
SharedPreferences.Editor editor;

private static final String PREFS_NAME = "nevada_food";

public static final String PRODUCT_LIST_RESPONSE = "product_list" ;

public SharedPreference() {
    super();
    // TODO Auto-generated constructor stub
}

public static String getStringValue(final Context context, String key) {
    return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
            .getString(key, "");
}

public static void setStringValue(final Context context, String key,
                                  String value) {
    final SharedPreferences prefs = context.getSharedPreferences(
            PREFS_NAME, Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = prefs.edit();

    editor.putString(key, value);
    editor.commit();
}

}

this is my server response. I saved it in Shared Preferences and parse data in UI from Shared Preferences. This method
parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE)); works properly first time when directly from server but when we use this method in another it does not work.

Upvotes: 0

Views: 1834

Answers (3)

Ranjit
Ranjit

Reputation: 5150

You are using a wrong way to save into SharedPreference.

Your Code:

 //set response to shared preference
  SharedPreference.setStringValue(mContext, SharedPreference.PRODUCT_LIST_RESPONSE, response);
  parseData(SharedPreference.getStringValue(mContext,SharedPreference.PRODUCT_LIST_RESPONSE));

I don't have any clue what you written here. Try my solution below.

You should have to follow the simple SharedPreference format followed by its Editor.

Just save your data like below:

SharedPreferences.Editor editor = getSharedPreferences("PREFS_NAME", 0).edit();
editor.putString("PRODUCT_LIST_RESPONSE", response);
editor.commit();

And get it by the KEY (PRODUCT_LIST_RESPONSE here)

SharedPreferences prefs = getSharedPreferences("PREFS_NAME", 0); 
String response = prefs.getString("PRODUCT_LIST_RESPONSE", any_default_Value);

Upvotes: 0

Geek
Geek

Reputation: 1530

Data stored in SharedPreference does not loss until unless:

  1. You clear it by manually or programmatically.
  2. Any cache clearing application won't clear application cache.
  3. You uninstall your application.

Depending on scenario you can opt from following approach to save/cache your json data/response:

  1. SharedPreference more convenient to use.
  2. Writing it text file as private or public in external/internal storage. Data stored in external store won't loss even if you uninstall application.
  3. If json is big and there is trade off associated with calling server every time you can go creating Sqlite database or can choose ORM tools like ORMLite, GreeDao etc.

  4. Caching library can be used to cache server response.

Upvotes: 1

azizbekian
azizbekian

Reputation: 62189

My question is whether the response will be lost in Shared Preferences

Shared preferences won't be removed/lost, unless:

  1. you remove them
  2. user clears app data

So, you are safe to store there necessary data.

Upvotes: 0

Related Questions