how to get JSONArray from sharedpreferences into Adapter - android

In the first activity to load in my app I put my JSONArray into Sharedpreferences (as a String):
//put myJsonArray into shared preferences file as a String
//Convert back to Json later, in the adapter
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
//we want to edit SharedPreferences
SharedPreferences.Editor editor = sharedPrefs.edit();
//put the string value into SharedPreferences, with the key "key_value"
editor.putString("key_value", myJsonArray.toString());
//commit the string
editor.commit();
I can get this string in another Activity and convert it back to a JSONArray easily with:
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("key_value", "0");
try
{
JSONArray jsonArray = new JSONArray(json_array);
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
}
But when I put the above code in the onBindViewHolder of my adapter, or anywhere else in my adapter, I am getting: NullPointerException and my app crashes.
Please tell me how I can solve this.
Where it crashes it says:
java.lang.NullPointerException at com.example.chris.tutorialspoint.SharedReviews.SharedPopulistoReviewsAdapter.onBindViewHolder(SharedPopulistoReviewsAdapter.java:130)
My onBindViewHolder code is:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) {
SharedReview r = the_Shared_reviews.get(position);
SharedPreferences sharedPrefs = context.getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("key_value", "0");
try
{
JSONArray jsonArray = new JSONArray(json_array);
System.out.println("SharedAdapter, the jsonarray is :" + jsonArray);
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
}
((ReviewHolder) viewHolder).category.setText("Category: " + r.getCategory());
((ReviewHolder) viewHolder).name.setText("Name: " + r.getName());
((ReviewHolder) viewHolder).phone.setText("Phone: " + r.getPhone());
((ReviewHolder) viewHolder).comment.setText("Your Comment: " + r.getComment());
//set an onClick listener for the row, if it's clicked anywhere
((ReviewHolder) viewHolder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
//When the review is clicked in PopulistoListView
//then show that review
public void onClick(View v) {
SharedReview sharedReview = (SharedReview) SharedPopulistoReviewsAdapter.getItem(position);
//we want to pass the review_id of the sharedReview being clicked
//to the ViewContact activity, and from there post it and get more
//info for that sharedReview - address, comments etc
Intent i = new Intent(v.getContext(), ViewContact.class);
//pass the review_id to ViewContact class
i.putExtra("review_id", sharedReview.getReviewid());
v.getContext().startActivity(i);
}
});
}
Line 130 is:
SharedPreferences sharedPrefs = context.getSharedPreferences("MyData", Context.MODE_PRIVATE);

This is happening because you have not initialized context. Either you must initialize context by passing context as a parameter when creating the object of the adapter or you can get the context from a view.
To get the context from a view change the line to:
SharedPreferences sharedPrefs = ((ReviewHolder) viewHolder).category.getContext().getSharedPreferences("MyData", Context.MODE_PRIVATE);

Related

Unable to access SharedPreferences value from a class into an activity

I am working on a server baser application so whenever a user logs in i have to capture his unique userId and use it in different activities in my whole project.
So after getting the userId from JSONObject i am putting it in sharedPrederence and getting it in another activity but after entering into my main activity which is after successful login the shared preference shows me the default value of userId which is zero.
Here is my code in PostData.java class which will work in background of login activity:
private SharedPreferences userIdSharedPreferences;
private SharedPreferences.Editor userIdEditor;
try {
JSONObject obj = new JSONObject(response.toString());
//boolean requestStatus = obj.getBoolean("requestStatus");
JSONObject data = obj.getJSONObject("data");
userId = Integer.parseInt(data.getString("userId"));
userIdEditor = userIdSharedPreferences.edit();
userIdEditor.putInt("crrUserId", userId);
userIdEditor.apply();
userIdEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
and here is how i am using that sharedPreference value in other acitivity:
userIdSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
crrUserId = userIdSharedPreferences.getInt("crrUserId", 0);
Toast.makeText(getApplicationContext(), "Your user id is: " + crrUserId, Toast.LENGTH_SHORT).show(); //This toast showing 0 which is default i set.
EDIT
for more clarification now i am passing my userId from my background class PostData.java to my LoginActivity using the below function:
Integer passUserId() {
return userId;
}
and from there i am passing userId using sharedPreference like this:
Intent loginSuccess = new Intent(getApplicationContext(), MainActivity.class);
Integer crrUserId = Login.passUserId(); //Login is name of variable which will accespassUserId function in PostData.java class
SharedPreferences userIdSharedPreferences = getApplicationContext().getSharedPreferences("userId", 0);
SharedPreferences.Editor userIdEditor;
userIdEditor = userIdSharedPreferences.edit();
userIdEditor.putInt("crrUserId", crrUserId);
userIdEditor.apply();
startActivity(loginSuccess);
finish();
and here is how i am using in my mainactivity:
public class MainActivity extends AppCompatActivity {
SharedPreferences userIdSharedPreferences;
SharedPreferences.Editor userIdEditor;
Integer crrUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userIdSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
crrUserId = userIdSharedPreferences.getInt("userId", 0);
Toast.makeText(getApplicationContext(), "Your user id is: " + crrUserId, Toast.LENGTH_SHORT).show();
}
Try this:
First you need to initialize userIdSharedPreferences object like below:
userIdSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
After getting object of SharedPreference do this:
userIdEditor = userIdSharedPreferences.edit();
After getting object of SharedPreferences.Editor do your task.
initialiase userIdSharedPreferences may be thats the problem
try {
JSONObject obj = new JSONObject(response.toString());
//boolean requestStatus = obj.getBoolean("requestStatus");
JSONObject data = obj.getJSONObject("data");
userId = Integer.parseInt(data.getString("userId"));
SharedPreferences userIdSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
SharedPreferences.Editor userIdEditor = userIdSharedPreferences.edit();
userIdEditor.putInt("crrUserId", userId);
userIdEditor.apply(); //apply or commit not both
userIdEditor.commit();
} catch (JSONException e) {
e.printStackTrace();
}

Key-Value Store Data not retrieved

In my app, I am trying to save a key value as zero or one depending on whether a checkbox is checked. I retrieve these values in a different activity. However, when I attempt to retrieve the value, I am getting an empty string:
Saving key values in Activity 1(ScienceCoursesCheck):
public void setDefaults(String key, String value) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox_APBio:
if (checked) {
setDefaults("APBio", "1");
}
else {
setDefaults("APBio", "0");
break;
}
}}
Retrieving key values in activity 2(MyHome):
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
public void myMethod() {
SharedPreferences myPrefs = getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
String APBio = myPrefs.getString("APBio","");
if (APBio.equals("1")){
Button myButton = new Button(this);
myButton.setText(APBio);
RelativeLayout ll = (RelativeLayout)findViewById(R.id.activity_my_home);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
}
}
Is the second activity accessing the correct SharedPreferences file?
Use the following code for sharedpreference. Call
Util.saveInfo(activityContext,_key,_value)
when you want to save the info. Then call
Util.getInfo(getApplicationContext(),_key)
to get the info.
public class Util{
public static void saveInfo(Context context, String key, String value )
{
try
{
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(key, value).apply();
}
catch (Exception ex)
{
Log.e(TAG," saveInfo "+ex+"");
}
}
public static String getInfo(Context context, String key)
{
try {
return PreferenceManager.getDefaultSharedPreferences(context).getString(key,"");
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
The issue is because when you store the items in SharedPreferences you are using
PreferenceManager.getDefaultSharedPreferences
but when you retrieve them you are using
getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
These are two different SharedPreferences files. Try using getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE); for your setting method as well. Or perhaps you meant to use your getDefaults() method in activity 2 instead of myPrefs
That is because you are saving in the DefaultSharedPreferences file
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
and retrieving from another file named "ScienceCoursesCheck"
SharedPreferences myPrefs = getSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
and they are not the same file!
See the difference between getSharedPreferences and getDefaultSharedPreferences in this answer
====
Solution is either to always use DefaultSharedPreferences OR always use the file named "ScienceCoursesCheck" .
The problem is you're saving the values in the DefaultSharedPreference and trying to retrieve the values from the ScienceCoursesCheck preference file.
Try below code for setDefaults method.The getDefaultSharedPreference and getSharedPreference methods are different.
See this link for the difference.
public void setDefaults(String key, String value) {
SharedPreferences sharedPref = getApplicationContext().getDefaultSharedPreferences("ScienceCoursesCheck", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
Hope this helps you...

store edited values in edittext fields after changed paramaters

public class ActivityEditParent extends AppCompatActivity {
private static final String TAG="ActivityEditParent";
CustomEditText etFirstName,etLastName,etEmail,etPhone;
public static ConnectionDetector detector;
private static final String URL = "http://hooshi.me.bh-in-13.webhostbox.net/index.php/parents/editprofile";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private CustomButton btnSave;
private String parentFirstName,parentLastName,parentPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_parent);
getSupportActionBar().hide();
detector = new ConnectionDetector(ActivityEditParent.this);
getUIComponents();
}
private void getUIComponents(){
etFirstName = (CustomEditText) findViewById(R.id.edit_first_name);
etLastName = (CustomEditText) findViewById(R.id.edit_last_name);
etEmail = (CustomEditText) findViewById(R.id.edit_email_address);
etPhone = (CustomEditText) findViewById(R.id.edit_phone_number);
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editParent();
}
});
TextView title = (TextView) findViewById(R.id.toolbar_title);
ImageButton back = (ImageButton) findViewById(R.id.toolbar_back);
title.setText("Edit parent");
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goBack();
}
});
sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
String fName = sharedPreferences.getString(AppConstants.PARENT_FNAME,AppConstants.fName);
String lName = sharedPreferences.getString(AppConstants.PARENT_LNAME,AppConstants.lName);
String email = sharedPreferences.getString(AppConstants.PARENT_EMAIL,AppConstants.email);
String phone = sharedPreferences.getString(AppConstants.PARENT_MOBILE,AppConstants.mobile);
etFirstName.setText(fName);
etLastName.setText(lName);
etPhone.setText(phone);
etEmail.setText(email);
}
private void goBack() {
startActivity(new Intent(getApplicationContext(), ActivityEditDetails.class));
finish();
}
private void editParent(){
SharedPreferences preferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonParam = null;
parentFirstName = etFirstName.getText().toString().trim();
parentLastName = etLastName.getText().toString().trim();
parentPhone = etPhone.getText().toString().trim();
if (detector.checkInternet()){
jsonParam = new JSONObject();
JSONObject header = new JSONObject();
try {
jsonParam.put("parentId",preferences.getString(AppConstants.PARENT_ID,""));
jsonParam.put("parentFN",parentFirstName);
jsonParam.put("parentLN",parentLastName);
jsonParam.put("parentPhone",parentPhone);
jsonParam.put("apiAccessKey",preferences.getString(AppConstants.API_ACCESS_KEY,""));
header.put("parent",jsonParam);
Log.d("POST PARAMETERS:",""+header);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, header, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response:",""+response);
String json_status = null;
try {
json_status = response.getString("status");
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
}
}
In the response After getting success message I want save the edited details in in respective edit text fields please help.After success message I am moving to home screen through intent and again I get back to this screen it is showing the previous details only.
all happens here :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
once you have a success response save the edited values on the preferences, for example etFirstName, save it is new value to the corresponding preference :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
editor.putString(AppConstants.PARENT_FNAME, parentFirstName);
editor.apply(); //don't forget this
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
any way you're creating the editor but not using it.
you want to save data after download from network or after an edit in edit text fields was made??
if from network add some save method execution statement in code where you download data was successful
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
// here you have successful received data so u can map them to edit text or save in shared prefs
// add method to save data here
saveData(response);
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
private void saveData(JSONObject response) {
// use JSon response object save here to shared preferences
// see how to load data from json object
// https://processing.org/reference/JSONObject_getString_.html
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
sharedPreferences.putString(....).apply;
// or set edit text controls with JSon data
}
to save edit text changes you have two choices :
add to layout save button (you have one) button and set on click listener with method to save data:
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData(v);
}
});
private void saveData(View view) {
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// get string from edit text widget
String firstName = etFirstName.getString.toString();
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// save to shared prefs firstName wher NAME_KEY is string to identified your saved data for later use - to load
sharedPreferences.putString(NAME_KEY,firstName).apply;
}
private void loadDataFromSharedPredferences(View view) {
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// load data from shared prefs firstName wher NAME_KEY is string to identified data to load
String firstName = sharedPreferences.getString(NAME_KEY,firstName);
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// set string to edit text widget
etFirstName.setText(firstName);
}
add on text change listener for edittext widgets
ps. you need to clarify - write a exactly steps of what you want to do achieve
load data from network ? then save ?
or save request date ?
or save result data ?

Correct way of getting a Json position

After the login I get this response from the webserver..
{"success":" Bem vindo lu#lu.com"}{"nomeusuario":"Lu Zimermann"}{"enderecousuario":"Rua Pedro Alves 270. Centro. Casa."}{"telefoneusuario":"(42) 3623-8052"}
Ok. Now My android code.
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),Restaurantes.class));
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This code Toast the following message. "Bem vindo lu#lu.com"
What I want is:
How can I get the other infos and pass it to a String.
Email = "lu#lu.com"
Endereco = "Rua Pedro..."
Name = "Lu Zimermann"
Soo I can use it later on the app.
Thanks.
Now the response is the right way you can do this to save data..
first wirte a custion class for Preferennce
SharedPreferenceCustom
public class SharedPreferenceCustom {
private Context mContext;
private String defValue = "";
public SharedPreferenceCustom(Context context) {
this.mContext = context;
}
public void setSharedPref(String inputKey, Object inputValue) {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(inputKey, String.valueOf(inputValue));
editor.apply();
}
public String getSharedPref(String inputKey) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
return sharedPreferences.getString(inputKey, defValue);
}
}
Now for saving the data, in the activity
try {
JSONObject response = new JSONObject(new String(response_from_server))
SharedPreferenceCustom sp = new SharedPreferenceCustom(Activity.this);
sp.setSharedPref("key_1", response.getString("nomeusuario")); // use key as per needed
sp.setSharedPref("key_2", response.getString("enderecousuario"));
sp.setSharedPref("key_3", response.getString("telefoneusuario"));
sp.setSharedPref("key_4", response.getString("success"));
} catch (JSONException e) {
e.printStackTrace();
}
And for getting the data call sp.getSharedPref("key"); pass the key for getting the corresponding data
EDIT: you can also write individual function in SharedPreferenceCustion to store different data type, or you can use just this, But it might create some conflicts for certain data types,
Hope this helps :) :)
To get access to the other keys, you can use the get(key) on the jsonObject object. Here are the code changes you need to make:
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
{"success":" Bem vindo lu#lu.com"}{"nomeusuario":"Lu Zimermann"}{"enderecousuario":"Rua Pedro Alves 270. Centro. Casa."}{"telefoneusuario":"(42) 3623-8052"}
//here I am just getting the other properties/keys
String nomeusuario = jsonObject.getString("nomeusuario");
String enderecousuario = jsonObject.getString("enderecousuario");
String telefoneusuario = jsonObject.getString("telefoneusuario");
//here you could do whatever you like - I am just making a Toast as an example:
Toast.makeText(getApplicationContext(), nomeusuario+ ", "+enderecousuario+ ", "+telefoneusuario ,Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
I hope this helps you - give it a try and let me know.
By the way, I am assuming the JSON that you are getting is proper.
There are several ways you can do that.
First of all you need to store them into variable/s.
You can choose to keep it as JSON var, as HashMap or each variable separate as String.
The second action is to access it from any place. This depends on how long to you want the information alive.
If you want them live for just as long as the app is live then the I suggest to create a Global Java class with set/get of your variable.
You could also store it in SharedPreferences or sqlite database for permanent.
Try following
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if(jsonObject.names().get(0).equals("success")){
//Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
JSONObject jsonObject = new JSONObject(response);
Iterator<String> keys = jsonObject.keys();
String values = "";
while(keys.hasNext()){
String keyName = keys.next();
values = jsonObject.getString(keyName) + "\n";
}
Toast.makeText(getApplicationContext(),values,Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),Restaurantes.class));
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Put and get String array from shared preferences

I need to save on shared preferences some array of Strings and after that to get them.
I tried this :
prefsEditor.putString(PLAYLISTS, playlists.toString()); where playlists is a String[]
and to get :
playlist= myPrefs.getString(PLAYLISTS, "playlists"); where playlist is a String but it is not working.
How can I do this?
You can create your own String representation of the array like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < playlists.length; i++) {
sb.append(playlists[i]).append(",");
}
prefsEditor.putString(PLAYLISTS, sb.toString());
Then when you get the String from SharedPreferences simply parse it like this:
String[] playlists = playlist.split(",");
This should do the job.
From API level 11 you can use the putStringSet and getStringSet to store/retrieve string sets:
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putStringSet(SOME_KEY, someStringSet);
editor.commit();
SharedPreferences pref = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
Set<String> someStringSet = pref.getStringSet(SOME_KEY);
You can use JSON to serialize your array as a string and store it in the preferences. See my answer and sample code for a similar question here:
How can write code to make sharedpreferences for array in android?
HashSet<String> mSet = new HashSet<>();
mSet.add("data1");
mSet.add("data2");
saveStringSet(context, mSet);
where
public static void saveStringSet(Context context, HashSet<String> mSet) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sp.edit();
editor.putStringSet(PREF_STRING_SET_KEY, mSet);
editor.apply();
}
and
public static Set<String> getSavedStringSets(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getStringSet(PREF_STRING_SET_KEY, null);
}
private static final String PREF_STRING_SET_KEY = "string_set_key";
Store array list in prefrence using this easy function, if you want more info Click here
public static void storeSerializeArraylist(SharedPreferences sharedPreferences, String key, ArrayList tempAppArraylist){
SharedPreferences.Editor editor = sharedPreferences.edit();
try {
editor.putString(key, ObjectSerializer.serialize(tempAppArraylist));
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
And how to get stored array list from prefrence
public static ArrayList getSerializeArraylist(SharedPreferences sharedPreferences, String key){
ArrayList tempArrayList = new ArrayList();
try {
tempArrayList = (ArrayList) ObjectSerializer.deserialize(sharedPreferences.getString(key, ObjectSerializer.serialize(new ArrayList())));
} catch (IOException e) {
e.printStackTrace();
}
return tempArrayList;
}

Categories

Resources