I want to implement twitter like functionality in my app as when you logged in for the first time you get the data from the server and show it inside listview but if you again open the app without logging out i do not want the app to request the server again for getting the same data so my question is where to store the data that fetched previously so app wont request the server again and for getting the new data i have implemented the refreshable list view so user will get the new data by refreshing the list.
And one more thing is after refreshing i want to store the new data as well to the same place where previous data was saved and i want to store only the 20 items to prevent the memory overflow . please help someone.
I have an arraylist ArrayList> fetch where i am storing the data while fetching from the server.
The server must be returning the information in JSON or XML format, simply put it in shared preferences and retrieve/show later based on a few internal flags.
For example, here's a sample code to store stuff in shared preferences:
private void writeStrToPreferences(String strKey, String str){
if(strKey == null) return;
if(str == null) return;
if(str.length() <= 0) return;
SharedPreferences.Editor ed = getSharedPreferences(strKey, 0).edit();
ed.putString(strKey, str);
ed.commit();
}
Reading back will also be similar and simple
private String readStrFromPreferences(String strKey){
if(strKey == null)return "NA";
if(strKey.length() <= 0) return "NA";
return getSharedPreferences(strKey, 0).getString(strKey, "NA");
}
For more, check documentation here:
http://developer.android.com/reference/android/content/SharedPreferences.html
Related
I'm wanting to store a number of different user favorites (in this example a max of 5) in sharedpreferences.
The user will be able to add and delete these favorites from within the app.
I'm having trouble getting my head around how to achieve this (I assume some sort of looping is needed).
The gist of what I'm trying to do when a user adds a new favorite:
//init prefs
public static final String PREFS_NAME = "PREFS";
SharedPreferences sharedPreferences = null;
SharedPreferences.Editor sharedPreferencesEditor;
//onCreate
sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
//method called when user adds new favorite
public void addFavorite(String fav) {
//int i = 0;
//int maxFavs = 5;
//check how many favorites are already stored in shared prefs, if any (is it under maxFavs?)
//if over maxFavs, display error
Toast.makeText(getApplicationContext(),"Favorite added",Toast.LENGTH_SHORT).show();
//else continue
//upon finding available favorite 'space' (less than permitted maxFavs), add to favorites in shared prefs
sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putString("fav_" + i, fav);
sharedPreferencesEditor.apply();
}
Am I getting the right idea here, or is there a better way to do what I'm intending to do? Hopefully it's clear from the above.
Store favorite count in preferences as an int and read & update it as needed. Also it would be better if you store favorites in preferences as (key : favoritedItemId, value boolean)
Even better: Use a proper local database for situations like this. Preferences is a primitive key value type storage intended for simplier cases like storing a users light mode preference.
Gave up and created a simple database following the example here:
https://inducesmile.com/android/android-sqlite-database-example-tutorial/
Still, if anyone has a solution I'd be interested to see!
I want to store data retrieved from API using volley, but if I made 2 different requests followed by each other , it shows the first request only before updating .
I have to request the second one again to store the new data.
Is there a solution?
SharedPreferences m=PreferenceManager.getDefaultSharedPreferences(context);
String resp=m.getString("Response","");
return resp;
private void share (String x)
{
SharedPreferences
m=PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor=m.edit();
editor.putString("Response",x);
editor.commit();
}
I'm using a listView and wants to restore/ resume the listView item/ state from where I had left (even after app closes).
For this purpose I'm using
Parcelable state = listView.onSaveInstanceState();
the state is of Parcelable type because it returns result in parcelable type also while on restoring listView using
listView.onRestoreInstanceState(state);
it needs Parcelable type data as a parmeter.
It works perfectly (using static variable) if user didn't closes the app.
But I want to save this state data into SharedPreferences that will help the user to restore the listView even after closing the app.
I don't know how to store this state data into SharedPreferences. Please help me to solve this issue.
I also have tried this solution
How Android SharedPreferences save/store object
but it didn't solved my problem. The app is crashing on
Parcelable obj = gson.fromJson(json, Parcelable.class);
So, Please don't duplicate my question, If you know the solution just answer it.
I assume that your listview has an adapter that contains your required data so you can save that data somewhere (e.g. in sharedpreferences) instead of whole view's parcelable, e.g. if your adapter data is an ArrayList<ModelA> you can do something like this:
if ( listview.getAdapter() instanceof MyAdapter){
MyAdapter adapter = (MyAdapter) listview.getAdapter();
SharedPreferences.Editor editor = prefs.edit();
editor.putString( "adapterdata" , gson.toJson(adapter.getData()));
editor.commit(); //or editor.apply()
}
and when you want to retrieve the data
String dataJson = prefs.getString( "adapterdata" , "");
ArrayList<ModelA> data = gson.fromJson( dataJson, new TypeToken<ArrayList<ModelA>>(){}.getType());
if ( data != null ){
//set data to your listview, also it's logical to delete retrieved data from sharedpreferences
SharedPreferences.Editor editor = prefs.edit();
editor.remove("adapterdata");
editor.commit();
}
Good day, Sorry for the rather long post. this is more like a design decision than anything else. I have an activity which contains 4 fragments. Now i switch through the fragments through a slideMenu.
Each Fragment makes a call to a webservices and gets a JSONObject result vis an AsyncTask. I am looking for a structure where i would have to cache each JSONObject result
for each fragment . when the user switches between the fragments, it checks if a certain amount of time has expired and acts accordingly
-if cached time has expired, reload the network request again.
-if not, use the cached JSONObject result and display to the user.
this means if i have an expiration time for like 6 hrs or rather the data from the backend updates every 6hrs, I should only request from the webservice via the asynctask
once every 6 hours and other times just used the cached values instead.
My current implementation
1. To have a set of global boolean variables via extending the Application class to load for each fragments the first time.
public class MyApp extends Application {
private boolean First_load_frag1 = true;
private boolean First_load_frag2= true;
public void setLoadFrag1(boolean value){
First_load_frag1 = value;
}
public boolean getLoadFrag1(){
return First_load_frag1;
}
}
in my fragments, i set them to true in onCreate(), use it to determine whether to request the first time and then set it to false so i don't have to anymore.
then in my fragments OnResume() i check to see if the cached_time has expired or not. i do something like this
#Override
public void onResume(){
super.onResume();
public final static long MINUTE_MILLIS = 60000;
Calendar cal = Calendar.getInstance();
int mins = (int) ((cal.getTimeInMillis()/MINUTE_MILLIS) - (cached_timer/MINUTE_MILLIS);
if(mins > 180){
Toast.makeText(getActivity(), "on resume refresh data", Toast.LENGTH_LONG).show();
requestService(); //this sends a request to the webservice
} else {
cached_result = manager.getCachedJSONResult(CACHED_RESULT );
if(cached_result != null){
Toast.makeText(getActivity(), "on resume cached data", Toast.LENGTH_LONG).show();
loadCachedResult(cached_result);
}
}
}
This feels like a messy way of handling this situations to me. Taken into consideration application crashes and Activity lifecycles, is this a good solution of doing something like this oris there a more elegant way i can achieve this? Every input will be much appreciated. Thanks
1.first you need to create data structure for holding data for fragment
check in data structure that data is available for selected fragement and it is time for refresh data
if yes then call load data(web service to load data) into fragment
else
load data from data structure and show in fragment.
Ok, this annoying problem is probably quite familiar, but I don't know what its being called and how to solve it. When I open my app and go to the menu and after a meanwhile, when resuming the app, I loose all my data. It seems that android likes to clean data in order to keep the OS as fast and stable as possible. Which method is recommended in saving data in the internal memory and retrieving it back when any kind of variable is cleaned/null before resuming the app? I tried setSharedPreferences to parse an ArrayList to an Object and parse the Object as a String to save the data and retrieve it, but I get cannot parse Object to String exception. There has to be a better alternative.
Any help will be appreciated.
Edit:
This is how I retrieve and store data:
JSONObject data = (JSONObject) new JSONTokener(result).nextValue();
Helper.RAW_PEOPLE_INFO = data.getJSONArray("people");
Helper.PEOPLE_CONTAINER = new ArrayList<PeopleInfoStorage>();
for( int i = 0; i < Helper.RAW_PEOPLE_INFO.length(); i++ ){
Helper.PEOPLE_CONTAINER.add( new PeopleInfoStorage(Helper.RAW_PEOPLE_INFO.getJSONObject(i)) );
}
I use the PEOPLE_CONTAINER ArrayList to use it later for when I need it. The PEOPLE_CONTAINER ArrayList gets probably cleaned before I resume my application, so can someone help me giving an example on how to store this ArrayList in the internal memory so I can retrieve the data from the internal memory and put it back to the PEOPLE_CONTAINER ArrayList for when it's null again.
It needs to be something like this:
#Override
protected void onPause() {
if( Helper.PEOPLE_CONTAINER != null ){
//save the Helper.PEOPLE_CONTAINER ArrayList to the internal memory
}
super.onPause();
}
#Override
protected void onResume() {
if( Helper.PEOPLE_CONTAINER == null ){
//retrieve the data and store it back to Helper.PEOPLE_CONTAINER ArrayList
}
super.onResume();
}
There are many methods to persist data in your application; I'm not going to go into great detail here, but you should check out these resources:
http://developer.android.com/guide/topics/data/data-storage.html
If you have an array list, it sounds like it might be worth SQLite.