如何保存JSON数组SharedPreferences,并在不同的活动再次读取。 Android

2019-10-20 16:13发布

我需要我的JSON数组保存到SharedPreferences,并在不同的活动日后访问。

这里是我的Json的例子:

Array
(
    [status] => success
    [reason] => success
    [version] => 1
    [total] => Array
        (
            [category_1] => 3
            [category_2] => 3
            [category_3] => 3
        )

    [title] => Array
        (
            [category_1] => Food
            [category_2] => Drink
            [category_3] => Dessert
        )

    [data] => Array
        (
            [category_1] => Array
                (
                    [0] => Array
                        (
                            [content_id] => 123456
                            [name] => Name1
                            [title] => This is title one
                            [desc] => This is title description
                            [thumb] => http://image.jpg

                        )

                    [1] => Array
                        (...

                )

            [category_2] => Array
                (
                    [0] => Array
                        (
                            [content_id] => 123456
                            [name] => Name1
                            [title] => This is title one
                            [desc] => This is title description
                            [thumb] => http://image.jpg
                        )

                    [1] => Array
                        (...

                )

            [category_3] => Array
                (
                    [0] => Array
                        (
                            [content_id] => 123456
                            [name] => Name1
                            [title] => This is title one
                            [desc] => This is title description
                            [thumb] => http://image.jpg
                        )

                    [1] => Array
                       ( ...
                )
        )
)

MainActivity:

...
try {

                        JSONObject jObject = new JSONObject(result);
                        String status = jObject.getString("status");

                        if (status.equals("success")) {
                            // Log.e("status",status);

                            JSONObject jObject_data = new JSONObject(jObject.getString("data"));
                            JSONArray jArray_data_category_1 = new JSONArray(jObject_data.getString("category_1"));
                            JSONArray jArray_data_category_2 = new JSONArray(jObject_data.getString("category_2"));
                            //JSONArray jArray_data_category_3 = new JSONArray(jObject_data.getString("category_3"));



                            //Log.e("category_1 *****************************************", jArray_data_category_1.toString());
                            vc.insertCategory_1Pref(jArray_data_category_1.toString()); 

这是我的SharedPrefInput.java:

...
public class SharedPrefInput {

    public static final String CATEGORY_1 = "CATEGORY_1";
    public static final String CATEGORY_2 = "CATEGORY_2";
    public static final String CATEGORY_3 = "CATEGORY_3";

...

这里是VarController

...
//category_1
        public void insertCategory_1Pref(String s){     
            prefSetting = context.getSharedPreferences(SharedPrefInput.DEVICE_SETTING, Context.MODE_PRIVATE);
            prefSettingEditor = prefSetting.edit();
            prefSettingEditor.putString(SharedPrefInput.CATEGORY_1, s);
            prefSettingEditor.commit();
        }

        public String readCategory_1Pref(){     
            prefSetting = context.getSharedPreferences(SharedPrefInput.DEVICE_SETTING, Context.MODE_PRIVATE);
            return prefSetting.getString(SharedPrefInput.CATEGORY_1, "00");
        }
...

这里是我试图访问它。 但它不工作。

 try {
                                    JSONArray jsonArray2 = new JSONArray(sharedCategory_1Pref.getString(CATEGORY_1, status));
                                    for (int i = 0; i < jsonArray2.length(); i++) {
                                         Log.d("your JSON Array", jsonArray2.getInt(i)+"");

                                         Log.e("inside try", "inside try");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Log.e("inside Exception", "inside Exception");
                                }

这是日志当我尝试阅读SharePref:

08-12 09:22:34.757: W/System.err(871):  at org.json.JSON.typeMismatch(JSON.java:96)
08-12 09:22:34.787: W/System.err(871):  at org.json.JSONArray.getInt(JSONArray.java:357)
08-12 09:22:34.787: W/System.err(871):  at com.example.brazilapps.MainActivity$1.onPostExecute(MainActivity.java:158)
08-12 09:22:34.787: W/System.err(871):  at com.example.brazilapps.MainActivity$1.onPostExecute(MainActivity.java:1)
08-12 09:22:34.787: W/System.err(871):  at android.os.AsyncTask.finish(AsyncTask.java:417)
08-12 09:22:34.797: W/System.err(871):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
08-12 09:22:34.797: W/System.err(871):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
08-12 09:22:34.797: W/System.err(871):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-12 09:22:34.808: W/System.err(871):  at android.os.Looper.loop(Looper.java:123)
08-12 09:22:34.808: W/System.err(871):  at android.app.ActivityThread.main(ActivityThread.java:3683)
08-12 09:22:34.818: W/System.err(871):  at java.lang.reflect.Method.invokeNative(Native Method)
08-12 09:22:34.827: W/System.err(871):  at java.lang.reflect.Method.invoke(Method.java:507)
08-12 09:22:34.827: W/System.err(871):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-12 09:22:34.827: W/System.err(871):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-12 09:22:34.867: W/System.err(871):  at dalvik.system.NativeStart.main(Native Method)
08-12 09:22:34.867: E/inside Exception(871): inside Exception

Answer 1:

我想建议你,当你在JSON得到结果转换成字符串

和该字符串存储在共享的偏好作为字符串并使用该线使用该字符串在活动期间使用转换救字符串转换成JSON对象JSONObject obj = new JSONObject(json); 使用这条线转换成JSONObject的字符串

    JSONObject foo = yourJSONOject;
String uid = foo.get("CNo").isString().toString();
String type = foo.get("CName").isString().toString();

或者您可以使用到的toString这样的JSONObject将它转换成字符串



Answer 2:

作为字符串中使用保存JSON JSONArray.toString()使用的SharedPreferences putString()和后来与检索的getString()然后调用新的JSONArray(字符串)



Answer 3:

你为什么要打电话jsonArray2.getInt(i) ,但在我看来,你阵列组成JSONObject S'

尝试jsonArray2.getJSONObject(i)来代替。

此外,这部分代码:

JSONArray jArray_data_category_1 = new JSONArray(jObject_data.getString("category_1"));

可以改写为

JSONArray jArray_data_category_1 = jObject_data.getJSONArray("category_1");


Answer 4:

您的JSON看起来像从API / web服务的响应。

为什么要存储在共享偏好这样的反应呢?

我想,只是为了避免在不同的活动相同的API请求调用?

我建议你实现缓存似的东西。 共享偏好是不是存储此类大串制成。

您也可以在JSON文件存储在文件中您的应用程序的文件夹,并在需要时阅读该文件。 (那是什么呢缓存)。



Answer 5:

Siince你得到的类型不匹配getInt()线,而不是线

Log.d("your JSON Array", jsonArray2.getInt(i)+"");

你可以把它作为字符串并解析它为int。

Log.d("your JSON Array", Integer.parseInt(jsonArray2.getString(i))+"");


文章来源: How to save a JSON array into SharedPreferences and read again in a different activity. Android