not getting data from shared preferences - android

i have async task where i am getting data from server in JSONArray format. I want to save that data in shared preferences and display it in list view. i am using adapter.
JSONArray arr = new JSONArray(strServerResponse);
JSONObject jsonObj = arr.getJSONObject(0);
for (int i = 0; i < arr.length(); i++) {
pojo = new Pojo();
JSONObject jobj2 = arr.getJSONObject(i);
String tipoftheday = jobj2.optString("tipsoftheday");
ArrayList<String> tii = new ArrayList<String>();
tii.add(tipoftheday);
List<String> listTemp = tii;
Set<String> temp = new HashSet<String>(listTemp);
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
for (int m=0; m<listTemp.size(); m++){
temp.addAll(listTemp);
editor.putStringSet("tipoftheday",temp);
editor.commit();
}
i am retrieving the value as in below code.
SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
Set<String> set = prefs.getStringSet("tipoftheday", null);
for(String p : set)
{
pojo.setTip(p);
tips.add(pojo);
}
tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
listTips.setAdapter(tipsAdapter);
but i am getting only one value. what is wrong in the code. can anyone please help me.

The problem is, when you're storing the data, every time you're creating a new ArrayList.
Here:
ArrayList<String> tii = new ArrayList<String>();
And you're getting the prefs on every iteration of your outer for loop, you don't have to do this. Just get the reference outside your loop and use it when needed.
Here:
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
Try to change your code to something like this:
JSONArray arr = new JSONArray(strServerResponse);
JSONObject jsonObj = arr.getJSONObject(0);
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
ArrayList<String> tii = new ArrayList<String>();
for (int i = 0; i < arr.length(); i++) {
pojo = new Pojo();
JSONObject jobj2 = arr.getJSONObject(i);
String tipoftheday = jobj2.optString("tipsoftheday");
tii.add(tipoftheday);
}
List<String> listTemp = tii;
Set<String> temp = new HashSet<String>(listTemp);
temp.addAll(listTemp);
editor.putStringSet("tipoftheday",temp);
editor.commit();
EDIT: On your "retrieving" part of the code, you forgot to instantiate your Pojo object.
Like:
pojo = new Pojo();
So your last for loop should look something like:
for(String p : set) {
pojo = new Pojo();
pojo.setTip(p);
tips.add(pojo);
}

The problem in your code is that you are setting the Set value in preference every time i.e. in loop on each element that is why you can only get the last entered value. Change your following code
Set<String> temp = new HashSet<String>(listTemp);
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
for (int m=0; m<listTemp.size(); m++){
temp.addAll(listTemp);
editor.putStringSet("tipoftheday",temp);
editor.commit();
}
Replace it with following
Set<String> temp = new HashSet<String>(listTemp);
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
for (int m=0; m<listTemp.size(); m++){
temp.addAll(listTemp);
}
editor.putStringSet("tipoftheday",temp);
editor.commit();
And see if its working or not
Edit:-
Change your adding code to
JSONArray arr = new JSONArray(strServerResponse);
JSONObject jsonObj = arr.getJSONObject(0);
ArrayList<String> tii = new ArrayList<String>();
for (int i = 0; i < arr.length(); i++) {
pojo = new Pojo();
JSONObject jobj2 = arr.getJSONObject(i);
String tipoftheday = jobj2.optString("tipsoftheday");
tii.add(tipoftheday);
}
List<String> listTemp = tii;
Set<String> temp = new HashSet<String>(listTemp);
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
temp.addAll(listTemp);
editor.putStringSet("tipoftheday",temp);
editor.commit();
And retrieving code to
SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
Set<String> set = prefs.getStringSet("tipoftheday", null);
for(String p : set)
{
pojo = new Pojo();
pojo.setTip(p);
tips.add(pojo);
}
tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
listTips.setAdapter(tipsAdapter);
See if its working or not

Related

Shared Preference multiple string set issue

I'm trying to copy original String set to other three strings sets. After storing/copying as shown below, if I try to print contents are different. any help appreciated.
{
SharedPreferences sp = this.getSharedPreferences("SS", 0);
Set<String> s = new HashSet<String>(sp.getStringSet("DD", new HashSet<String>()));
Object[] array = s.toArray();
SharedPreferences.Editor editor = sp.edit();
editor.putStringSet("CC", s);
editor.commit();
Set<String> zz = new HashSet<String>(sp.getStringSet("ZZ", new HashSet<String>()));
zz.add(array[0].toString());
zz.add(array[1].toString());
SharedPreferences.Editor editor_zz = sp.edit();
editor_zz.putStringSet("ZZ", ZZ);
editor_zz.commit();
Set<String> hop = new HashSet<String>(sp.getStringSet("HH", new HashSet<String>()));
hop.add(array[1].toString());
hop.add(array[0].toString());
SharedPreferences.Editor editor_hop = sp.edit();
editor_hop.putStringSet("HH", hop);
editor_hop.commit();
logSet = null;
iterator = null;
logSet = new HashSet<String>(sp.getStringSet("ZZ", new HashSet<String>()));
iterator = logSet.iterator();
while (iterator.hasNext())
{
String zz = iterator.next();
Log.d("wrong string Y??","ZZList "+zz);
}
}

save data from arraylist to shared preferences not working

i want to add the data from arraylist to sharedpreferences and retrieve the same.
but it is not working. i am getting only one value which is the last value
not all values are retrieved from shared preferences. i am getting the values from
JSONArray first the added in the arraylist.
below is my code to save the data.
JSONArray arr = new JSONArray(strServerResponse);
JSONObject jsonObj = arr.getJSONObject(0);
for (int i = 0; i < arr.length(); i++) {
pojo = new Pojo();
JSONObject jobj2 = arr.getJSONObject(i);
String tipoftheday = jobj2.optString("tipsoftheday");
ArrayList<String> tii = new ArrayList<String>();
tii.add(tipoftheday);
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
for (int i1 = 0; i1 < tii.size(); i1++) {
editor.putString("tipoftheday", TextUtils.join(",", tii));
editor.commit();
}
}
below is the code to retrieve data from shared preferences and using setter to set the d
ata retrieved from shared preferences and adding it to list view adapter. i am not getting what is the mistake.
SharedPreferences prefs=getSharedPreferences("MyPref", MODE_PRIVATE);
String serialized = prefs.getString("tipoftheday", null);
List<String> list = Arrays.asList(TextUtils.split(serialized,","));
for(int i=0; i < list.size(); i++){
String ttt = list.get(i);
pojo.setTip(ttt);
tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
tips.add(pojo);
listTips.setAdapter(tipsAdapter);
}
How to save data in shared preferences? I am getting only one value.
how to save data in shared prefernces. i am getting only one value.
Problem is not related to SharedPreferences it is related to data-source which is currently setting inside for-loop.
Set Adapter as:
for(int i=0; i < list.size(); i++){
String ttt = list.get(i);
pojo.setTip(ttt);
tips.add(pojo);
}
tipsAdapter = new TipsAdapter(TipsActivity.this, tips);
listTips.setAdapter(tipsAdapter);
Try this:
It will work:
To store data:
StringBuilder sb = new StringBuilder();
JSONArray arr = new JSONArray(strServerResponse);
JSONObject jsonObj = arr.getJSONObject(0);
for (int i = 0; i < arr.length(); i++)
{
pojo = new Pojo();
JSONObject jobj2 = arr.getJSONObject(i);
String tipoftheday = jobj2.optString("tipsoftheday");
sb.append(tipoftheday).append(",");
}
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
editor.putString("tipoftheday", sb).commit();
To retrieve data:
String[] strArr = getSharedPreferences("MyPref", MODE_PRIVATE).getString("tipsoftheday").split(",");
You are using two for loop when you are adding values to SharedPreference. Move out the inner loop and your code will be good to get you all values of list. Add some more line to it like below code:
for (int i = 0; i < arr.length(); i++) {
pojo = new Pojo();
JSONObject jobj2 = arr.getJSONObject(i);
String tipoftheday = jobj2.optString("tipsoftheday");
ArrayList<String> tii = new ArrayList<String>();
tii.add(tipoftheday);
}
for (int i1 = 0; i1 < tii.size(); i1++) {
SharedPreferences.Editor editor = getSharedPreferences("MyPref", MODE_PRIVATE).edit();
SharedPreferences prefs=getSharedPreferences("MyPref", MODE_PRIVATE);
StringBuffer stringBuffer = new StringBuffer();
stringBuffer = prefs.getString("tipoftheday", null).toString();
editor.putString("tipoftheday", stringBuffer.append(stringBuffer +",", tii.get(i1).toString()));
editor.commit();
}
You are losing your previous values because you are updating the same key inside your SharedPreferences.Editor. What you have to do in order to add more information afterwards is to first retreive your String value, then add your information and finally store all the info inside your SharedPreferences.Editor.
EDIT
I think it should be something like this, I have done it without any IDE or compiler, so it may have some syntax mistakes :)
SharedPreferences prefs=getSharedPreferences("MyPref", MODE_PRIVATE);
String serialized = prefs.getString("tipoftheday", null);
List<String> list;
if(serialized != null)
list = Arrays.asList(TextUtils.split(serialized,","));
list .add(tipoftheday);
SharedPreferences.Editor editor = prefs.edit();
for (int i1 = 0; i1 < tii.size(); i1++) {
editor.putString("tipoftheday", TextUtils.join(",", list));
editor.apply(); // if you do not need the return value, apply is faster than commit
}
Hope it helps
EDIT 2
Check also ρяσѕρєя K answer, he has spotted a different mistake you are making :)

Save the LinkedHashMap variables in to shared preferences in android

I was struck up with an issue, I would like to save the linkedhashmap variables in the shared preferences and my code is here..
public static LinkedHashMap<String, AppVariable> GlobalAppVariables;
if (Constants.DEVICE_ID == 0) {
String accounts_service = serverSync.getCentralServer(this,serial_number);
if (accounts_service != null){
Constants.MACHINE_CENTRAL_SERVER = accounts_service;
}
Constants.REGISTER_DEVICE_SERVICE = String.format("%sCommon/RegisterMachine", Constants.MACHINE_CENTRAL_SERVER);
GlobalAppVariables = serverSync.registerDevice(this, serial_number);
}
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
SharedPreferences.Editor editor= sharedPref.edit();
editor.putString("name", GlobalAppVariables.toString());
editor.commit();
SharedPreferences sharedPref1= getSharedPreferences("mypref", 0);
LinkedHashMap<String, AppVariable> reqVariables= sharedPref1.getString("name", "");
Now my issue is I would like to save the globalappvariables in shared preferences and use the same variables i.e reqVariables when wifi is not available because globalappvariables will be available only when net is available i.e from
GlobalAppVariables = serverSync.registerDevice(this, serial_number);
When I build the code like above, i am getting the issue
The method putString(String, String) in the type SharedPreferences.Editor is not applicable for the arguments (String, LinkedHashMap<String,AppVariable>)
So please suggest me how to save the appvariables. Hoping the issue is understandable . Thanks in advance.
You can not save a HashMap in to SharedPrefernces in android.
So i think you can do this via a trick,example: you will save all keys of hashmap as String[] & all value as String[]
// Try this way,hope this will help you to solve your problem...
HashMap<String,String> map = new HashMap<String, String>();
map.put("name","ANC");
map.put("address","XYZ");
map.put("age","20");
map.put("phone","123456");
// Set SharedPreferences
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
String keys="";
Iterator<String> itr = map.keySet().iterator();
while (itr.hasNext()) {
String key = itr.next();
SharedPreferences.Editor editor= sharedPref.edit();
editor.putString(key,map.get(key));
editor.commit();
keys += itr.next()+",";
}
keys = keys.substring(0,keys.length()-1);
SharedPreferences.Editor editor= sharedPref.edit();
editor.putString("keys",keys);
editor.commit();
// Get SharedPreferences
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
String[] keysArray = sharedPref.getString("keys","").split(",");
for (int i=0;i<keysArray.length;i++){
System.out.println("Key : "+keysArray[i]+" Value : "+sharedPref.getString(keysArray[i],""));
}
Put ur map into list :
for example :
LinkedHashMap < String, String > map
List < String > keyList;
List < String > valueList;
map.keySet();
map.values();
List<String> keyList = new ArrayList<String>(map.keySet());
List<String> valueList = new ArrayList<String>(map.values());
get array from ur list :
String[] MyArr = new String[My_list.size()];
MyArr = My_list.toArray(MyArr);
and then save array into ur sharedpreferences.
Save Array:
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
Load array :
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
If you don't want to code a lot, then just download Gson.
Here is the sketch:
private Type entityType = new TypeToken<LinkedHashMap<String, AppVariable>>(){}.getType();
private void save(LinkedHashMap<String, AppVariable> map){
Gson gson = new Gson();
String data = gson.toJson(map, entityType);
getSharedPreferences("mypref", 0)
.edit()
.putString("name", data)
.commit();
}
private LinkedHashMap<String, AppVariable> load(){
Gson gson = new Gson();
String data = getSharedPreferences("mypref", 0).getString("name", "");
return gson.fromJson(data, entityType);
}

SharedPreferences not storing value

Hi guys I have got a String I am trying to store in to SharedPreferences:
here is the method I am using to store the string:
global vars:
private ArrayList<String> mListEmailAddresses;
method:
public void setEmailAddressList(String emailAddress){
emailAddress.replaceAll(",", "");
mListEmailAddresses.add(emailAddress);
SharedPreferences prefs = getSharedPreferences("invitefriends", 0);
StringBuilder str = new StringBuilder();
for (int i = 0; i < mListEmailAddresses.size(); i++) {
str.append(mListEmailAddresses.get(i).toString()).append(",");
}
LogUtils.log("emails: " + str.toString());
String theString = str.toString();
prefs.edit().putString("emails", theString);
prefs.edit().commit();
}
everytime this method is called the str.toString method is updated with a new email added to the list. for example "email1#gmail.com,email2#yahoo.co.uk,email3#hotmail.co.uk" would be the string that gets formed. the Log shows this string correctly. I then go to put theString under the key "emails" and whenever the view is restarted it is refreshed like so:
SharedPreferences prefs = getSharedPreferences("invitefriends", 0);
String savedString = prefs.getString("emails", "");
LogUtils.log("saved emails: " + savedString);
StringTokenizer st = new StringTokenizer(savedString, ",");
mListEmailAddresses = new ArrayList<String>();
for (int i = 0; i < st.countTokens(); i++) {
String strEmail = st.nextToken().toString();
mListEmailAddresses.add(strEmail);
}
The problem is that the Log here shows the saved emails is an empty string. What am I doing wrong? Thanks guys.
You are making the commit on an other instance of the editor. Try the following code
SharedPreferences.Editor editor = prefs.edit();
editor.putString("emails", theString);
editor.commit();

android array from shared preferences

I'm trying to iterate over a collection of shared preferences, and generate an ArrayList of HashMaps, but having an issue.
SharedPreferences settings = getSharedPreferences(pref, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
and then I was thinking something along the lines of:
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
SharedPreferences settings = getSharedPreferences(pref, 0);
Map<String, ?> items = settings.getAll();
for(String s : items.keySet()){
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("key", s);
temp.put("value", items.get(s));
LIST.add(temp);
}
This gives the following error:
The method put(String, String) in the type HashMap<String,String> is not applicable for the arguments (String, capture#5-of ?)
Is there a better way to do this?
Hache had the correct idea. An Object is not a String, so .toString() was necessary.
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
SharedPreferences settings = getSharedPreferences(pref, 0);
Map<String, ?> items = settings.getAll();
for(String s : items.keySet()){
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("key", s);
temp.put("value", items.get(s).toString());
LIST.add(temp);
}
Change
HashMap<String,String> temp = new HashMap<String,String>();
final ArrayList<HashMap<String,String>> LIST = new ArrayList<HashMap<String,String>>();
to
HashMap<String,?> temp = new HashMap<String,?>();
final ArrayList<HashMap<String,?>> LIST = new ArrayList<HashMap<String,?>>();
and it should work. You're not putting an String but an object this causes the error

Categories

Resources