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.
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:
when load, you can convert it back to ArrayList:
another approach is to store several values with different names:
when loading you have to check until you get a null value;
And for last, you can store it comma separated:
When loading, you can use String.split to get array back