How to Use Sharedpreferences to Save More Than One Values

How to use SharedPreferences to save more than one values?

You can save multiple favorites in a single preference by adding numerous favorites in a single string, each favorite item separated by comma. Then you can use convertStringToArray method to convert it into String Array. Here is the full source code.

Use MyUtility Methods to save multiple favorite items.

            MyUtility.addFavoriteItem(this, "Sports");
MyUtility.addFavoriteItem(this, "Entertainment");

get String array of all favorites saved

String[] favorites = MyUtility.getFavoriteList(this);// returns {"Sports","Entertainment"};

Save these methods in separate Utility class

 public abstract class MyUtility {

public static boolean addFavoriteItem(Activity activity,String favoriteItem){
//Get previous favorite items
String favoriteList = getStringFromPreferences(activity,null,"favorites");
// Append new Favorite item
if(favoriteList!=null){
favoriteList = favoriteList+","+favoriteItem;
}else{
favoriteList = favoriteItem;
}
// Save in Shared Preferences
return putStringInPreferences(activity,favoriteList,"favorites");
}
public static String[] getFavoriteList(Activity activity){
String favoriteList = getStringFromPreferences(activity,null,"favorites");
return convertStringToArray(favoriteList);
}
private static boolean putStringInPreferences(Activity activity,String nick,String key){
SharedPreferences sharedPreferences = activity.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, nick);
editor.commit();
return true;
}
private static String getStringFromPreferences(Activity activity,String defaultValue,String key){
SharedPreferences sharedPreferences = activity.getPreferences(Activity.MODE_PRIVATE);
String temp = sharedPreferences.getString(key, defaultValue);
return temp;
}

private static String[] convertStringToArray(String str){
String[] arr = str.split(",");
return arr;
}
}

If you have to add extra favorites. Then get favorite string from SharedPreference and append comma+favorite item and save it back into SharedPreference.

* You can use any other string for separator instead of comma.

How to use SharedPreferences to save more than one Integer values?

For saving in SharedPreferences:

public void putListInt(String key, ArrayList<Integer> intList) {
checkForNullKey(key);
Integer[] myIntList = intList.toArray(new Integer[intList.size()]);
preferences.edit().putString(key, TextUtils.join("‚‗‚", myIntList)).apply();
}

For retrieving from SharedPreferences:

public ArrayList<Integer> getListInt(String key) {
String[] myList = TextUtils.split(preferences.getString(key, ""), "‚‗‚");
ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList));
ArrayList<Integer> newList = new ArrayList<Integer>();

for (String item : arrayToList)
newList.add(Integer.parseInt(item));

return newList;
}

How can i add multiple entries in a shared prefrences file

You have to use different keys, e.g.:

            SharedPreferences settings = getSharedPreferences("users", 0);

SharedPreferences.Editor editorUser = settings.edit();
for (int i = 0; i < users.size(); i++)
editorUser.putString("user" + i, users.get(i));

editorUser.commit();

Android Save Multiple Values in SharedPreferences

Yes, sharedPreferences should work. You can use fotoID as the key, if you have the fotoID, you can both set and look up the fotoID in shared preferences to manage the boolean "liked".

imageToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
addLike();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(foto_id, imageToggle.isChecked()); // changed from "liked". Changed "foto_id" to foto_id -mysticola
// remove this line editor.putString("pic_id", foto_id);
editor.commit();
} else {
unLike();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(foto_id, false); // changed from liked
editor.commit();

}
}
});

and

   SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean liked = preferences.getBoolean(foto_id, false); // change from "liked"
// remove String pic = preferences.getString("pic_id", "0");
final ToggleButton imageToggle = (ToggleButton) findViewById(R.id.like);
if (liked) { // changed this part
imageToggle.setChecked(liked);
}

Save multiple EditText values using SharedPreferences

You just have to save each EditText value and retrieve them next time your Activity reloads. The code below is adapted from the link you mentioned in your question:

public class PersonalInformation extends Activity{

private SharedPreferences savedFields;
private Button saveButton;
private EditText editText1;
private EditText editText2;
// Add all your EditTexts...

// Upon creating your Activity, reload all the saved values.
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);

saveButton = (Button) findViewById(R.id.your_save_button_id);
editText1 = (EditText) findViewById(R.id.your_edit_text_1_id);
editText2 = (EditText) findViewById(R.id.your_edit_text_2_id);
// Keep adding all your EditTexts the same way...

// "info" is just a tag name, use anything you like
savedFields = getSharedPreferences("info", MODE_PRIVATE);

// In case no value is already saved, use a Default Value
editText1.setText(savednotes.getString("editText1", "Default Value 1"));
editText2.setText(savednotes.getString("editText2", "Default Value 2"));

// Save the changes upon button click
saveButton.setOnClickListener(saveButtonListener);
}

public OnClickListener saveButtonListener = new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor preferencesEditor = savedFields.edit();
if(editText1.getText().length() > 0) // Not empty
preferencesEditor.putString("editText1", editText1.getText());
if(editText2.getText().length() > 0) // Not empty
preferencesEditor.putString("editText2", editText2.getText());
// You can make a function so you woudn't have to repeat the same code for each EditText

// At the end, save (commit) all the changes
preferencesEditor.commit();
}
}
};
}


Related Topics



Leave a reply



Submit