views:

98

answers:

2

I want to have the status of a checkbox be saved into my prefs.

I set a listener on the checkbox, and if it is checked I do a prefs.putBoolean("cbstatus", true), and it is it unchecked i do a prefs.putBoolean("cbstatus", false);

Trouble is, in my onStart() when I get prefs, my Boolean getcbstatus = prefs.getBoolean("cbstatus", false); will always return a true, regardless of how my listener should have set that status previously.

What am I doing wrong? I have working prefs for other things like spinners, textviews, and edit texts, but what should be the simplest type (a boolean) is giving me a hard time.

I've even tried taking out all code related to listeners and pref setting for this checkbox, so that the only code in the entire activity that deals with the checkbox is in the line

Boolean getcbstat = prefs.getBoolean("cbon", false);
    if (getcbstat = true) {
        cb1.setChecked(true);
    }
    else {
        cb1.setChecked(false);
        format.setVisibility(View.VISIBLE);
    }

Since there is no cbon preference (i deleted them all), it should return false by default and the box should be unchecked since. cb1, of course, is the name of my checkbox.

Any ideas?

Update on the code:

OnClickListener cb = new OnClickListener() {
    public void onClick(View v) {
        if (cb1.isChecked()) {
            prefs.putBoolean("cbon", true);
        }
        else {
            prefs.putBoolean("cbon", false);
        }
    }
};

And in the onStart():

        Boolean getcbstat = prefs.getBoolean("cbon", false);
        cb1.setChecked(getcbstat);
+2  A: 

You've accidentally assigned it to true in your if statement.

Change it to this

if (getcbstat == true)

[Edit -- How to use shared preferences (instead of Java's preferences class)] How to use SharedPreferences:

private SharedPreferences mPref;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);

mPref = getSharedPreferences("my_prefs_file", MODE_PRIVATE);

//Other onCreate code goes here...

}  

//Example of where you might want to save preferences
@Override
protected void onPause() {
super.onPause();
Editor prefEdit = pref.edit();

prefEdit.putBoolean("cbon", true);
prefEdit.commit();

}

When you need to read it later:

//Example of where you might want to save preferences
@Override
protected void onResume() {
super.onResume();
boolean getcbstat = pref.getBoolean("cbon", false);
}

It would probably be a good idea to make the pref variable class level and get the preferences object in the onCreate section. Change "my_prefs_file" to whatever you like, but remember that that string is what you will use to access that that particular set of preferences from within your application. I also recommend using constants instead of raw strings for the access keys (like "cbon").

Good luck:)

Marloke
Alright I did that, but now it always returns false. I just don't understand what mechanic is at work now... why would it always return false if the only issue with the code was the "=="? I even set up a discrete button to set the cbon pref to true, independent of the listener. It still doesnt work, and always comes up false.
Sean
Please show the code where you are setting the preference. Also, make sure you are running a commit(); on your preferences edit object after you are done assigning values.
Marloke
could you explain what the commit(); does? I'm not using sharedpreferences, and I'm not sure what a preference edit object is.
Sean
If you're not using SharedPreferences, what is this pref object you're using above? Could you show us the declaration?
Marloke
Preferences prefs = Preferences.userNodeForPackage(getClass ());
Sean
Java's preferences object is not well supported in android. I did a quick google search and found a number of people having problems getting it to work (but no one with any answers). One of the main complaints is that it doesn't seem to keep its state very well. The official mechanism (and the one most folks use) is SharedPreferences. I recommend switching to that unless there's a very compelling reason not to do so.
Marloke
Thanks for all the help Marloke! Now that I'm switching to SharedPreferences, could you explain how to use this editor and commit function? Or maybe point me in the direction of a tutorial for it?
Sean
I'll edit my answer above.
Marloke
Eclipse isnt returning and any errors but my app now force closes when running it in my emulator. Is it possible to use sharedpreferences for just the checkbox, leaving regular Preferences for the rest of my app, or do I have to switch over completely?
Sean
Also, eclipse couldn't resolved "Editor", and I tried using SharedPreferences.Editor instead, which worked (as far as syntax at least). Is that proper or should I be importing some other package besides android.content.SharedPreferences; ?
Sean
SharedPreferences.Editor is fine (its the same object). Are you getting any errors in logcat when you run the app? It shouldn't just close without any errors. I'd recommend switching everything to shared preferences instead of preferences to be consistent. Preferences wasn't actually saving the boolean value before it may also have problems with other values in the future.
Marloke
here's what logcat says when I run the app:
Sean
From AndroidRuntime, ERROR: thread attach failed
Sean
Are there any other errors? Do you have a stack trace for when the application crashes?
Marloke
Posting it in an answer
Sean
A: 

rebooted the emulator, got a whole bunch of new errors when I ran the app fresh.

10-06 05:18:34.045: ERROR/AndroidRuntime(223): Uncaught handler: thread main exiting due to uncaught exception
    10-06 05:18:34.115: ERROR/AndroidRuntime(223): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.sean.sean/com.sean.sean.dofcalc2}: java.lang.NullPointerException
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2402)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2497)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.app.ActivityThread.access$2200(ActivityThread.java:119)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1848)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.os.Handler.dispatchMessage(Handler.java:99)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.os.Looper.loop(Looper.java:123)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.app.ActivityThread.main(ActivityThread.java:4338)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at java.lang.reflect.Method.invokeNative(Native Method)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at java.lang.reflect.Method.invoke(Method.java:521)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at dalvik.system.NativeStart.main(Native Method)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223): Caused by: java.lang.NullPointerException
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at com.sean.sean.dofcalc2.<init>(dofcalc2.java:47)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at java.lang.Class.newInstanceImpl(Native Method)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at java.lang.Class.newInstance(Class.java:1479)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2394)
    10-06 05:18:34.115: ERROR/AndroidRuntime(223):     ... 11 more
    10-06 05:18:34.135: INFO/Process(50): Sending signal. PID: 223 SIG: 3
    10-06 05:18:34.135: INFO/dalvikvm(223): threadid=7: reacting to signal 3
    10-06 05:18:34.145: ERROR/dalvikvm(223): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
Sean
The null pointer probably means some variable isn't getting set. Please show me the whole method where you are calling getSharedPreferences. Failing that, put in some breakpoints around that line and see what isn't getting populated at runtime.
Marloke
I had to block out every preference setting and disable the main SharedPreferences prefs = getSharedPreferences("remember", MODE_PRIVATE); line to stop the forceclose issue. As soon as I called a SharedPreference, the app became unstable. Even without invoking prefs, just defining it forces the program to close. What could be causing this?
Sean
Yeah it looks from the logcat output that where you are defining SharedPreferences is the problem. Where are you defining it? Can you post some code of how you are using it? It might provide me with some insight as to why this isn't working.
Marloke
I'm defining it after I extend the activity and before the onCreate section. Should I move it elsewhere? Theres a lot of code, I don't want to paste it all.
Sean
Basically though its just public class dofcalc2 extends Activity { [naming a bunch of TextViews etc] SharedPreferences prefs = getSharedPreferences("remember", MODE_PRIVATE); SharedPreferences.Editor edit = prefs.edit();@Override public void onCreate(Bundle savedInstanceState) {etc.
Sean
That shared preferences needs to be inside of a method. Try moving it inside the OnCreate. I'll edit my example above to give you a better idea.
Marloke
Finally have it all sorted out! Thank you so much Marloke for all of your help, I never would have been able to figure this out on my own. I ended up doing a save on the box status in the onStop method and that cleared up the very last of my issues. Thanks again for everything, this site and you in particular have been a wonderful resource for a *very* novice programmer
Sean