0

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.

mahesh
  • 147
  • 12
  • What do you mean by first syntax and second syntax?? – Pankaj Jun 18 '15 at 07:41
  • @Clairvoyant i mean, this is first syntax `imagepathb.append(al[i]).append(",");` in for loop. and this is second syntax `Toast.makeText(getApplicationContext(), "This is image path : "+ imagepathb, Toast.LENGTH_LONG).show();` when i run only first string builder variable `imagepatb` can store value for tamperory, but toast can not display value of `imagepathb` – mahesh Jun 18 '15 at 07:45
  • @Clairvoyant when i execute only `System.out.println(imagepathb);` or `Toast with imagepathb` variable output toast message display perfect. but when try to save this string array with shared preference it display only toast and share preference variable remain null(as it is). – mahesh Jun 18 '15 at 07:48
  • Put `sharedpreference` line outside after the loop. – Pankaj Jun 18 '15 at 07:48
  • @Clairvoyant i also have try this and it's display null toast mesage. – mahesh Jun 18 '15 at 07:53
  • Can you edit your code and show me how you changed it – Pankaj Jun 18 '15 at 07:55
  • @Clairvoyant i have edited my code. just put sharerpreference outside for loop. – mahesh Jun 18 '15 at 08:04
  • If you make a toast outside of loop then can you see imagepathb data – Pankaj Jun 18 '15 at 08:07
  • @Clairvoyant No i can't see toast outside loop. imagepathb data display null. – mahesh Jun 18 '15 at 08:14
  • If you put sharedpreference inside your loop it will override your data. And string builder in loop is also overriding that's why you are getting single data entry. – Pankaj Jun 18 '15 at 08:17
  • @Clairvoyant I try to save its outside try and catch but it's still null. Now I think, i should try with DB. – mahesh Jun 18 '15 at 08:23
  • You need to put logic to save in sharedPreference first get data from shared prefernece and use a string builder to append the new data with old shared preference data in loop not outside of loop – Pankaj Jun 18 '15 at 08:25
  • @Clairvoyant yes i am trying this. thank you for take time for me. – mahesh Jun 18 '15 at 08:32
  • @Clairvoyant Hey, i have done this. with split. first get string from shared preference using `sheredpreference.getString("imagepathb","")` and save it in `String ab`. After this i have add split(";") like this `String[] array = ab.split(",");` and run with for loop and its display all image path. – mahesh Jun 18 '15 at 09:06
  • That's what i have already told you to do and you have used split too – Pankaj Jun 18 '15 at 09:29
  • @Clairvoyant yes, thanks again. – mahesh Jun 19 '15 at 08:05
  • I am here to help, thats it. – Pankaj Jun 19 '15 at 08:09
  • @Clairvoyant can you help me [on this question](http://stackoverflow.com/questions/30961325/how-to-update-first-and-second-page-view-in-view-pager).? – mahesh Jun 21 '15 at 04:43

2 Answers2

1

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(',');
AterLux
  • 4,566
  • 2
  • 10
  • 13
  • 1
    @peter Just one things you missed in first code. you don's save it with `commit();` without commit() it is work like only simple variable . – mahesh Jun 20 '15 at 03:49
0

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!

Community
  • 1
  • 1
  • @peter can you tell me how can i convert array-list to `set`.? Because i am passing array-list in first activity. – mahesh Jun 18 '15 at 07:58
  • Click in the hyperlink (post word) if you want to see the post, and if you want to pass array list from activity to another one then you need to find documentation about bundles! – Merlí Escarpenter Pérez Jun 18 '15 at 08:00
  • @peter can you help me [on this question](http://stackoverflow.com/questions/30961325/how-to-update-first-and-second-page-view-in-view-pager) – mahesh Jun 21 '15 at 04:44