How to update shared preference instantly after reading data from volley? - android

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

Related

Logic behind storing a max number of user favorites to SharedPreferences

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!

App crashes when trying to load the data to and from shared preference

In my app, i am taking the notification posted event and filtering the notification, then saving it in the shared preference from the object model and used hashmap for it :
Map<String, List<Model>>
I am using asynctask to fetch the list back in the app from shared preference :
private class FetchData extends AsyncTask<Void,Void,Map<String,List<Model>>> {
#Override
protected Map<String, List<Model>> doInBackground(Void... voids) {
SharedPreferences shared;
Gson gson = new Gson();
shared = getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
modelList = gson.fromJson(
shared.getString("My_map", null),
new TypeToken<HashMap<String, List<Model>>>() {
}.getType());
return modelList;
}
#Override
protected void onPostExecute(Map<String, List<Model>> stringListMap) {
super.onPostExecute(stringListMap);
if(modelList!=null) {
keys = getKeys(modelList);
adapter = new CustomListAdapter(getApplicationContext(), keys);
list.setAdapter(adapter);
}
}
}
The saving of the data is in this function :
private void saveMap(Map<String,List<Model>> inputMap){
SharedPreferences shared;
SharedPreferences.Editor editor;
shared = getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
editor = shared.edit();
Gson gson = new Gson();
String json = gson.toJson(inputMap);
editor.putString("My_map", json);
editor.commit();
}
Whenever a new notification is posted , i extract the data from it and save it in the local hashmap and to the shared prefernce too . and at the time of app opening i load the data from the shared preference to the local list .
What i am not able to understand is the reason of anr in my app whenever a new notification is posted.
It has been 8006.8ms since event, 8006.4ms since wait started. Reason: Waiting to send non-key event because the touched window has not finished processing certain input events that were delivered to it over 500.0ms ago. Wait queue length: 2. Wait queue head age: 9112.1ms.
Reason: Waiting to send non-key event because the touched window has not finished processing certain input events that were delivered to it over 500.0ms ago. Wait queue length: 2. Wait queue head age: 9112.1ms.
Good day!
First of all, you should move a call of saveMap() function to background thread. For example inside doInBackground().
Also I recommend you to think about using database to store notifications - there are too complex to be stored in Shared Preferences.

How to change password after user login in android ? In shared Preferences?

I use token based authentication in my app. When user logins through Android app the server returns token which needs to be sent with each subsequent request.
I need to store that value on the devices. Since token is a simple string, I thought I'd use SharedPreferences to hold that value.
Two think confuse me on which method save token in sharedpref. and other one is where to receive the token while implementing change password.
Use Aynch task For network task
Use Post Method Api
try something like this.. Create a class for saving values
public class SharedPreferenceCustom {
private String defValue = "";
private SharedPreferences sharedPreferences;
public SharedPreferenceCustom(Context context) {
sharedPreferences = context.getSharedPreferences("app_name", Context.MODE_PRIVATE);
}
public void setSharedPref(String inputKey, String inputValue) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(inputKey, String.valueOf(inputValue));
editor.apply();
}
public String getSharedPref(String inputKey) {
return sharedPreferences.getString(inputKey, defValue);
}
}
and call whenever needed
Call by
SharedPreferenceCustom sp = new SharedPreferenceCustom(mContext);
sp.setSharedPref("KEY", "VALUE");
// or
sp.getSharedPref("KEY");

Storing and retrieving array list values in shared preferences android returns null

I am trying to store and retrieve values in shared preferences but first time when I open the app, the shared preference value is NULL. From next time, it shows the values of previous key.
This is my code,
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Set<String> set;
sharedPreferences = getApplicationContext().getSharedPreferences(mypreference, Context.MODE_PRIVATE);
databaseReferenceImages.child(postkey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
SharedPreferences.Editor editor = sharedPreferences.edit();
Set<String> sharedlist = new HashSet<String>();
sharedlist.addAll(second);
editor.putStringSet("notifications", sharedlist);
editor.apply();
for (String a : sharedlist) {
Log.d("thesharedlist", a);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
set = sharedPreferences.getStringSet("notifications", null);
if (set != null) {
for (String a : set) {
Log.d("thesetis", a);
}
}
Here I want the values for a particular "POSTKEY"(Poskey will be different for each post)
I want to get the value of array list or "SET" outside of onDataChange method so I used shared Preferences. Its working fine for a String but not for Array list or Set. The following problem occurs,
When I open the app for the first time and click a particular post,
the value of the shared preference value which is returned is NULL.
When I open the same post for the second time, the values are
returning perfectly.
When I open second post ,the values of
previous post are returning.
When I open the first post again, the values of second post are returning.
I don't know where I am wrong. I tried clearing the values of shared preferences each time the app opens but the same problem occurs. I even followed this link but nothing worked. Any help would be great. Thanks in advance.
If you don't want to get null first time, you can do one of these 2 things:
1- call getStringSet differently
sharedPreferences.getStringSet("notifications", "it isn't saved yet!");
2- save default value to sharedpreference before getStringSet
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet("notifications", sharedlist);
editor.apply();
If you want to get current post not previous one, you should save it before. my guess is that you click on post number one and it's stored in sharedpreference and when you want to check the second one, it returns first one.
I have solved the issue by storing it in sharedpreference after 1500ms.
This is my code,
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
set = sharedPreferences.getStringSet("notifications", null);
if (set != null) {
for (String a : set) {
Log.d("thesetis", a);
}
}
}
}, 1500);

Problems in storing the listview data

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

Categories

Resources