Avinash
Avinash

Reputation: 325

How to store and retrieve JSONArray in Android studio sharedpreferences

I Want to store below JSONArray in sharedpreferences.How can I store JSONArray in sharedPreferences and How to retrieve stored JsonArray back.

StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_ATTENDANCE,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                jsonArray = new JSONArray(response); (***)
                                

                            } catch (JSONException e) {


                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {


                        }
                    })


Upvotes: 0

Views: 577

Answers (1)

MLFR2kx
MLFR2kx

Reputation: 1135

You can use GSON.

JSONArray jArr = new JSONArray();
editor.putString("YOURKEY", jArr.toString());
editor.commit();

And this one to read:

JSONArray jArr = (new Gson()).fromJson(preferences.getString("YOURKEY"), JSONArray.class));

As a really good alternative, you can use Hawk library. It's a secure, simple key-value storage for android using shared preferences that supports object storage and encryption.

Upvotes: 1

Related Questions