【发布时间】:2016-01-19 09:20:10
【问题描述】:
JSON 数组
[{
"status": "dummy text",
"statusId": 3,
"Imgstatus": "http://7-themes.com/data_images/out/40/6907072-flowers-abstract-backgrounds.jpg"
},
{
"status": "example text",
"statusId": 5,
"Imgstatus": "http://www.wallmuu.com/top/wallfile/flowers-background-high-definition-beautiful.jpg"
},
{
"status": "sample text",
"statusId": 4,
"Imgstatus": "http://www.twitterevolutions.com/bgs/flowers-and-swirls-twitter-background.jpg"
}]
如何根据上述JsonArray 中的"statusId" 键从"ImgStatus" 键中获取图像网址,并将每个图像网址保存在单独的SharedPreference 中?
我在这里尝试过,但它工作正常。谁能帮帮我?
SharedPreferences sp = (SharedPreferences)getSharedPreferences("MYPREF",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
for (int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String statusID = jsonObject1.getString("statusId");
String imgUrls = jsonObject1.getString("Imgstatus");
if (statusID.toString().equals("3")){
editor.putString("IMG_1", imgUrls);
}
if (statusID.toString().equals("4")){
editor.putString("IMG_2", imgUrls);
}
if (statusID.toString().equals("5")){
editor.putString("IMG_3", imgUrls);
}
editor.commit();
}
SharedPreferences sharedPreferences = (SharedPreferences)getSharedPreferences("MYPREF", Context.MODE_PRIVATE);
String img1 = sharedPreferences.getString("IMG_1", "");
String img2 = sharedPreferences.getString("IMG_2", "");
String img3 = sharedPreferences.getString("IMG_3", "");
Log.d(">> Sharedpref img values : ", img1+"\n"+img2+"\n"+img3);
【问题讨论】:
-
什么不起作用。您的查询非常不清楚。
-
您的字符串转换对我来说似乎很奇怪。您是否尝试过
int statusID = jsonObject1.getInt("statusId");然后if (statusID == 3)而不是多个字符串转换? -
请发布 logcat !
-
@Rohit5k2,它只显示一个图片网址......我正在尝试的是,显示所有三个图片网址
-
@Rohit5k2 是的,我只是拆分,所有三个图像作为一个单独的字段,这就是我想要的。但它不是那样的:(
标签: java android json sharedpreferences