【问题标题】:How to compare json objects and get particular json object inside json array in Java Android? [closed]如何比较 json 对象并在 Java Android 中的 json 数组中获取特定的 json 对象? [关闭]
【发布时间】: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


【解决方案1】:

您只得到一个值,因为您在for 循环的第一次迭代中关闭了首选项。在其他迭代中,没有数据被保存。

你需要放

editor.commit();

在 for 循环之外(循环之后)。

【讨论】:

  • 但它仍然只显示一个图片网址
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2018-05-03
  • 2019-08-01
  • 2015-07-18
  • 1970-01-01
相关资源
最近更新 更多