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
Related
I'm running to a really weird behavior with SharedPreferences. I'm wondering if I'm running into a synchronization issue.
It seems like the app can remember the preference changes in between activities but not when I restart the app. The state always returns back to the very first instance I created a preference. I've followed several examples, tutorials, and android documentation that all suggest similar code layout. I also watched how the preference.xml file changed while interacting with my code using the debugger and I confirmed it looked like the key value pair updated.
Could I be experiencing a synchronization issue with my emulator? I tried using both the editor.apply() method and editor.commit() method with the same results.
The only thing I've found that fixes my problem is using the editor.clear() method, but this feels a bit hacky...
note: please forgive the variable names, I'm making a pokedex...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
Try to use SharedPreferences this way:
To save data
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("stringName", "stringValue");
editor.apply();
To retrieve data
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PREFS", MODE_PRIVATE);
String name = preferences.getString("stringName", "none"));
Note that this "none" is in case to string "stringName" be null.
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.
I have a Settings class so the user can decide to subscribe/unsubscribe to channels in Parse Push.
I think I got it all figure out except for the part to recover, and maintain the switch state next time user open the app or changes the state.
Can someone please help me on how to save the state, and switch the SWITCH to what the user selected?
public class Settings extends Activity {
/**
* Called when the activity is first created.
*/
private Switch krspush, egspush;
public static final String PREFS_NAME = "SwitchButton";
krspush = (Switch) findViewById(R.id.krspush);
egspush = (Switch) findViewById(R.id.egspush);
SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE);
// How?
public void onKrsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
public void onEgsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
Override the onCreate method of that activity class and attempt to load the values you saved in SharedPreferences.
krspush.setChecked(sharedPrefs.getBoolean("onKrsClick",false));
findviewbyid will crash unless called after the view is created ie, in the oncreate method.
Consider using click listener on your switches.
I don't see the point of this line of code "SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE)"
Here is how you use shared preferences : https://stackoverflow.com/a/23024962/2590252
You better look into some samples to learn about best coding practices http://developer.android.com/samples/index.html
I am trying to figure out how I would achieve storing image URLs via onClick of an item button so they can be accessed by another class.
I have looked around and saw that it would be best to achieve this using shared preferences.
I have never used shared preferences before so I am a little confused as how I will be able to achieve this because I would like to get the URL from the String I have called "mImageUrl"
I know my String "mImageUrl" will give me the URL of the image that is currently being viewed, so I like to somehow store the String/URL from my String to shared preferences so the specific URLs can used via another class.
Would using shared prefs be a good way to achieve my requirement,
Any guidance would be appreciated thanks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.SetWallpaper:
new SetWallpaperAsync(getActivity()).execute(mImageUrl);
break;
case R.id.SaveWallpaper:
new SaveWallpaperAsync(getActivity()).execute(mImageUrl);
break;
case R.id.FavouriteWallpaper:
//Use shared preferences here somehow:
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
SharedPreferenceUtil.setSharedPreference(context, "ImageKey", mImageUrl);
String url = SharedPreferenceUtil.getSharedPreference(context,"ImageKey",null);
if(url != null){
// set image source here..
}
break;
}
return super.onOptionsItemSelected(item);
}
Try this code:
Save in SharedPreferences :
SharedPreferences prefs;
prefs = PreferenceManager.getDefaultSharedPreferences(contextActivity);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("imgUrl", UrlString);
editor.commit();
To retrive value:
prefs = PreferenceManager.getDefaultSharedPreferences(contextActivity);
prefs.getString("imgUrl", null);
try this
in one Activity :
SharedPreferences sp;
SharedPreferences.Editor edit;
sp = getSharedPreferences("enter", MODE_PRIVATE);
edit = sp.edit();
edit.putString("imagerul", user_validate);
edit.commit();
in next activity :
SharedPreferences sp = getSharedPreferences("enter", MODE_PRIVATE);
sp.getString("imageurl", "fdgf"));
You can simple implement a class that handles get/set operations of shared preferences.
I will provide a class so that you can easily integrate to your project.
Here is our SharedPreferenceUtil class
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPreferenceUtil {
public static String getSharedPreference(Activity activity, String prefName, String key, String defaultValue){
SharedPreferences prefs = activity.getSharedPreferences(prefName,0);
String pref = prefs.getString(key, defaultValue);
return pref;
}
public static void setSharedPreference(Activity activity, String prefName, String key, String value){
SharedPreferences prefs = activity.getSharedPreferences(prefName,0);
SharedPreferences.Editor editor = prefs.edit();
// edit and commit
editor.putString(key, value);
editor.commit();
}
}
You can simply set/get preference from your activity with the following code sample.
// You can set your shared preferences like following.
SharedPreferenceUtil.setSharedPreference(this.getActivity(),"pref","yourImageKey","yourImageUrl");
// and you can get your shared preferences like following.
String url = SharedPreferenceUtil.getSharedPreference(this.getActivity(),"pref","yourImageKey",null);
if(url != null){
}
EDIT:
You can reach SharedPreferences from a Fragment by following
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
Hope this may help.
Try:
SharedPreferences pr=PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor r=pr.edit();
r.putString("name","yourlink");
r.commit();
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();
}
}