android array from shared preferences - android

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

Related

How to get Hashmap Data

I had seen many examples regarding Hashmap Data but I am not getting the data as required.
Here is my code:
HashMap<String,ArrayList<String>> citylist = new HashMap<String, ArrayList<String>>();
ArrayList<String> Gujarat = new ArrayList<String>();
Gujarat.add("Surat");
Gujarat.add("Baroda");
Gujarat.add("Ahmedabad");
ArrayList<String> Rajasthan = new ArrayList<String>();
Rajasthan.add("Udaipur");
Rajasthan.add("Jaipur");
ArrayList<String> UP= new ArrayList<String>();
UP.add("Lucknow");
UP.add("Agra");
citylist.put("Gujarat", Gujarat);
citylist.put("UP", UP);
citylist.put("Rajasthan", Rajasthan);
It is in recyclerview how to get this type of data in BindViewHolder?
Toast is coming like:
{Rajasthan=[Udaipur, Jaipur], UP=[Lucknow, Agra], Gujarat=[Surat, Baroda, Ahmedabad]}
I had used this method to get but error is coming:
public void onBindViewHolder(MyViewHolder holder, int position) {
ArrayList<String> lst = citylist.get("" + position);
for (Integer i = 0; i < lst.size(); i++) {
holder.tv.setText(citylist.toString());
Log.e("Hashmap....", ""+holder.tv );
}
the output should be like Gujarat is state and surat baroda and ahmedabad are cities?
First create one ArrayList with all state :
ArrayList<String> stateList = new ArrayList<String>();
stateList.add("Gujarat");
stateList.add("UP");
stateList.add("Rajasthan");
Second create one HashMap with each state name as Key and each state city as Value:
HashMap<String,ArrayList<String>> stateCityMap = new HashMap<String,ArrayList<String>>()
ArrayList<String> gujaratCityList = new ArrayList<String>();
gujaratCityList.add("Ahmedabad");
gujaratCityList.add("Surat");
gujaratCityList.add("Baroda");
.......................
ArrayList<String> upCityList = new ArrayList<String>();
upCityList.add("Lucknow");
upCityList.add("Agra");
..........................
ArrayList<String> rajasthanCityList = new ArrayList<String>();
rajasthanCityList.add("Udaipur");
rajasthanCityList.add("Jaipur");
...........................
stateCityMap.put("Gujarat",gujaratCityList);
stateCityMap.put("UP",upCityList);
stateCityMap.put("Rajasthan",rajasthanCityList);
Now get all city name based on state in Adapter :
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.e("State : ",stateList.get(position));
ArrayList<String> cityList= (ArrayList<String>)stateCityMap.get(stateList.get(position));
for(String cityName : cityList){
Log.e("City : ",cityName);
}
}
you can get like below.
Iterator iterator = map.keySet().iterator();
while(iterator.hasNext()) {
String key=(String)iterator.next();
String value=(String)map.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
HashMaps do not preserve ordering:
This class makes no guarantees as to the order of the map; in
particular, it does not guarantee that the order will remain constant
over time.
Take a look at LinkedHashMap, which guarantees a predictable iteration order.
You might wanna try something like this.
for (Map.Entry<String, ArrayList<String>> entry : citylist.entrySet())
{
String key = entry.getKey(); // Your State
String value = entry.getValue(); // Your List of Cities.
// Split data and insert in Views
}
However I recommend (for easy to use case) keep a List of all the states and get Value from HashMap using keys from this List of states.
Please check it :
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> h1 = new HashMap<String, String>();
h1.put("h1_key_1", "h1_value_1");
h1.put("h1_key_2", "h1_value_2");
arrayList.add(h1);
for (HashMap<String, String> hashMap : arrayList) {
System.out.println(hashMap.keySet());
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
}
}
Try This:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}

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

How to Convert ArrayList<HashMap<String, String>> to a StringArray?

I want to store a String array in the database, but I got values from another activity as an ArrayList<Hashmap<String, String>>. How should I convert this ArrayList into a String array?
Code:
HashMap <String, String> h1 = new HashMap <String, String> ();
h1.put("member_id", member_id);
h1.put("categoryname", category_name);
h1.put("routinetype", routine_type);
h1.put("targettype", target_type);
h1.put("days", countOfDays);
h1.put("point", points);
h1.put("daystring", listOfDayString);
h1.put("create_date", strDate);
arrayList1.add(h1);
Simply use:
String[] strArray = new String[urArrayList.size()];
strArray = urArrayList.toArray(strArray);
EDIT:
Then you can simply use this:
int i = 0;
String strArr[] = new String[urArrayList.size()];
for (HashMap<String, String> hashMap : urArrayList) {
for (String value : hashMap.values()) {
strArr[i] = value ;
i++;
}
}

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

Android: Sort data retrieved from SharedPreferences

I am trying to store data in Android. I am using the SharedPreferences. And I am retrieving these data by using:
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
Map<String, ?> keys = myPrefs.getAll();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
Log.i("map values", entry.getKey());
//some code
}
EDIT:
But data retrieved are not in the same order as they were inserted. How to get the same order?
Copy the resulting Map into an implementation of SortedMap, e.g. TreeMap.
Like this (sort by key):
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
TreeMap<String, ?> keys = new TreeMap<String, Object>(myPrefs.getAll());
for (Map.Entry<String, ?> entry : keys.entrySet()) {
Log.i("map values", entry.getKey());
//some code
}
To sort by value & not lose any key-value pairs (since a Map will readily allow duplicate values mapping to different keys) you'd need to first convert it into
a List and sort that.
List<Pair<Object, String>> sortedByValue = new LinkedList<Pair<Object,String>>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
Pair<Object, String> e = new Pair<Object, String>(entry.getValue(), entry.getKey());
sortedByValue.add(e);
}
// Pair doesn't have a comparator, so you're going to need to write one.
Collections.sort(sortedByValue, new Comparator<Pair<Object, String>>() {
public int compare(Pair<Object, String> lhs, Pair<Object, String> rhs) {
// This is a naive and shitty comparator, but it works for
// arbitrary objects. Sort of. Tweak depending on the order you need.
String sls = String.valueOf(lhs.first);
String srs = String.valueOf(rhs.first);
int res = sls.compareTo(srs);
// Sort on value first, key second
return res == 0 ? lhs.second.compareTo(rhs.second) : res;
}
});
for (Pair<Object, String> pair : sortedByValue) {
Log.i("map values", pair.first + "/" + pair.second);
}
Add a property with the order, like so...
First save the settings...
public static void saveSettings(final Editor editor, final String [] order) {
final String csl = toString(order);//comma separated
editor.putString("insert_order", csl);
for (int i = 0; i < values.length; i++) {
editor.putString(values[i], your_value[i]);
}
}
Now load them:
public static List<String> loadSetting(final SharedPreferences preferences) {
final List<String> inOrder = new ArrayList<>();
final String[] ordering = preferences.getString("insert_order", "").split(",");
for (final String item : ordering) {
final String value = (String) preferences.getString(item, "");
inOrder.add(value);
}
return inOrder;
}

Categories

Resources