4

I am creating an application,In my app I am getting response and displaing it in custom alert dialog, Till here it works fine, Now what I am trying to do is if user selects an item from alert dialog once, it should store it in preference so that no need of fetch the data every time.

Following is my code snippet.

The following response which i am getting is :

    {
    "states": [
        {
            "id": "1",
            "state_slug": "agra",
            "statename": "Agra"
        },
        {
            "id": "2",
            "state_slug": "andaman_and_nicobar_islands",
            "statename": "Andaman and Nicobar Islands"
        },
        {
            "id": "3",
            "state_slug": "andhra_pradesh",
            "statename": "Andhra Pradesh"
        },
        {
            "id": "4",
            "state_slug": "arunachal_pradesh",
            "statename": "Arunachal Pradesh"
        },
        {
            "id": "5",
            "state_slug": "assam",
            "statename": "Assam"
        },
        {
            "id": "6",
            "state_slug": "bihar",
            "statename": "Bihar"
        },
        {
            "id": "7",
            "state_slug": "bulandshahr",
            "statename": "Bulandshahr"
        },
        {
            "id": "8",
            "state_slug": "chhattisgarh",
            "statename": "Chhattisgarh"
        },
        {
            "id": "9",
            "state_slug": "dadra_and_nagar_haveli",
            "statename": "Dadra & Nagar Haveli"
        },
        {
            "id": "10",
            "state_slug": "daman_and_diu",
            "statename": "Daman & Diu"
        },
        {
            "id": "11",
            "state_slug": "delhi",
            "statename": "Delhi"
        },
        {
            "id": "12",
            "state_slug": "farrukhabad",
            "statename": "Farrukhabad"
        },
        {
            "id": "13",
            "state_slug": "goa",
            "statename": "Goa"
        },
        {
            "id": "14",
            "state_slug": "gujarat",
            "statename": "Gujarat"
        },
        {
            "id": "15",
            "state_slug": "haryana",
            "statename": "Haryana"
        },
        {
            "id": "16",
            "state_slug": "himachal_pradesh",
            "statename": "Himachal Pradesh"
        },
        {
            "id": "17",
            "state_slug": "jammu_and_kashmir",
            "statename": "Jammu & Kashmir"
        },
        {
            "id": "18",
            "state_slug": "jharkhand",
            "statename": "Jharkhand"
        },
        {
            "id": "19",
            "state_slug": "karnataka",
            "statename": "Karnataka"
        },
        {
            "id": "20",
            "state_slug": "kerala",
            "statename": "Kerala"
        },
        {
            "id": "21",
            "state_slug": "lakshadweep",
            "statename": "Lakshadweep"
        },
        {
            "id": "22",
            "state_slug": "madhya_pradesh",
            "statename": "Madhya Pradesh"
        },
        {
            "id": "23",
            "state_slug": "maharashtra",
            "statename": "Maharashtra"
        },
        {
            "id": "24",
            "state_slug": "manipur",
            "statename": "Manipur"
        },
        {
            "id": "25",
            "state_slug": "meghalaya",
            "statename": "Meghalaya"
        },
        {
            "id": "26",
            "state_slug": "mizoram",
            "statename": "Mizoram"
        },
        {
            "id": "27",
            "state_slug": "nagaland",
            "statename": "Nagaland"
        },
        {
            "id": "28",
            "state_slug": "orissa",
            "statename": "Orissa"
        },
        {
            "id": "29",
            "state_slug": "pondicherry",
            "statename": "Pondicherry"
        },
        {
            "id": "30",
            "state_slug": "punjab",
            "statename": "Punjab"
        },
        {
            "id": "31",
            "state_slug": "purulia",
            "statename": "Purulia"
        },
        {
            "id": "32",
            "state_slug": "rajasthan",
            "statename": "Rajasthan"
        },
        {
            "id": "33",
            "state_slug": "sikkim",
            "statename": "Sikkim"
        },
        {
            "id": "34",
            "state_slug": "tamil_nadu",
            "statename": "Tamil Nadu"
        },
        {
            "id": "35",
            "state_slug": "tripura",
            "statename": "Tripura"
        },
        {
            "id": "36",
            "state_slug": "uttar_pradesh",
            "statename": "Uttar Pradesh"
        },
        {
            "id": "37",
            "state_slug": "uttarakhand",
            "statename": "Uttarakhand"
        },
        {
            "id": "38",
            "state_slug": "west_bengal",
            "statename": "West Bengal"
        }
    ]
}

I am displaying statename in my alert dialog,

class LoadAllStates extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {

          ArrayAdapter<String> adapterallstates ;
        private ProgressDialog pDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("Please wait..");
                pDialog.setIndeterminate(true);
               // pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
                pDialog.setCancelable(true);
                pDialog.show();

            }
            protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
                ServiceHandler sh = new ServiceHandler();

                // Making a request to url and getting response
                statedata = new ArrayList<HashMap<String, String>>();
                String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);

                Log.d("Response: ", "> " + jsonStr);

                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);
                        state_list = jsonObj.getJSONArray(COUNTRY_LIST);

                        // looping through All Contacts
                        for (int i = 0; i < state_list.length(); i++) {
                            JSONObject c = state_list.getJSONObject(i);

                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                              map.put(STATE_SLG, c.getString(STATE_SLG));
                          map.put(STATE_ID, c.getString(STATE_ID));
                            map.put(STATE_NAME,c.getString(STATE_NAME));

                           statedata.add(map);

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }

                return statedata;
            }

            protected void onPostExecute(ArrayList<HashMap<String,String>> result) {

                super.onPostExecute(result);
               pDialog.dismiss();

                String[] arrallstates=new String[statedata.size()];
                for(int index=0;index<statedata.size();index++){
                          HashMap<String, String> map=statedata.get(index);
                      arrallstates[index]=map.get(STATE_NAME);
                 }  


                 // pass arrConuntry array to ArrayAdapter<String> constroctor :
                adapterallstates = new ArrayAdapter<String>(MainActivity.this,
                                    android.R.layout.simple_spinner_dropdown_item,
                                                                          arrallstates);
                spstate.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View w) {
                          new AlertDialog.Builder(MainActivity.this)
                          .setTitle("Select")
                          .setAdapter(adapterallstates, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                spstate.setText(adapterallstates.getItem(which).toString());

                                 try {

                                     String n  = state_list.getJSONObject(which).getString("state_slug");


                                    statename=state_list.getJSONObject(which).getString("state_slug");
                                    stnm=state_list.getJSONObject(which).getString(STATE_NAME);

                                     Log.d("Response statenm: ", "> " + statename);

                                     SharedPreferences.Editor editor = sharedpreferences.edit();

                                        editor.putString(States, n);
                                        editor.commit();
                                     new LoadAllStatesCity().execute();

                                    // Toast.makeText(getActivity(), statename, Toast.LENGTH_LONG).show();
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                              dialog.dismiss();
                            }
                          }).create().show();
                        }
                });

            }
     }
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96

8 Answers8

5

if you want to store the response the better way is to write the content into a file.if you want to store only some values you can do like this

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("key_from_json", "String_value_from_json");
 editor.putInt("key_from_json","int_value_from_json");
 editor.commit();
Akhil Jayakumar
  • 2,262
  • 14
  • 25
5

You can store your whole object class in preference using gson.jar file -> click here

And to use it...

static public void setPreferenceObject(Context c, Object modal,String key) {
    /**** storing object in preferences  ****/
    SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(
            c.getApplicationContext());
    Editor prefsEditor = appSharedPrefs.edit();

    Gson gson = new Gson();
    String jsonObject = gson.toJson(modal);
    prefsEditor.putString(key, jsonObject);
    prefsEditor.commit();

}

static public Object getPreferenceObjectJson(Context c,String key) {

    SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(
            c.getApplicationContext());
    /**** get user data    *****/
    String json = appSharedPrefs.getString(key, "");
    Gson gson=new Gson();
    User selectedUser=gson.fromJson(json, User.class);
    return  selectedUser;
}
Beena
  • 2,334
  • 24
  • 50
1

SharedPreferences it is prefered for storing small data. Hence to save your entire response it is better you save it to a file (ex: .bin) like so:

 public static synchronized void saveToFileSystem(Context context, Object object, String binFileName) {
        try {
            String tempPath = context.getFilesDir() + "/" + binFileName + ".bin";
            File file = new File(tempPath);
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(object);
            oos.flush();
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

and for reading it you can do smth like:

public static synchronized Object readFromFileSystem(Context context, String binFileName) {
        Object obj = new Object();
        try {
            String tempPath = context.getFilesDir() + "/" + binFileName + ".bin";
            File file = new File(tempPath);
            if (file.exists()) {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
                obj = ois.readObject();
                ois.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return obj;
    }
hrskrs
  • 4,447
  • 5
  • 38
  • 52
1

You can easily save your JSON file completely as a string variable with a key in shared preferences and pars it when you aim to read it again.

1

The easiest way to store JSON object to shared preference is Just make a JSONObject add values to JSONObject at last save to preference with toString

 private void storeDataToPref() {
    SharedPreferences sharedPreferences = getSharedPreferences("localpref", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "hello");
        jsonObject.put("number", "aaaa");
        android.util.Log.d("response", jsonObject.toString());
        editor.putString("pref_data", jsonObject.toString()).commit();
    } catch (JSONException json) {

    }
}

For getting result from shared preference first of all read string convert into jsonobject and get your desire value thats solve hope this will help you all thanks

private void getDataFromPref() {
    SharedPreferences sharedPreferences = getSharedPreferences("localpref", MODE_PRIVATE);
    String value = sharedPreferences.getString("pref_data", "");
    try {
        JSONObject jsonObject = new JSONObject(value);
        String name = jsonObject.getString("name");
        String number = jsonObject.getString("number");
        android.util.Log.d("result", name + "...." + number);
    } catch (Exception e) {

    }
}
Asif Ashraf
  • 13
  • 1
  • 7
0

I'd store the selected value in a key in SharedPreferences. Then, at startup, you'll be able to load SharedPreferences to check whether you already have a value or not (and in that case, you can reload your JSON entirely)

Guide here.

IMMO, it's useless to save a file if you're just looking for storing a value. That's where SharedPreferences are supposed to be used: they are kept even if you close your application and restart it.

Stefano
  • 156
  • 3
  • 14
0

Data for states does not change for years so you can keep this json data in assets and use it from there or keep it in a static map. instead of calling webservice to fetch it.

for persisting the selected value, you can use SharedPreferences and store state id in it. next time whenever you inflate list of states you can check in your shared preference and select the one which is saved.

Community
  • 1
  • 1
Rahul Tiwari
  • 6,851
  • 3
  • 49
  • 78
0

Basically you could check if the value of preferences is stored or not.

you could do this onCreate() method:
Check if preference value exists
if yes:
then no need to make AsyncTask call
and if no:
then make the AsyncTask call

Code:

String statename = preferences.getString("STATE_NAME<name you gave while committing for first time>,"");
 if(statename!=""){
   //Then directly go inside main activity

 }
 else{
//Make AsyncTask Call

 }
PunitD
  • 2,293
  • 1
  • 20
  • 29
  • so what if first user want to change? – Aditya Vyas-Lakhan Oct 19 '15 at 07:07
  • sorry i didn't get it ?what do you mean to say? – PunitD Oct 19 '15 at 07:15
  • @Lakhan do you mean to ask how to change the state once set by user? – PunitD Oct 19 '15 at 07:28
  • Then inside mainactivity you could provide option to user to click on some button or menu option whichever is best and once he clicks on it you once again use the above code and get the json resullts in dialog box and allow him to select it..once selected you change the preferences setting the new state.. Clear? – PunitD Oct 19 '15 at 07:31
  • yes clear but i cant use another extra button or something – Aditya Vyas-Lakhan Oct 19 '15 at 07:35
  • you need to use something like that to help user change his/her state..Or else create separate profile activity page containing his/her personal details from where he could change his/her state..Profile activity page could be accessed from navigation drawer if that works out for you.. – PunitD Oct 19 '15 at 07:39
  • Thank you for time but i can not change the view of my project which is already done... – Aditya Vyas-Lakhan Oct 19 '15 at 07:42
  • Dude..then what exact answer are you looking for over here?!! – PunitD Oct 19 '15 at 07:43