【发布时间】:2015-09-03 17:27:11
【问题描述】:
我有两个活动。我将数组列表从第二个活动传递到第一个活动。在第一个活动中,将数组列表转换为字符串数组。现在我想用共享首选项保存这个字符串数组,但我不能这样做。
传递数组列表的第二个活动代码
Intent i = new Intent();
//Bundle extra = new Bundle();
//i.putStringArrayList("array",h);
i.putStringArrayListExtra("array", h);
//i.putExtras(extra);
setResult(RESULT_OK,i);
finish();
获取此结果的第一个活动代码
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();
}
}
}
}
我在使用这段代码时遇到了麻烦,因为当我尝试这段代码时,只有第一种语法开始执行,其他两种语法保持原样,Toast 显示空值。共享首选项也无法保存 String-Builder 变量 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();
}
当onActivityResult 收到结果时,我想将此字符串数组存储在共享首选项中。但我不知道它如何在loop 中处理多种语法。
任何人都可以将这个字符串数组存储在我的共享偏好中。提前谢谢你。
【问题讨论】:
-
第一种语法和第二种语法是什么意思??
-
@Clairvoyant 我的意思是,这是 for 循环中的第一个语法
imagepathb.append(al[i]).append(",");。这是第二个语法Toast.makeText(getApplicationContext(), "This is image path : "+ imagepathb, Toast.LENGTH_LONG).show();当我只运行第一个字符串生成器变量imagepatb可以存储 tamperory 的值,但 toast 不能显示imagepathb的值 -
@Clairvoyant 当我只执行
System.out.println(imagepathb);或Toast with imagepathb变量输出 toast 消息显示完美。但是当尝试使用共享首选项保存此字符串数组时,它仅显示 toast 并且共享首选项变量保持为空(原样)。 -
将
sharedpreference行放在循环之后。 -
@Clairvoyant 我也试过这个,它显示空吐司消息。
标签: android arrays arraylist sharedpreferences onactivityresult