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