I know there are couple examples of this but i tried many of them and i couldn't fix my issue.I want to delete an ArrayList from my shared preferences.
I create my ArrayList on shared preference in the first activity:
public void saveArrayList(ArrayList<String> list){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString("testShared", json);
editor.apply(); // This line is IMPORTANT !!!
}
On my second activity i retrieve my array like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_food_basket);
alreadyAddedFoodtest = (ListView) findViewById(R.id.alreadyAddedList);
registerForContextMenu(alreadyAddedFoodtest);
getArrayList();
}
public ArrayList<String> getArrayList(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(AddFoodBasket.this);
Gson gson = new Gson();
String json = prefs.getString("testShared", null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
itemsAdded=gson.fromJson(json, type);
return itemsAdded;
}
And finally i delete the arrays items in my second activity here:
public boolean onContextItemSelected(MenuItem item){
if(item.getItemId()==R.id.delete){
AddFood add=new AddFood();
count--;
countTextbasket(count);
Toast.makeText(getApplicationContext(),"Διαγράφηκε"+item,Toast.LENGTH_LONG).show();
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); // init the info the position from
itemsAdded.remove(info.position); // remove the item from the list
addedAdapter.notifyDataSetChanged();//updating the adapter
SharedPreferences preferences = getSharedPreferences("testShared", MODE_PRIVATE);
preferences.edit().clear().apply();
}else{
return false;
}
return true;
}
The problem is that
SharedPreferences preferencesgetSharedPreferences("testShared", MODE_PRIVATE);
preferences.edit().clear().apply();
Doesn't work so when i open my activity again the list is there again.
getSharedPreferences() doesn't do what you think it does. The String you pass to it is the name of that set of SharedPreferences and anything stored in that instance will be in its own file.
For instance, using
getSharedPreferences("hello", ...).edit().putString("test", "something").apply();
will create a whole new file in your app's data directory (preferences_hello.xml), where the test/something key/value is stored.
getSharedPreferences() doesn't get a specific preference, it gets a specific set of preferences. getDefaultSharedPreferences() actually calls getSharedPreferences() internally and passes your app's package name.
You are currently saving testShared to the default SharedPreferences (getDefaultSharedPreferences()). If you want to clear that value, use
PreferenceManager.getDefaultSharedPreferences(context).edit().remove("testShared").apply();
When you clear the prefs you do this:
SharedPreferences preferences = getSharedPreferences("testShared", MODE_PRIVATE);
This means you want a specific preference set with that name. Your other preferences aren’t named so they will be a different set.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(AddFoodBasket.this);
Use the exact same way to get the preferences and then set the key you want to null, or if you want to delete all preferences you can clear() them.
Related
and sorry if this is a stupid question. I'm learning to use SharedPreferences and I have a bit of a problem:
I'm using this code to save to SharedPreferences:
public void saveInMemory(String[] saveThis){
StringBuilder sb = new StringBuilder();
prefs = PreferenceManager.getDefaultSharedPreferences(OIBListActivity.this);
editor = prefs.edit();
for (int i = 0; i < saveThis.length; i++) {
sb.append(saveThis[i]);
sb.append(";");
}
editor.putString("listaOIB", sb.toString());
editor.commit();
}
And this code to load saved values:
public String loadFromMemory(String id){
prefs = PreferenceManager.getDefaultSharedPreferences(OIBListActivity.this);
return prefs.getString(id, "NOPREFSAVED");
}
I've also already declared prefs and editor outside, so that shouldnt be a problem:
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
Now, my problem is that when I enter this activity and save files that i received from other activity(via putExtra, if that helps), then proceed to load it everything works fine.
Then I reenter my activity without sending any files to it (from other activity) and try to use loadFromMemory() and it doesnt work. My understanding is that it should have saved files when I entered Activity for the first time, and then load it whenever I want.
Any help?
add the method and call when you add and other is call when you get
//this method is call when you add the data
public static void setAlarmHourTime(String value, Activity activity) {
SharedPreferences.Editor pref = activity.getSharedPreferences("ALARMHOURTIME", Context.MODE_PRIVATE).edit();
pref.putString("alarmhourtime", value);
pref.commit();
}
//this method is call when you retrive the data
public static String getAlarmHourTime(Activity activity) {
SharedPreferences prefs = activity.getSharedPreferences("ALARMHOURTIME", Context.MODE_PRIVATE);
return prefs.getString("alarmhourtime","7");
}
if you want to retrieve content saved in editor.putString("listaOIB", sb.toString());, then the id you pass in loadFromMemory should be "listaOIB".
Is it the case?
I have a fragment where I let set some SharedPreference values set.
In the fragment, everything works fine - I can get any value I want, saving, editing, deleting works fine.
Then I have an Activity, from where I want to get the value "savedValue1" - but it does not work
public static final String MyPref = "MyPreference";
static SharedPreferences sharedpreferences;
//onCreateView...
sharedpreferences = this.getActivity().getSharedPreferences(MyPref,
Context.MODE_PRIVATE);
editor.putString("savedValue1", someString);
editor.commit();
I tried it with in Fragment:
public static String getValue(){
return sharedpreferences.getString("savedValue1","");
}
in Activity:
String newValue = Fragment.getValue();
But that doesn't work - any hint?
You should not have a Fragment.getValue() method.
SharedPreferences are here to avoid that.
Use the same getSharedPreferences("whatever", Context.MODE_PRIVATE) code and you shall get/set the same values inside the same preferences.
That is how it is supposed to be used. From the official documentation:
For any particular set of preferences, there is a single instance of
this class that all clients share.
Use this code to save and retrieve values from SharedPreferences
//To save string
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putString("savedValue1", someString);
e.commit();
//Retrieve team score
String saved_value = settings.getString("savedValue1", "");
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();
}
}
I am trying to save a date in one activity and then have that date put in a textView in another activity. I am not sure about how to get the two activities to communicate with each other.
In file called report.java I have this method that gets the date and save it in sharedPrefernces.
private void updateLabel() {
date.setText(fmtDate.format(dateAndTime.getTime()));
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("date", date.getText().toString()); // value to store
editor.commit();
}
I am trying to figure out how to get my file called inspection use this to populate a textView
The problem I think I am having is with getting the correct name for the report file.
public static final String PREF_FILE_NAME = "report";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
then I have this code on a method called onResume()
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String strDate=preferences.getString("date", date.getText().toString());
date.setText(strDate);
}
You are saving the value to two seperate preference files.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
Use only one.
Why not use the default preference file that is accessible by all classes/activities of your app?
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(yourContext);
preferences.edit().putString(YOURKEY, yourStrValue);
This way you are not creating extra preference files in your app that you have to remember which values are stored in which files. Definately makes life easier.