0

What i am basically trying to do here is,i am receiving the data from the database using php file,and i want to store them in shearedpreference for later use in another activity,

this is my 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"}]}

and this is my android activity i store them in shearedpreference,

1st activity

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

and in 2nd activity i try to receive like this

    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);

    }
}

my problem is i dont know how to seperate the string in second activity from shearedpreference ,the app is getting closed,anyone help me to seperate the string and i want to put them in toast.

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) 
selva surya
  • 103
  • 9
  • 2
    Possible duplicate of [How to parse JSON in Android](https://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) – Tim Biegeleisen Mar 13 '18 at 06:20
  • Your question appears to actually have nothing to do with Shared Prefs, but rather how to parse a JSON string coming from a key in shared prefs. Follow the duplicate link for some help. – Tim Biegeleisen Mar 13 '18 at 06:20
  • @ Tim Biegeleisen i have edited the question,what i want to do is in 2nd activity i want to sepertate the strings and put them in toast.can you help me to do that,in "result " i have json string – selva surya Mar 13 '18 at 06:24

1 Answers1

3

First of all create a jsonobject using your result string

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();
    }

then do like this

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

In your 1st activity do this to save

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

and in 2nd activity retrieve it like this

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

Now to get any key from this json object,

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();
    }

Note : First initialise this >> private ArrayList<String> ScheduleDateArray=new ArrayList<>();

Navneet Krishna
  • 5,009
  • 5
  • 25
  • 44
  • ok when i do like that "try/catch" statement,you have created object for given json string,but when i get json string more then the given string means what should i do? weather i have to create object again for extra json string? – selva surya Mar 13 '18 at 06:43
  • you may add the json string to a string variable and reasign it as needed – Navneet Krishna Mar 13 '18 at 06:51
  • suppose you save it to `result`, then use it like this `JSONObject MyObject=new JSONObject(result)` – Navneet Krishna Mar 13 '18 at 06:53
  • bro but i am not able to store them in array like this "ScheduleDate=jsonObject.getString("ScheduleDate"); ScheduleDate =ScheduleDates[i];" – selva surya Mar 13 '18 at 07:28
  • if you want to save it in an array, loop through all the data and store it in a string array, i will update the code – Navneet Krishna Mar 13 '18 at 07:31
  • as mentioned in the change you can save the data to an arraylist `ScheduleDateArray` and you can find all the `ScheduleDate` in this arraylist – Navneet Krishna Mar 13 '18 at 07:40
  • bro again the same problem bro not working,i have edited my code,please check them @ ヅ fix – selva surya Mar 13 '18 at 07:54
  • no error is shown in logcat,but the app is getting closed – selva surya Mar 13 '18 at 08:01
  • if app closes down unespectedly(anr), you would be getting error in logcat. If you are having trouble finding it, try adding a breakpoint on the code and check if any data is returned as null – Navneet Krishna Mar 13 '18 at 08:05
  • ok bro i check it and update you,bro did you see my edited code weather i am correctly retiving the data in for loop at last – selva surya Mar 13 '18 at 08:07
  • also try removing the second for loop and try adding the toast inside the for loop that i added – Navneet Krishna Mar 13 '18 at 08:07
  • bro,when i try to put them in toast it is working "ScheduleDateArray.get(3)" but when i put them inside the for loop it is not working like this "ScheduleDateArray.get(i)" i have upload the logcat also – selva surya Mar 13 '18 at 08:19
  • it is becuase toast is not generally used for this purpose, it will have some delay to load the next item since you are adding it in a loop, you may try to pass this arraylist to a listview so that you can get all data together – Navneet Krishna Mar 13 '18 at 08:26