Getting shared preferences data of another class - android

Im trying to make a favorites list. I have this class called Animal and another called Favorites. The favorites arraylist is created in the class Favorites. I can access the favorites arraylist from Animal with
public static Favorites addfavorite = new Favorites();
and add items to the favorits list.
As the items that are added from the Animal class to the favorites list i need this arraylist to be saved. I tried to do this with SharedPreferences. It almost works. After adding items and completely closing and reopening the app i get the following problem.
Problem:
If i open the app and go to the Animal class, without opening the Favorites class first and seeing the previously added items (So the OnCreate() method for Favorites hasn't been called yet), and if i add or dont add a new item to favorites list (it doesn't matter) while I'm in Animal class, when i open the 'Favorites' class the previously added items are deleted and replaced by the newly added ones if new items are added, if not the list becomes empty. (I dont want this i need to have both the old and new items) But if i first open the Favorites class and see the previously added items(thus having the 'OnCreate()' method be called for 'Favorites') and then go to the Animal class and add new items both the new and old items are listed in 'Favorites'. (This is what I'm trying to achieve)
How do i fix this problem?
EDIT: Some code from Animal
#Override
protected void onPause() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(PREFS_NAME,
new HashSet<String>(addfavorite.getFavorites()));
editor.commit();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
favoritesanimal = new ArrayList<String>(prefs.getStringSet(PREFS_NAME,
new HashSet<String>()));
super.onResume();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putStringArrayList(PREFS_NAME, addfavorite.getFavorites());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null
&& savedInstanceState.containsKey(PREFS_NAME)) {
favoritesanimal = savedInstanceState.getStringArrayList(PREFS_NAME);
}
}
favoritesanimal is an arbitrary arraylist i created. It isnt related to the Favorite class or the favoriteslist Its actually useless. So the onPause() and onResume methodes do nothing at the moment.
And here is code from Favorites (notice i am using the same sharedpreferences attributes in both classes)
#Override
public void onCreate(Bundle savedInstanceState) {
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
favorites = new ArrayList<String>(prefs.getStringSet(PREFS_NAME,
new HashSet<String>()));
super.onCreate(savedInstanceState);
//As you can see i added SharedPreferences to OnCreate
//more code..
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(PREFS_NAME, new HashSet<String>(favorites));
editor.commit();
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
favorites = new ArrayList<String>(prefs.getStringSet(PREFS_NAME,
new HashSet<String>()));
super.onResume();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putStringArrayList(PREFS_NAME, favorites);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null
&& savedInstanceState.containsKey(PREFS_NAME)) {
favorites = savedInstanceState.getStringArrayList(PREFS_NAME);
}
}

I think that, when you use addfavorite.getFavorites(), this method returns empty list. And when you goes to Favorites class, onPause() method in Animals class is called and rewrote your preferences.

Related

My shared pref listener wont' listen

I have followed the Google dev docs and come up with the following shared preference activity:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// TODO Auto-generated method stub
Toast.makeText(this, "Pref changed", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
getApplicationContext().getSharedPreferences(this.getLocalClassName(), MODE_PRIVATE).registerOnSharedPreferenceChangeListener(this);
//Toast.makeText(this, "registered pref listener", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
getApplicationContext().getSharedPreferences(this.getLocalClassName(), MODE_PRIVATE).unregisterOnSharedPreferenceChangeListener(this);
}
}
As you can see, I have a simple toast message in the onSharedPreferenceChanged method so I can see it working, but it doesn't seem to work.
The only difference with the Google docs is that I am using getApplicationContext() instead of getPreferenceScreen() in the onResume(), because getPreferenceScreen() is showing up as deprecated.
I just need to figure out why its not listening - my preference screen is just full of checkboxes, so I would assume, when I click any of them, the onSharedPreferenceChanged() method is called and I would see my toast.
This simple one has got me stumped.
You are registering your listener to a wrong preference.
Loaded preference from XML resource in SettingsFragment uses default shared preferences so you should register the listener like this:
#Override
public void onResume() {
super.onResume();
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
pref.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
pref.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}

Android: Unable to get preference values from settings.xml

I have a settings.xml in my res folder to manage user settings. I load this into a fragment. I require to store these settings to a backend service for this I want to know what values have been by the user or whenever user changes a setting I want to know so that I update the server about the settings.
I have tried many approaches as shown in the code below but I am unable to read the value. I tried putting Toast and log statements to check the listeners but nothing is appearing which indicates that listener is not getting called. Am I doing something wrong?
UserSettingFragment.java
public class UserSettingFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
//Method 1
PreferenceScreen shared = getPreferenceScreen();
shared.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// TODO Auto-generated method stub
Toast.makeText(getActivity().getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
Log.d("preference", "change");
return true;
}
});
final SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Preference gender = (Preference) findPreference("gender");
//Method 2
// Get the custom preference
Preference mypref = (Preference) findPreference("mypref");
mypref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// TODO Auto-generated method stub
String highScore = sharedPref.getString("gender", "Male");
Toast.makeText(getActivity().getApplicationContext(), "Changed to " + highScore, Toast.LENGTH_LONG).show();
Log.d("preference", "change");
return false;
}
});
} //Method 3
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
Toast.makeText(getActivity().getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
}
settings.xml
<?xml version="1.0" encoding="utf-8"?>
<SwitchPreference
android:key="gender"
android:title="I am"
android:switchTextOn="Female"
android:switchTextOff="Male"
/>
</PreferenceCategory>
Since you are using a PreferenceFragment you need to register and unregister OnSharedPreferenceChangeListener in the onResume and onPause methods for method #3 that you mentioned in your question.
public class UserSettingFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(getActivity().getApplicationContext(), "Changed key: " + key, Toast.LENGTH_LONG).show();
}
}
Reference

what should I do[Shared Preferences]

I want to save 2 variable when application stopped and I want to use these variables when application restarted.I'm using sharedpreferences but I couldnt solve.
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
for(int k=0;k<=secili.length;k++){
if(secili[k]!=0)
cevapdizisi[k]=secili[k];
}
for(int m=100;m>=0;m--){
if(m!=0){
sonsoru=m;
break;
}
in onStop there isnt problem
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
setContentView(R.layout.answerpage);
txtquestion.setText(questions[sonsoru]);
rdiogroup.check(secili[sonsoru]);
}
in onRestart can't accessing txtquestion and rdiogroup.I'm created them on OnCreate.What should I do.I cant created them again onRestart.it will absurd.there must be another way.I need a help
To store values in shared preferences you may use following code:
public class MainActivity extends Activity{
SharedPreferences prefs;
EditText edTextName,edTextPassword,edTextServer;
protected void onCreate(Bundle arg0) {
.
.
//do your stuff...
.
prefs= this.getSharedPreferences("UserInfo", MODE_PRIVATE);
String hostname = prefs.getString("HostName", null);
String name = prefs.getString("UserName", null);
String password = prefs.getString("Password", null);
}
protected void onStop() {
.
//do your stuff...
.
SharedPreferences.Editor editor = prefs.edit();
editor.putString("HostName", edTextName.getText().toString());
editor.putString("UserName", edTextPassword.getText().toString());
editor.putString("Password", edTextServer.getText().toString());
editor.commit();
}
}

How to update ListPreferences after implementing OnChangeListener

I have PrefActivity and I use OnChange Listener to make a toast when ever user change any button in list preferences.
But now I have 2 problems:
1-first time that user change an option toast is not shown
2-after that, when ever user change prefrences, the value of list is not updated, and is always set on second value.
this is my code:
public class PrefsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener{
private ListPreference myPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences arg0, String key) {
ListPreference lp = (ListPreference) findPreference("blocktype");
lp.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// TODO Auto-generated method stub
Toast.makeText(PrefsActivity.this, "second", Toast.LENGTH_LONG).show();
return false;
}
});
}
}
What is
As no one answered my question I figured out, where is problem.
return false
should be changed to
return true
in order to update the preferences

Not understanding extended class correctly

Bassicly my aim is too extend a activity so when the user presses Next how many times he wants to , i want to be able to display the value in the Activity2.
I want to somehow still keep the values stored into the variables even when i go into a new activity - im not too sure if thats possible. Any help would be appreciated
1st class
public class Activity extends Activity1 implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.Next:
if (value==0) {
value=1;
}
else if(value==1){
value=2
break;
}
case R.id.one:
Intent i1 = new Intent(this, Form.class);
startActivity(i1);
}
}
}
2nd Class
public class Activityv2 extends Activity1 implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button:
if(value==1){
display.setText("1");
}
else if(value==2)
{
display.setText("2");
}
}
}
}
you can store the value in a public static field.
Edit: or you can save it in SharedPreferences, or pass this value through the activity using the bundle
For instance you can save it in this way:
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private String loadPreferences(String key, String value){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
return settings.getString("silentMode", "");
}
You can pass values between Activities and Fragment via a Bundle or an Extra in the Intent class.
To retrieve these back, in an Activity you would call getIntent() and either get the Extra out of this, or call getExtras() on the returned Intent to get the Bundle. In a Fragment you would call getArguments() which returns a Bundle.
Bundles are very handy, allowing you to pass primitive data easily between Activities.
Another option is to store these values in your own class which extends from Application, which you can then access anywhere and at any time.

Categories

Resources