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 :)
Related
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
For my app, I need to save a simple SparseBooleanArray to memory and read it later.
Is there any way to save it using SharedPreferences?
I considered using an SQLite database but it seemed overkill for something as simple as this. Some other answers I found on StackOverflow suggested using GSON for saving it as a String but I need to keep this app very light and fast in file size. Is there any way of achieving this without relying on a third party library and while maintaining good performance?
You can use the power of JSON to save in the shared preferences for any type of object
For example SparseIntArray
Save items like Json string
public static void saveArrayPref(Context context, String prefKey, SparseIntArray intDict) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
JSONArray json = new JSONArray();
StringBuffer data = new StringBuffer().append("[");
for(int i = 0; i < intDict.size(); i++) {
data.append("{")
.append("\"key\": ")
.append(intDict.keyAt(i)).append(",")
.append("\"order\": ")
.append(intDict.valueAt(i))
.append("},");
json.put(data);
}
data.append("]");
editor.putString(prefKey, intDict.size() == 0 ? null : data.toString());
editor.commit();
}
and read json string
public static SparseIntArray getArrayPref(Context context, String prefKey) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String json = prefs.getString(prefKey, null);
SparseIntArray intDict = new SparseIntArray();
if (json != null) {
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
intDict.put(item.getInt("key"), item.getInt("order"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return intDict;
}
and use like this:
SparseIntArray myKeyList = new SparseIntArray();
...
//write list
saveArrayPref(getApplicationContext(),"MyList", myKeyList);
...
//read list
myKeyList = getArrayPref(getApplicationContext(), "MyList");
Write the values separately, and keep a list of the names of the values you write:
SparseBooleanArray array = //your array;
SharedPreferences prefs = //your preferences
//write
SharedPreferences.Editor edit = prefs.edit();
Set<String> keys = new HashSet<String>(array.size());
for(int i = 0, z = array.size(); i < z; ++i) {
int key = array.keyAt(i);
keys.add(String.valueOf(key));
edit.putBoolean("key_" + key, array.valueAt(i));
}
edit.putStringSet("keys", keys);
edit.commit();
//read
Set<String> set = prefs.getStringSet("keys", null);
if(set != null && !set.isEmpty()) {
for (String key : set) {
int k = Integer.parseInt(key);
array.put(k, prefs.getBoolean("key_"+key, false));
}
}
String sets are supported since API 11.
You could instead build a single csv string and split that rather than storing the set.
You can serialize the object to a byte array and then probably base64 the byte array before saving to SharedPreferences. Object serialization is really easy, you don't need a third party library for that.
public static byte[] serialize(Object obj) {
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
ObjectOutputStream objectOS = new ObjectOutputStream(byteArrayOS);
objectOS.writeObject(obj);
objectOS.flush();
return byteArrayOS.toByteArray();
}
public static Object deserialize(byte[] data) {
ByteArrayInputStream byteArrayIS = new ByteArrayInputStream(data);
ObjectInputStream objectIS = new ObjectInputStream(byteArrayIS);
return objectIS.readObject();
}
The code above doesn't have try catch block for simplicity. You can add it on your own.
I have been doing this as the following by using Gson
To save sparseboolean array in SharedPreference:
public void SaveSparseBoolean() {
SparseBooleanArray booleanArray = new SparseBooleanArray();
SharedPreferences sP;
sP=context.getSharedPreferences("MY_APPS_PREF",Context.MODE_PRIVATE)
SharedPreferences.Editor editor=sP.edit();
Gson gson=new Gson();
editor.putString("Sparse_Array",gson.toJson(booleanArray));
editor.commit();
}
To get the SparsebooleanArray from SharedPreferences
public SparseBooleanArray getSparseArray() {
SparseBooleanArray booleanArray;
SharedPreferences sP;
sP = context.getSharedPreferences("MY_APPS_PREF", Context.MODE_PRIVATE);
Gson gson=new Gson();
booleanArray=gson.fromJson(sP.getString("Sparse_Array",""),SparseBooleanArray.class);
return booleanArray;
}
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();
how to get value from shared preferences and save it array list
I want to get the string from shared preferences so that i want save that string to array list
SharedPreferences keyValues = context.getSharedPreferences("name_icons_list", context.MODE_PRIVATE);
if(keyValues.getString(""+str,"").equals("true"))
{
holder.tb1.setChecked(true);
onApps.add(str);
System.out.println("Block appp+++++"+onApps);
System.out.println("******************************************");
System.out.println("data retrive from database"+ position);
System.out.println("******************************************");
}
You may use this code to save preference in arraylist and vice versa
public String[] getApplicationList() { Log.i("test","prefrence getapplist");
return mApplicationList;
}
public void saveApplicationList(String[] applicationList) { Log.i("test","prefrence saveapplist");
mApplicationList = applicationList;
String combined = "";
for (int i=0; i<mApplicationList.length; i++){
combined = combined + mApplicationList[i] + ";";
}
mPref.edit().putString(PREF_APPLICATION_LIST, combined).commit();
}
I believe this should do the trick:
String savedString = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
.getString("name_icons_list", "");
StringTokenizer st = new StringTokenizer(savedString, ",");
int numberOfToken = st.countTokens();
ArrayList<String> arraylist = new ArrayList<String>();
for (int i = 0; i < numberOfToken; i++) {
arraylist.add(st.nextToken());
}
I have a problem with my code,
I have a json array
[{"Response":{"data":"sibin1"}},{"Response":{"data":"sibin2"}},
{"Response": {"data":"sibin3"}}]
And iam trying to extract the json data using the below code,Here i added only some parts of the coode
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
for (int i = 0; i < finalResult.length(); i++)
{
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
System.out.println(result);
}
The code is worked very well
when the value of
i=0 ,result is sibin1
i=1 ,result is sibin2
i=2 ,result is sibin3
But my problem is , i need to store the result in a string array of length finalresultlength inside the given for loop, also i need to print the values in the string array in a for loop outside the given for loop
if anybody knows please help me...........
You could do this way as well.
Create an ArrayList of size 'finalresultlengt' and the add the values in.
list.add(result); // variable 'result' in your case is the value from JSON
If you have more values to be added, create a POJO class.
class POJO {
private String dataVal;
public void setDataVal(String dataVal) {
this.dataVal = dataVal;
}
public String getDataVal() {
return dataVal;
}
}
Then create an ArrayList of type POJO.
ArrayList<POJO> list = new ArrayList<POJO>(finalresultlengt);
EDIT
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
ArrayList<String> list = new ArrayList<String>(finalresultlengt);
for (int i = 0; i < finalResult.length(); i++) {
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
list.add(result);
}
Populate values from ArrayList.
for(String value : list)
System.out.println(value);