Shared Preferences no longer saving - android

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.

Related

how to save fragments data to show to next login

i have this application
when user press at day on the calendar adds a new fragment with a tag of this date. He put data on fragments and show it in a linear layout like that . Can I save fragments in my sqlidatabase with contentProvider and contentResolve so when user login again to have this data in the linear layout? Or I have to try something else?
I try to save the Fragments with Gson.
1) I got the fragments from manager to a List.
2)Save the List with gson as json in a string variable
and
3)get the fragments with type-typeToken
#Override
protected void onPause() {
super.onPause();
Log.d(TAG,"onPause");
SharedPreferences sharedPreferences=getSharedPreferences("FragmentsList",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
manager=getFragmentManager();
fragmentList = manager.getFragments();
if (fragmentList!=null) {
Gson gson = new Gson();
String json = gson.toJson(fragmentList); // error here cant serialize context
editor.putString("ListFragment", json);
}
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("FragmentsList",Context.MODE_PRIVATE);
String jsonreader=sharedPreferences.getString("ListFragment",null);
Type type = new TypeToken<List<Fragment>>(){}.getType();
Gson gson = new Gson();
manager=getFragmentManager();
fragmentList=gson.fromJson(jsonreader,type);
if (fragmentList!=null) {
for (Fragment fragment : fragmentList) {
manager.putFragment(bundle, "BundleFragment", fragment);
}
}
}
With this code, I got an error when I try to save the list with gson.tojson because I think fragments have context and can't get the format to json

Delete An ArrayList from SharedPreferences

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.

Android SharedPreferences is not saving after re-opening the application

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);

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.

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!).

Categories

Resources