Android sharedpreferences force closes - android

I am trying to use sharedpreferences in a PreferenceActivity, but unfortunately it force closes. Part of it:
public class EditPreferences extends PreferenceActivity {
String ListPreference;
boolean CheckboxPreference;
SharedPreferences mprefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (newValue.toString().equals("true"))
{
Toast.makeText(getApplicationContext(), "CB: " + "true", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor edit = mprefs.edit();
edit.putString("cbstate", "true");
edit.commit();
}
else
{
Toast.makeText(getApplicationContext(), "CB: " + "false", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor edit = mprefs.edit(); //this line force closes
edit.putString("cbstate", "false");
edit.commit();
}
return true;
}
});
What is wrong with the code?
Thanks,
B

It doesn't look like mprefs is ever assigned a value (unless it's happening somewhere else)

You should look at the log to see the stack crawl of the exception, which tells you why your code is crashing.
I am not adding this as a question for clarification, because the fact that a stack crawl is not included in the question is a strong indication that you haven't actually looked at it, and if that is the case then the answer to your question and most likely solution to your problem is to go look at that and see why it says you are crashing.

Related

SharedPreferences saves state between android activities but not upon restarting the app

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.

Run code on first OnCreate only

I have a piece of code that I only want to run the very first time a particular OnCreate() method is called (per app session), as opposed to every time the activity is created. Is there a way to do this in Android?
protected void onCreate(Bundle savedInstanceState) has all you need.
If savedInstanceState == null then it is the first time.
Hence you do not need to introduce extra -static- variables.
use static variable.
static boolean checkFirstTime;
use static variable inside your activity as shown below
private static boolean DpisrunOnce=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_once);
if (DpisrunOnce){
Toast.makeText(getApplicationContext(), "already runned", Toast.LENGTH_LONG).show();
//is already run not run again
}else{
//not run do yor work here
Toast.makeText(getApplicationContext(), "not runned", Toast.LENGTH_LONG).show();
DpisrunOnce =true;
}
}
use sharedpreference...set value to true in preference at first time...at each run check if value set to true...and based on codition execute code
For Ex.
SharedPreferences preferences = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
if (!preferences.getBoolean("isFirstTime", false)) {
//your code goes here
final SharedPreferences pref = getSharedPreferences("MyPrefrence", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isFirstTime", true);
editor.commit();
}

Android issue with boolean on shared preferences

Android issue with boolean on shared preferences
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSlide=spref.getBoolean("SLIDE_SHOW",false);
//in isSlide am getting the right value but the if statement is not working
if(isSlide==true){
//if true the page will slide but it works in false too
}
i tried in this link Issue with boolean on shared preferences but the answer is not clear
settings code:
<PreferenceCategory android:title="Slide Show" >
<CheckBoxPreference android:title="Slide Show" android:key="SLIDE_SHOW" />
</PreferenceCategory>
You may want to check if your SharedPreference variables are active. This is an example on how to set the SharedPreference.
To write into SharedPreference:
SharedPreferences prefs = getSharedPreferences("myPref", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("myBool", true);
editor.commit();
To read from SharedPreference:
SharedPreferences prefs = getSharedPreferences("myPref", 0);
if (prefs.getBoolean("myBool", false)) { //myBool is true; }
sorry i will not post the question correctly
The problem is not with preference it returns correct value the problem is in handler which is used to slide the viewpager based on the value which is returned by preference
the handler is running even though the activity is killed below the code solved my problem
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSlide=spref.getBoolean("SLIDE_SHOW",false);
if(isSlide==true)
{
SlideShowTimer();
}
public void SlideShowTimer()
{
mFilterTask = new Runnable() {
#Override
public void run() {
int i=0;
itemPosition = viewPager.getCurrentItem() + 1;
if(itemPosition!=10)
{
if(i <= adapter.getCount()-1)
{
viewPager.setCurrentItem(itemPosition,true);
mHandler.postDelayed(mFilterTask, 3000);
i++;
}
}
else
{
//ViewPagerAdapter.mediaPlayer.stop();
ViewPagerActivity.this.finish();
}
}
};
mHandler.removeCallbacks(mFilterTask);
mHandler.postDelayed(mFilterTask,3000);
}
#Override
public void onDestroy(){
super.onDestroy();
mHandler.removeCallbacks(mFilterTask);
}

Android: updating displayed preferences from SharedPreferences

I'm writing an android app with a preferencesActivity in which selections made in my instance of preferencesActivity affect the values of other preferences items displayed. While I'm able to change the values of the underlying SharedPreferences items pogrammatically, those changed values aren't reflected in the displayed list items until I exit my preferencesActivity and reload it. Below is a stripped down version of my settings class and xml file which illustrate the problem. If a user sets Guitar as the value for the preference with the key instrumentList, I'd like the preference with key tuningChoice to revert to Standard.
//necessary import declarations go here
public class Settings extends PreferenceActivity implements OnSharedPreferenceChangeListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
app_preferences.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) {
Log.d("onSharedPreferencesChanged", "sharedPreferences changed. key: " + key);
Editor preferencesMod = sharedPreferences.edit();
String instrumentChoice = sharedPreferences.getString("instrumentList", "Guitar");
if(key.equals("instrumentList")) {
Log.d("Settings", "key is instrumentList. chooseTuning before if: " + sharedPreferences.getString("chooseTuning", "no luck"));
if(instrumentChoice.equals("Guitar")) {
preferencesMod.putString("chooseTuning", "Standard");
preferencesMod.commit();
Log.d("Settings", "chooseTuning after if: " + sharedPreferences.getString("chooseTuning", "ciao"));
}
}
}
}
xml file preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings">
<ListPreference android:title="Choose an Instrument" android:key="instrumentList" android:entryValues="#array/instruments" android:entries="#array/instruments"/>
<ListPreference android:title="Choose Tuning" android:key="chooseTuning" android:entryValues="#array/tuningChoices" android:entries="#array/tuningChoices" android:persistent="true"/>
</PreferenceScreen>
I can call addPreferencesFromResource again in my onSharedPreferenceChanged method and that loads a duplicate of all the preferences items, displayed below the old items, with the correct values. If I could figure out some way to cancel out the initial addPreferencesFromResource called during onCreate, I guess I would be set.
Any help would be appreciated, Thanks
I do something along these lines...hopefully it helps:
ListPreference list = (ListPreference) getPreferenceManager().findPreference("myList");
list.setValue(sharedPrefs.getString("myList", "default"));
list.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
sharedPrefs.put("myList", newValue.toString());
return true;
}
});
You need to prevent addPReferencesFromResource from running twice? Is this loading your default values? If so, add an additional SharedPreference called DEFAULTS_LOADED and read its value in on create like: (WARNING PSUEDO CODE):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean loadDefaults = app_preferences.getBoolean(DEFAULTS_LOADED, true);
if(loadDefaults)
{
addPreferencesFromResource(R.xml.preferences);
Editor editor = app_preferences.edit();
editor.putBoolean(DEFAULTS_LOADED, true);
editor.commit();
}
app_preferences.registerOnSharedPreferenceChangeListener(this);
}
This will prevent you defaults from being written to the shared preferences every time your activity starts. I assume this is at least a portion of your issue.
If anyone comes to this problem, this is the solution:
ListView list = preferenceActivity.getListView();
list.performItemClick(list, 1, list.getItemIdAtPosition(1));
Maybe I am too late for answering this. But, I hope this might help beginner like me.
PackageInfo packageInfo = null;
try {
packageInfo = preference.getContext().getPackageManager().getPackageInfo(preference.getContext().getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
preference.setSummary(packageInfo.versionName);

Android sharedpreferences

I've been following this tutorial and i am stuck.
public class Main extends Activity {
SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
firstRunPreferences();
if(getFirstRun())
{
Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
setRunned();
}
else
{
Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
}
}
public boolean getFirstRun() {
return mPrefs.getBoolean("firstRun", true);
}
public void setRunned() {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putBoolean("firstRun", false);
edit.commit();
}
public void firstRunPreferences() {
Context mContext = Main.this.getApplicationContext();
mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
}
}`
Everytime i run it in Eclipse it says "not firstrun". I guess the preferences reset every time the app is reinstalled, so what is wrong with the code? As far as i remember, i saw once "firstrun".
Thanks
I am assuming you are using the Emulator to run your app. Are you closing the emulator between runs?
Check if you have the "Wipe User Data" checkbox ticked in the Target tab of your Debug run configuration in Eclipse.
SharedPreferences are not cleaned by uninstall.
If you want something cleaned after reinstall, put a field in your database.
Stéphane
I'm not sure but I think SharedPreferences are removed when uninstalling, but not when updating an app.

Categories

Resources