Getting an array from SharedPreferences - android

I am trying to save different arrays of information related to movies that are added to SharedPreferences when the user presses the favorite star, like a favorite movie list, then I'll use that list to sort a movie poster listview display screen.
Preferences variable:
preferences = getContext().getSharedPreferences("favorites_list", Context.MODE_PRIVATE);
Here is where I add the movie (or remove) to the list when the user presses the favorite button:
ib = (ImageButton) rootView.findViewById(R.id.favorite);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!favoriteState) {
ib.setBackgroundResource(R.drawable.starpressed);
favoriteState = true;
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putStringSet(movieInfo[1], new HashSet<String>(Arrays.asList(movieInfo)));
preferencesEditor.commit();
}else{
ib.setBackgroundResource(R.drawable.star);
favoriteState = false;
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.remove(movieInfo[1]);
preferencesEditor.commit();
}
}
});
Here is where I want to get the array from SharedPreferences, but I want to get everything there not only some array based on the keyValue that I set.
Here is where I want to fetch all data in the favorites_list inside SharedPreferences:
private void updateMovies() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String preference = prefs.getString(getString(R.string.pref_sortby_key), getString(R.string.pref_sortby_default));
if(preference.toLowerCase().equals("favorites")){
SharedPreferences preferences = getContext().getSharedPreferences("favorites_list", Context.MODE_PRIVATE);
}else{
new FetchMoviesTask().execute(baseUrl+preference.toLowerCase()+apiKey, "i");
}
}
I am not sure if I inserted them correctly, and is there a way to check on androidStudio?
Thank you in advance for your help.

Related

Android Save Multiple Values in SharedPreferences

I have a pretty straightforward toggle button "Like" system. A user id and photo id are sent to the database and stored... then, in the app, I use Shared Preferences to remember if a user has liked a photo or not.
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("liked", imageToggle.isChecked()); // value to store
editor.putString("pic_id", foto_id);
editor.commit();
} else {
unLike();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("liked", false); // value to store
editor.commit();
}
}
});
Then... whenever the view is created... the preferences are checked to see if the photo is liked or not.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean liked = preferences.getBoolean("liked", false);
String pic = preferences.getString("pic_id", "0");
final ToggleButton imageToggle = (ToggleButton) findViewById(R.id.like);
if (pic.equals(foto_id)) {
imageToggle.setChecked(liked);
}
The problem... you might have guessed... is that this only works for one photo at a time. If I click on another photo and like it then THAT photo's ID becomes the pic_id and the original photo becomes unchecked.
I'm not even sure SharedPreferences is the right way to achieve what I want to do. (Storing and retrieving multiple values of liked photos). I've looked into everything from saving Sets, to converting everything to JSON... I've thought about querying the database each time to find out if the user has liked a particular photo...
...but I'm SO close to what I want to achieve that I just know there must be some really simple way to do it that just hasn't dawned on me. All I want SharedPreferences to do is remember if I've liked each individual photo or not. Maybe just a new SharedPreference for each photo?
What is the simplest possible solution for what I'm trying to do given what I have so far?
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);
}
try this:
var buttonLocalState: SharedPreferences =
context.getSharedPreferences(SPP_NAME, MODE_PRIVATE)
fun savebuttonstate(mExampleList: ArrayList<commentItemModel>) {
val userLocalDatabaseEditor: SharedPreferences.Editor = buttonLocalState.edit()
val gson = Gson()
val json = gson.toJson(mExampleList)
userLocalDatabaseEditor.putString("yesbtn list", json)
userLocalDatabaseEditor.apply()
}
fun getyesBtn(): ArrayList<commentItemModel> {
val gson = Gson()
var mExampleList: ArrayList<commentItemModel> = ArrayList<commentItemModel>()
val json: String = buttonLocalState.getString("yesbtn list", null).toString()
val type: Type = object : TypeToken<ArrayList<commentItemModel?>?>() {}.getType()
if (!mExampleList.isEmpty()) {
mExampleList = gson.fromJson<Any>(json, type) as ArrayList<commentItemModel>
}
return mExampleList
}
this is model class to add item to list for example: list.Add(commentItemModel(1, true))
data class commentItemModel(var id: Int, var clicked: Boolean) {
}
Because you don't know how many photos will be selected and it can change quite dynamically, you might want to save a list of like photo ids into shared preferences. Normally shared preferences only allow you saving sets of data not lists so this SO question shows how to do that.
Save ArrayList to SharedPreferences

Android SharedPreferences update does not work

I know, this issue has been dealt with in many threads, but I cannot figure out this one.
So I set a shared preference like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.apply();
I read the preferences like this:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = null;
spinnerValuesSet = prefs.getStringSet(spinnerName,null );
Everything works, except for my changes are visible while this activity runs i.e. - I display the values from the SharedPreferences, allow the user to delete or add and then update the ListView. This works, but after I restart the application, I get the initial values.
This for example is my method to delete one value from the list, update the values in SharedPreferences and update the ListView
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
for (String s : spinnerValuesSet)
{
if(s == currentSelectedItemString)
{
spinnerValuesSet.remove(s);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, spinnerValuesSet );
editor.apply();
break;
}
}
updateListValues();
}
});
And this is the method that updates the ListView:
private void updateListValues()
{
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
Set<String> spinnerValuesSet = prefs.getStringSet(spinnerName,null );
if(spinnerValuesSet.size() > 0)
{
names = new ArrayList<String>();
names.clear();
int k=0;
for (String s : spinnerValuesSet) {
names.add(k, s);
k++;
}
namesAA = new ArrayAdapter<String> ( this, android.R.layout.simple_list_item_activated_1, names );
myList.setAdapter(namesAA);
}
}
Any help is much appreciated.
The Objects returned by the various get methods of SharedPreferences should be treated as immutable. See SharedPreferences Class Overview for reference.
You must call remove(String) through the SharedPreferences.Editor returned by SharedPreferences.edit() rather than directly on the Set returned by SharedPreferences.getStringSet(String, Set<String>).
You will need to construct a new Set of Strings containing the updated content each time since you have to remove the Set entry from SharedPreferences when you want to update its content.
Problem happens because the Set returned by SharedPreference is immutable. https://code.google.com/p/android/issues/detail?id=27801
I solved this by created a new instance of Set and storing in all the values returned from SharedPreferences.
//Set<String> address_ids = ids from Shared Preferences...
//Create a new instance and store everything there.
Set<String> all_address_ids = new HashSet<String>();
all_address_ids.addAll(address_ids);
Now use the new instance to push the update back to SharedPreferences
I may be wrong but I think the way you are retrieving the Shared Preferences is the problem. Try using
SharedPreferences prefs = getSharedPreferences("appPreferenceKey", Context.Mode_Private);
Use editor.commit(); instead of editor.apply();
Example Code:
SharedPreferences prefs = MainActivity.this.getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(spinnerName, myValueSet );
editor.commit();
I hope this helps.
Depending on the OS Build you may have to save values in a different way.
boolean apply = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
public static void saveValue(SharedPreferences.Editor editor)
{
if(apply) {
editor.apply();
} else {
editor.commit();
}
}

Delete data from shared preferences in android

I am trying to delete the data from shared preferences. But I cant do that. To track that the data is removed or not, I am using this code:
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(share_pref_file, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove(share_pref_file);
editor.clear();
editor.commit();
getApplicationContext().getSharedPreferences(share_pref_file, 0).edit().clear().commit();
String strJson = prefs.getString("jsondata","");
if(strJson != null)
{
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(),LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
But in logcat window it is showing me "cccccccccccccccccccccccccccc" value every time.
So can anyone help me out that how to remove/delete the data from shared preferences so that if I click on 'logout' button it will remove all the stored data? Thanks in advance.
An empty string is still a string (and String("") != null will return true). Try this instead:
if(!strJson.equals(""))
This assumes the empty string will never be a valid input in your SharedPreferences in the first place.
Try this one inside the button click event to clear the SharedPreferences values.
Editor editor = getSharedPreferences("MyPref", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
Try editor.clear(); followed by a editor.commit();
Here is one example that I've used:
Preference clearPref = (Preference) findPreference("MyPref");
btnLogout.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
Toast.makeText(getBaseContext(), "All data cleared!", Toast.LENGTH_SHORT).show();
return true;
}
});
Either change this:
String strJson = prefs.getString("jsondata", "");
To:
String strJson = prefs.getString("jsondata", null);
And then check:
if(strJson != null) {
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
Or keep it as it is and check it like this:
if(strJson.equals("")) {
Log.d("CLEAR", "cccccccccccccccccccccccccccc");
}
settings.edit().clear().commit();
is a one line code I am using, works perfectly
It is my solution:
You can put null instead of your favorite data in shareprefrences
getApplicationContext();
SharedPreferences.Editor pref = (Editor) getSharedPreferences("data", MODE_PRIVATE).edit();
pref.putString("admin_no", null);
pref.commit();

How to save the state of the toogleButton on/off selection?

Hello i have implemented the application based on the toggleButton selection. but while i close that application and then reopen it, it will get in to its default selection that is "off".
So can any budy tell mw what should i have to save the state of the toogleButton selection and perform some action based on that toggleButton selection state. . .
Thanks.
Use SharedPreferences.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if((tg.isChecked()))
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
}
else
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", false); // value to store
editor.commit();
}
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
if (tgpref = true) //if (tgpref) may be enough, not sure
{
tg.setChecked(true);
}
else
{
tg.setChecked(false);
}
I did not verify this code, but look at some examples on the net, it is easy!
Use SharedPreferences like erdomester suggested, but I modified little bit his code. There's some unneeded conditions.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", tg.isChecked()); // value to store
editor.commit();
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
tg.setChecked(tgpref);
The best way, you can set tgbutton same
screen main
Intent intent = new Intent(this, Something.class);
intent.putExtra(BOOLEAN_VALUE, Boolean.valueOf((tvConfigBoolean.getText().toString())));
startActivity(intent);
screen something
Bundle bundle = getIntent().getExtras();
tbtConfigBoolean.setChecked((bundle
.getBoolean(MainActivity.BOOLEAN_VALUE)));
and save state
editor.putBoolean("BooleanKey", tbtConfigBoolean.isChecked());
editor.commit();
good luck

how to reset all stored data store using shared preferences

I have created an activity where i have used shared preferences for storing data..now in another activity i have an reset button..when i click on the reset button the data store will be lost..so how that can be done..my code is
code in activity1:
public void writeToRegister()
{
// Write history data to register
SharedPreferences preferences1 = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor1 = preferences1.edit();
editor1.putInt("iHistcount", CycleManager.getSingletonObject().iHistCount);
for(int i=0;i< CycleManager.getSingletonObject().iHistCount;i++)
{
editor1.putLong("dtHistoryDate"+Integer.toString(i), CycleManager.getSingletonObject().dtHistory[i].getTime());
}
editor1.commit();
}
public void readFromRegister()
{
// Read history data from register
SharedPreferences preferences1 = getPreferences(MODE_PRIVATE);
CycleManager.getSingletonObject().iHistCount=preferences1.getInt("iHistcount", 0);
for(int i=0;i< CycleManager.getSingletonObject().iHistCount;i++)
{
Long x=preferences1.getLong("dtHistoryDate"+Integer.toString(i), 0L);
CycleManager.getSingletonObject().dtHistory[i]=new Date(x);
}
}
code for Activity 2:
Button pBtnReset = new Button(this);
pBtnNextMonth.setOnClickListener(pBtnReset OnClickListener);
Button.OnClickListener pBtnReset OnClickListenernew Button.OnClickListener()
{
public void onClick(View arg0)
{
}
};
so what i have to write in second activity reset button so that it clear the stored data
Get your Editor and call clear() something like this:
Edit: as the user DDoSAttack mentioned.
There are two ways of getting SharedPreferences
1: getting default SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
2: getting specific SharedPreferences
SharedPreferences prefs = Context.getSharedPreferences("FileName", Context.MODE_PRIVATE);
and here is how you'll clear it.
public void clear()
{
SharedPreferences prefs; // here you get your prefrences by either of two methods
Editor editor = prefs.edit();
editor.clear();
editor.commit();
}
its very easy..
yourEditor.remove(" thing you want to remove on start");
and then give must
yourEditor.commit();
If you want to wipe all the data in a preference file call clear() from the SharedPreferences.Editor instance
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear()
Use SharedPreferences.Editor clear() method.
See Documentation
SharedPreferences preferences = getPreferences(0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

Categories

Resources