如何将json存储在sharedpreference中并逐个在另一个活动中检索它们?

时间:2018-03-13 06:16:33

标签: php android sharedpreferences

我基本上想在这里做的是,我使用php文件从数据库接收数据,我想将它们存储在shearedpreference中,以便以后在另一个活动中使用,

这是我的json

{"NEW_DISPLAY_SCHEDULE":[{"ScheduleDate":"2018-03-01","StartTime":"9:10 am","Endtime":"11:30 am"},{"ScheduleDate":"2018-03-02","StartTime":"2:00 pm","Endtime":"4:00 pm"},{"ScheduleDate":"2018-03-03","StartTime":"5:00 pm","Endtime":"6:00 pm"},{"ScheduleDate":"2018-03-04","StartTime":"2:00 pm","Endtime":"6:00 pm"},{"ScheduleDate":"2018-03-05","StartTime":"RTO","Endtime":""},{"ScheduleDate":"2018-03-06","StartTime":"10:00 am","Endtime":"11:00 pm"},{"ScheduleDate":"2018-03-06","StartTime":"2:00 pm","Endtime":"4:00 pm"},{"ScheduleDate":"2018-03-31","StartTime":"6:00 am","Endtime":"4:00 pm"},{"ScheduleDate":"2018-03-14","StartTime":"7:00 am","Endtime":"4:00 pm"},{"ScheduleDate":"2018-03-28","StartTime":"1:00 pm","Endtime":"4:00 pm"}]}

这是我的android活动,我将它们存储在shearedpreference中,

第一项活动

  SharedPreferences  sp = getSharedPreferences("identifier", Context.MODE_PRIVATE);
        SharedPreferences.Editor Ed= sp.edit();
        Ed.putString("result", result  );
        Ed.commit();

在第二次活动中,我试着像这样收到

    package com.example.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Main2Activity extends AppCompatActivity {

    Context context;
    String jsonarray;
    JSONArray jsonArray;
     private ArrayList<String> ScheduleDateArray=new ArrayList<>();
    int L;
    String[] ScheduleDates,StartTimes,Endtimes;
    String ScheduleDate;
    TextView Dates;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        context = getApplicationContext();
        SharedPreferences  mPrefs = getSharedPreferences("identifier", Context.MODE_PRIVATE);
        jsonarray = mPrefs.getString("result", null);

        try {
            JSONObject jsonObjects = new JSONObject(jsonarray);
            try {
                  jsonArray=jsonObjects.getJSONArray("NEW_DISPLAY_SCHEDULE");
                for (int i=0;i<jsonArray.length();i++){
                    JSONObject jsonObject=jsonArray.getJSONObject(i);

                       ScheduleDate=jsonObject.getString("ScheduleDate");
                    ScheduleDateArray.add(ScheduleDate);

                   // String StartTime=jsonObject.getString("StartTime");
                     //String Endtime=jsonObject.getString("Endtime");
                   // Toast.makeText(Main2Activity.this ,   ScheduleDate+"/"+StartTime+"/"+Endtime, Toast.LENGTH_LONG).show();


                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

for(int i=0;i<=jsonArray.length();i++){

    Toast.makeText(Main2Activity.this ,  "ScheduleDates"+ ScheduleDateArray.get(i), Toast.LENGTH_LONG).show();
}


       // Dates=(TextView)findViewById(R.id.textView);
       // Dates.setText(jsonarray);

    }
}

我的问题是我不知道如何从shearedpreference分离第二个活动中的字符串,应用程序正在关闭,任何人都帮我分开字符串,我想把它们放在吐司。

logcat的

03-13 13:51:50.160 4045-4045/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.example.myapplication, PID: 4045
                                                                     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.Main2Activity}: java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                         at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                      Caused by: java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10
                                                                         at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                                                                         at java.util.ArrayList.get(ArrayList.java:308)
                                                                         at com.example.myapplication.Main2Activity.onCreate(Main2Activity.java:63)
                                                                         at android.app.Activity.performCreate(Activity.java:6251)
                                                                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                         at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                         at android.os.Looper.loop(Looper.java:148) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

1 个答案:

答案 0 :(得分:0)

首先使用jsonobject字符串

创建result
try {
        JSONObject MyObject=new JSONObject("{\"NEW_DISPLAY_SCHEDULE\":[{\"ScheduleDate\":\"2018-03-01\",\"StartTime\":\"9:10 am\",\"Endtime\":\"11:30 am\"},{\"ScheduleDate\":\"2018-03-02\",\"StartTime\":\"2:00 pm\",\"Endtime\":\"4:00 pm\"},{\"ScheduleDate\":\"2018-03-03\",\"StartTime\":\"5:00 pm\",\"Endtime\":\"6:00 pm\"},{\"ScheduleDate\":\"2018-03-04\",\"StartTime\":\"2:00 pm\",\"Endtime\":\"6:00 pm\"},{\"ScheduleDate\":\"2018-03-05\",\"StartTime\":\"RTO\",\"Endtime\":\"\"},{\"ScheduleDate\":\"2018-03-06\",\"StartTime\":\"10:00 am\",\"Endtime\":\"11:00 pm\"},{\"ScheduleDate\":\"2018-03-06\",\"StartTime\":\"2:00 pm\",\"Endtime\":\"4:00 pm\"},{\"ScheduleDate\":\"2018-03-31\",\"StartTime\":\"6:00 am\",\"Endtime\":\"4:00 pm\"},{\"ScheduleDate\":\"2018-03-14\",\"StartTime\":\"7:00 am\",\"Endtime\":\"4:00 pm\"},{\"ScheduleDate\":\"2018-03-28\",\"StartTime\":\"1:00 pm\",\"Endtime\":\"4:00 pm\"}]}");
    } catch (JSONException e) {
        e.printStackTrace();
    }

然后这样做

SharedPreferences  preferences = getSharedPreferences("identifier", Context.MODE_PRIVATE);

在您的第一个活动中执行此操作以保存

Editor prefsEditor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyResultObject", json);
prefsEditor.commit();

并在第二个活动中检索它

Gson gson = new Gson();
String json = preferences.getString("MyResultObject", "");
JSONObject obj = gson.fromJson(json, JSONObject.class);

现在从这个json对象获取任何键,

try {
        JSONArray jsonArray=obj.getJSONArray("NEW_DISPLAY_SCHEDULE");
        for (int i=0;i<jsonArray.length();i++){
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            String ScheduleDate=jsonObject.getString("ScheduleDate");
            ScheduleDateArray.add(ScheduleDate);
            //add toast here to display the value of ScheduleDate in first array element
            Toast.makeText(Main2Activity.this ,  "ScheduleDates"+ ScheduleDate, Toast.LENGTH_LONG).show();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

注意:首先初始化此&gt;&gt; private ArrayList<String> ScheduleDateArray=new ArrayList<>();