How to store string array (which is converted from array list <string> to string array) in shared preference.?

968 views Asked by At

I Have two activities. I am passing array list from second activity to first activity. In first activity convert array list to string array. now i want to save this string array with shared preference but i can't do that.

second activity code to pass array list

                Intent i = new Intent();
                //Bundle extra = new Bundle();
                //i.putStringArrayList("array",h);
                i.putStringArrayListExtra("array", h);
                //i.putExtras(extra);
                setResult(RESULT_OK,i);
                finish();

First activity code to get this result

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{

if(requestCode == 1){

    if(resultCode == RESULT_OK){

    //  Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_SHORT).show();
        File imgFile = null;
        Bundle extras = data.getExtras();

        a= extras.getStringArrayList("array");
        try{
        al = new String[a.size()];
        al = a.toArray(al);

        //for(String ss : al)             
              for(int i = 0; i < al.length; i++){
                  imagepathb.append(al[i]).append(",");

              } 
         }
         sharedpreferences.edit().putString("imgpath",imagepathb.tostring()).commit();                            catch(Exception e){

                  }

        if(ab != null){
            ab =  sharedpreferences.getString("imgpath", ab);
          Toast.makeText(getApplicationContext(), "This is ab image path : "+ ab, Toast.LENGTH_LONG).show();    
        }else{
            Toast.makeText(getApplicationContext(), "This is null", Toast.LENGTH_LONG).show();              
        }


    }

   }
}

i have trouble by using this code, because when i am trying this code, execution start for only first syntax other two syntax remain as it is and Toast display null value. Also shared preference can not save value of String-Builder variable imagepathb.

  for(int i = 0; i < al.length; i++){

     imagepathb.append(al[i]).append(",");
     Toast.makeText(getApplicationContext(), "This is image path : "+ imagepathb, Toast.LENGTH_LONG).show();        
     sharedpreferences.edit().putString("imgpath",imagepathb.tostring()).commit();                    

  } 

i want to store this string array in shared preference when result received in onActivityResult. But I don't know how its work for multiple syntax in loop. Any one can store this string array in shared preference for me. thank you in advance.

2

There are 2 answers

1
AterLux On

First, if all the strings in your ArrayList are known to be unique (i.e. no duplicates), you can convert your ArrayList to a Set and store it, using the putStringSet() method:

sharedpreferences.edit().putStringSet("imgpath", new HashSet<String>(a)).commit();

when load, you can convert it back to ArrayList:

ArrayList<String> myList = 
      new ArrayList<>(sharedpreferences.getStringSet("imgpath", new HashSet<String>()));

another approach is to store several values with different names:

Edit edit = sharedpreferences.edit();
int cnt = 0;
for (String s : a) 
   edit.putString("imgpath_" + (cnt++), s);
while (sharedpreferences.getString("imgpath_" + cnt, null) != null) {
  edit.remove("imgpath_" + cnt); // delete all extra values from previous save time;
  cnt++;
}
edit.commit();

when loading you have to check until you get a null value;

ArrayList<String> a = new ArrayList<>();
for(int cnt = 0;; cnt++) {
   String s = sharedpreferences.getString("imgpath_" + cnt, null);
   if (s == null) break;
   a.add(s);
}

And for last, you can store it comma separated:

StringBuilder sb = new StringBuilder();
for (String s : a) {
    is (sb.length() > 0) sb.append(',');
   sb.append(s);
}
sharedpreferences.edit().putString("imgpath",sb.tostring()).commit();                    

When loading, you can use String.split to get array back

String[] al = sharedPreferences.getString("imgpath", "").split(',');
3
Merlí Escarpenter Pérez On

I think the best way is save it in database, the shared preferences is good to save variables of user conexion (users, passwords,...), initial variables, etc... But no to save array list, it's not a good programming practice! I know too you can't save array list as array list but if as Sets, you can see this post.

Tell me if I helped you and good programming!