Shared Preference multiple string set issue - android

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

Related

I am trying to pass the values in shared preference from one Activity to another

I am trying to pass the values from one activity to another using shared preference but am getting null value.In the first activity i printed values in console and its getting printed but in that i couldn't retrieve the values.please help me to come out of this error
First activity: values are passed
sharedpreferences.edit().putString("CHECKPASS","changepass").commit();
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
Second Activity: where I am retrieving
Log.d("succ", "reached");
String yourpass = sharedpreferences.getString("CHECKPASS","changepass");
Log.d("succ", "yournext" + yourpass);
if (yourpass.equals("changepass")) {
{
final String foodshared = sharedpreferences.getString("FOOD","NULL");
Log.d("succ", "foodshared" + foodshared);
final String colorshared = sharedpreferences.getString("COLOR", "NULL");
Log.d("succ", "colorshared" + colorshared);
final String buyshared = sharedpreferences.getString("BUY", "NULL");
Log.d("succ", "buyshared" + buyshared);
final String placeshared = sharedpreferences.getString("PLACE", "NULL");
Log.d("succ", "placeshared" + placeshared);
}
Use this code
//For writing data
SharedPreferences.Editor
editor=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE).edit();
editor.putString("CHECKPASS","changepass");
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.apply();
//For Reading Data
SharedPreferences sharedPreferences=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE);
String foodshared = sharedPreferences.getString("FOOD","NULL");
String colorshared = sharedPreferences.getString("COLOR", "NULL");
final String buyshared = sharedPreferences.getString("BUY", "NULL");
final String placeshared = sharedPreferences.getString("PLACE", "NULL");
Also while writing data don't use editor.commit() instead use editor.apply() because it handles data in background.
UPDATE:
in your first activity
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);//or MODE_PRIVATE
Editor editor = pref.edit();
editor.putString("CHECKPASS","changepass")
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
IN your secondActivity
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
final String foodshared = pref.getString("FOOD",null);
Log.d("succ", "foodshared" + foodshared);
final String colorshared = pref.getString("COLOR",null);
Log.d("succ", "colorshared" + colorshared);
final String buyshared = pref.getString("BUY",null);
Log.d("succ", "buyshared" + buyshared);
final String placeshared = pref.getString("PLACE",null);
Log.d("succ", "placeshared" + placeshared);
edit:
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
STORE THE DATA
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getBoolean("key_name", null); // getting boolean

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 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: 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