Save the LinkedHashMap variables in to shared preferences in android - 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);
}

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

not getting data from shared preferences

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

Save SparseBooleanArray to SharedPreferences

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

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: How to store array of strings in SharedPreferences for android

I'm building an app which searches the web using search engine. I have one edittext in my app from which user will search the web. I want to save the search keywords just like browser history does. I'm able to save and display it with the last keyword but I can't increase the number of searches result. I want to display the last 5 searhes. Here is my code :
public class MainActivity extends Activity implements OnClickListener {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
txt1.setOnClickListener(this);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((edt.getText().toString().equals(""))) {
Toast.makeText(
getBaseContext(),
"Whoa! You haven't entered anything in the search box.",
Toast.LENGTH_SHORT).show();
} else {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
public void onClick(View v) {
String text = txt1.getText().toString();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT).show();
}
}
Please help me in overcoming this problem.
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;
}
Convert your array or object to Json with Gson library and store your data as String in json format.
Save;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
Original answer: Storing Array List Object in SharedPreferences

Categories

Resources