Android SharedPreferences is not saving after re-opening the application - android

I am trying to add a function named removeCard, this function receives an array of strings. This array length is 48 and the strings inside this array contains a name of a card, i.e prince or knight. If a String inside this array is null it means there is no more card to delete (the game contains 48 cards but maybe I want to delete just 2 of them).
All my cards are saved in SharedPreferences with the key key1. This function is supposed to remove from the key all the cards inside the array (if someone accidentally added the prince but he didn't unlock it yet).
However, this function works fine and when I return to the main3.class intent it shows the cards inside the array were removed from the SharedPreferences key but when I close the application and re-open it, they remain like they never were removed.
Here is my code:
public static void removeCard(String[] s) {
Set<String> used;
used = prefs.getStringSet("key1", null);
for (String card : s) {
if (card != null)
used.remove(card);
else
break;
}
editor.putStringSet("key1", used);
editor.commit();
Intent k = new Intent(cont, main3.class);
cont.startActivity(k);
}
Also, the array contains the cards to remove is being created when you click on a ListView item (each item is a card). result[position] is the card name and cards is the array contains values to remove:
#Override
public void onClick(View v) {
if (position == 0) { // back button pressed
main2.removeCard(cards);
main2.cont.finish(); // close main2 activity
} else {
Toast.makeText(context, result[position] + " Picked", Toast.LENGTH_LONG).show(); // Toast the card you picked
if (!Arrays.asList(cards).contains(result[position])) { // if card is not already in array, add it.
cards[count] = result[position];
count++;
}
}
}
This is how I'm getting the editor of the SharedPreferences.
public static SharedPreferences prefs;
public static SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
cont = this;
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(new CustomAdapter(main2.this, mDrawableName, mDrawableImg, n));
prefs = getSharedPreferences("MyPrefs", 0);
editor = prefs.edit();
}
And also, to display the cards you have from the other activity I used:
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
Set<String> cards = pref.getStringSet("key1", null);
tv1.setText("Available cards: " + cards);

Related

Shared Preferences no longer saving

I have an activity that saves ListView objects to an ArrayList and loads them upon OnCreate.
I tested it out last night and it worked perfectly, however when I tested it again today, it's loading what it already has saved from yesterday, but it is no longer saving new list items.
Here's my code:
public class SubActivity extends AppCompatActivity {
Button addItem;
ImageButton back;
Button saveListBtn;
private ListView listViewer;
ArrayList<ItemObjects> items = new ArrayList<ItemObjects>();
private String key = "arg";
//Retrieves the saved preferences from the given kay: value pair.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment1_item_screen);
Bundle extra = getIntent().getExtras();
String extraString = extra.getString(key);
//This loads the items from sharedPreferences and is working correctly.
if(loadList(extraString) != null){
items = loadList(extraString);
}
//Loads the listView with the correct information.
final ItemObjectsAdapter adapter = new ItemObjectsAdapter(this,
items);
listViewer = (ListView) findViewById(R.id.itemListView);
listViewer.setAdapter(adapter);
//At the push of a button, a new object is added to the items ArrayList. I'm just putting in a blank object for now. The issues comes at saveList(items, key). It doesn't seem to be working correctly, but it did yesterday, since every time I load the activity, 4 list items are loaded from sharedPreferences, however, I cannot seem to save anymore.
addItem = (Button) findViewById(R.id.addItemBtn);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ItemObjects blank = new ItemObjects("", "", "", "");
items.add(blank);
saveList(items, key);
adapter.notifyDataSetChanged();
}
});
//Here's the code I have for saving the items list. Note this worked yesterday, I haven't changed anything with it yet.
private void saveList(ArrayList<ItemObjects> list, String key) {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
prefsEditor.putString(key, json);
prefsEditor.apply();
}
//This is just the code to load the items from sharedPreferences and seems to be working correctly.
private ArrayList<ItemObjects> loadList(String key) {
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<ExerciseObjects>>() {}.getType();
return gson.fromJson(json, type);
}
}
Any ideas as to why it's not saving?
Ok so looks like saveList(items, key); is supposed to be saveList(items, extraString);
It works now.

Getting an array from SharedPreferences

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.

Save and Load strings

I used Menu onOptionsItemSelect(MENU) to save and load strings like this
public static String filename = "MySharedString";
SharedPreferences someData;
String s;
someData = getSharedPreferences(filename, 0);
case R.id.save:
Toast.makeText(getApplicationContext(), "Samples saved", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor1 = someData.edit();
editor1.putString("ourString1", s);
and load like this
case R.id.load:
s = someData.getString("ourString1", "Couldn't Load Data");
and it worked well...as android removed MENU button for many devices i made a new activity which extends MainActivity and I put in Save and Load button.
public void bSave (View v){
SharedPreferences.Editor editor1 = someData.edit();
editor1.putString("ourString1", s);
editor1.commit();
and load
public void bLoad (View v){
s = someData.getString("ourString1", "Couldn't Load Data");
For some reason it doesnt work, I repeat i made new activity ( public class Menu extends MainActivity{ ) which i start as Intent and it wont save or load strings from MainActivity
make sure you are using the button listener properly. check if you set android:onClick attreibute like
android:onClick="bSave"

Android: how to get list of all preference xml's for my app and read them?

how to get list of all application preferences for application,
1. I am saving shared preference in this manner
2. I know that they are in data/data/app_packagename/shared_prefs
3. THE PROBLEM: But how to get list of all preference xml files in a spinner
and read each preference, i searched in SO, but i did not found any help regarding this, how to do read all preference xml files in my application directory and access the preferences?
P.S: I am aware of SharedPreference.getAll();, will be enough to read once i get the file?
I have wrote in bits(Rough Code), it give error when tried to run, here is the implemented method
void getList()
{
//will be invoked from onCreate to populate spinner,yes spinner is already binded
PackageManager m = getPackageManager();
String s = getPackageName();
try {
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
} catch (NameNotFoundException e) {
Log.w("yourtag", "Error Package name not found ", e);
}
Log.i("dir", s=s+"/shared_prefs");
//is this write way, how to proceed from here
}
Try this
File prefsdir = new File(getApplicationInfo().dataDir,"shared_prefs");
if(prefsdir.exists() && prefsdir.isDirectory()){
String[] list = prefsdir.list();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, android.R.id.text1,list);
Spinner sp = (Spinner) findViewById(R.id.spinner1);
sp.setAdapter(adapter);
}
//To get the selected item
String item = (String) sp.getSelectedItem();
//remove .xml from the file name
String preffile = item.substring(0, item.length()-4);
SharedPreferences sp2 = getSharedPreferences(preffile, MODE_PRIVATE);
Map<String, ?> map = sp2.getAll();
for (Entry<String, ?> entry : map.entrySet()){
System.out.println("key is "+ entry.getKey() + " and value is " + entry.getValue());
}
If you want to use reflection, there is an #hide function Context#getSharedPrefsFile(String name)
So you would call
Context#getSharedPrefsFile(String name).getParentFile() to get a reference to the shared_prefs dir
public class Preferences extends PreferenceActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// load the XML preferences file
addPreferencesFromResource(R.xml.preferences);
}
}
Then in your main class, you can refer to the preferences
public class DrinkingBuddy extends Activity
implements OnSharedPreferenceChangeListener {
private int weight;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// register preference change listener
prefs.registerOnSharedPreferenceChangeListener(this);
// and set remembered preferences
weight = Integer.parseInt((prefs.getString("weightPref", "120");
// etc
}
// handle updates to preferences
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.equals("weightValues")) {
weight = Integer.parseInt((prefs.getString("weightPref", "120");
}
// etc
}
}
The saving of preference updates is handled for you.
(Not too sure about public/private declarations!).

Shared preferences wont save before closing the app or activity

I am making an activity that will edit the shared preferences just when the activity starts before it executes any functions. I am stuck and dont know how to. My app only edits the shared preferences when i close the app or go back to another activity. I want to edit them when the activity starts without executing any function ie checkpreferences();.Precisely How to edit the shared preferences on start of activity?
public class MyActivity extends Activity {
private SharedPreferences app_preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the app's shared preferences
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
final int id = 42;
int idd = app_preferences.getInt("idd", 0);
// I am Stuck in this part
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("idd", 43);
editor.commit(); // Very important
final int iddd = idd;
checkpreferences(id, iddd);
}
private void checkpreferences(int di, int dii) {
if(di == dii) {
Toast.makeText(AudioActivity.this,"id is same"+dii+"="+di , Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(AudioActivity.this,"id is different"+dii+"!="+di, Toast.LENGTH_SHORT).show();
}
}
}
I think the error is here
you are tryinh to fetvh the value of shared preference before saving it
// Fetching of value
int idd = app_preferences.getInt("idd", 0);
Log.e("value " , " is " + idd);
as at this time there shall be no value in preference
// and commitng after it
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("idd", 43);
editor.commit(); // Very important
you should save preference before fetching
and to assure it print the logs as well

Categories

Resources