简体   繁体   中英

How to save the value of json response in shared preference?

I have to hit a json service and if the response came true than I have to save the user value in shared preference for future use. How can i do that?

my url is: http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id= {aff_id}

Variables will be passed by the sdk user. In the above url my variables are- id: 4 and public_key: 9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G

I have made a class and declared a static method. Inside the static method I have to do parsing and save the variables in shared preference.

public class InitializeSDK {
   public static void init(final Context ctx, int id, String public_key){
     new AsyncTask<Void, Void, Void>() {

        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected Void doInBackground(Void... unused) {

            return null;

        }

        protected void onPostExecute(Void unused) {

        }

     }.execute();
  }

}

Please tell me how to parse it to get the response and save it in shared preference?

Here is a sample code you can use:

protected Void doInBackground(Void... unused) {

    //TODO: add code to read http request and store the json data in json variable
    JSONObject jsonObject = new JSONObject(json);
    boolean state = jsonObject.getBoolean("success");
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    Editor editor = prefs.edit();
    editor.putBoolean("state",state);
    editor.commit();
    return null;

}

Firstly, I suggest you need to get JSON data as a string and you can parse it.

    String json = "";
    URL url;
    HttpURLConnection connection = null;


    try {
        url =  new URL("http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id=");
        connection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = connection.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);
        int data = reader.read();

        while (data != -1) {

            char currentChar = (char) data;
            data = reader.read();
            json += currentChar;


        }

    }catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return json;
}

I call this method inside the doInBackground.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM