android - Clearing cache of CheckBoxPreference - android

I am developing a PreferenceActivity where I can add CheckBoxPreference instances according to some dynamic content. I also maintain a count of the checked preferences in the activity. Everything is good when I load the application for the first time. But when I select some 2-3 check boxes and deploy the application code again on emulator, the previously selected check boxes just remain checked when I come back to same activity. The same happens when I move to and from some activities within the same application!
To prevent this, every time when I create an instance of CheckBoxPreference, I explicitly call .setChecked(false)!!! But still those previously checked preferences remain checked only!
I can't understand the behavior! Does it bring those values checked from cache! But I explicitly call .setChecked(false), what about that then?
Thank you very much,
Ketan
EDIT : Here is my code:
String content = null;
for (String title : titles) {
checkBoxPref = new CheckBoxPreference(this);
checkBoxPref.setKey(title);
checkBoxPref.setTitle(title);
<b>checkBoxPref.setDefaultValue(Boolean.FALSE); //Line # 1 set default to false
checkBoxPref.setChecked(false);//Line # 2 set checked = false </b>
content = config.getString(title, "Yet to define!");
if (content.length() > 30) {
content = content.substring(0, 30);
}
checkBoxPref.setSummary(content);
checkBoxPref.setOnPreferenceChangeListener(new MyCheckBoxChangeListener());
checkBoxPreferenceList.add(checkBoxPref);
inlinePrefCat.addPreference(checkBoxPref);
}
This code is executed everytime I app comes back to this activity! But still had I checked 2-3 checkboxes before leaving this activity, they will remain in the same state when app comes back to this! Please have a look at the code, I am already setting setChecked(false) explicitly, but still can't get them unchecked!
Please suggest some solution! I am stuck!

You will probably have to post some code to get a better answer. I had this same issue when I had my checkbox inside my adapter. I got around the issue by handling the checkbox with an onClickListener:
CheckBox menuOption = (CheckBox) v.findViewById(R.id.list_checkbox);
menuOption.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
CompoundButton cb = (CompoundButton) v;
// code to set preference goes here
// can check if true or false with cb.isChecked()
}});

Related

How to checkbox checked always even after app relaunch until user uncheck it in android?

My question is simple i want to checked checkbox for always even app is closed and relaunch. This process should continue till user itself uncheck it. If user itself uncheck it then should be uncheck till user checked it again in android .
Please guide me how can I do this.
Use this one simple code ......
Use SharedPreferences to maintain state of check boxes.
Initialization....
checkBox.setChecked(getSharedPreferences("MyAPP", Context.MODE_PRIVATE).getBoolean("checkBox", true));
OnCheckedChangeListener
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getSharedPreferences("MyAPP", Context.MODE_PRIVATE).edit().putBoolean("checkBox", isChecked).commit();
}
});
First time all check boxes will be checked and it will be work like you want....
Above code only for one check box. Try same for other check-boxes. Just change unique key for all check boxes like i used here "checkbox" in checkBox.setChecked(getSharedPreferences("MyAPP", Context.MODE_PRIVATE).getBoolean("checkBox", true));
hope your work done by this.....
For that you have to use SharedPreferance globally to store the default value of check box and change value inside the preference onCheckChange and when view load set state of checkbox according to flag in preferance
keep a boolean flag in sharedPreferences or localDB for the user action. And by default keep this flag's value as true. When the user clicks checkbox, update this flag's value as well. So, whenever the application is launched, check this flag's value like:-
if(checkBoxEnabled) {
checkBox.setEnabled(true);
} else {
checkBox.setEnabled(false);
}
Where you have added check box in xml layout, add android:checked="true" for initial check.
Add status to SharedPreferences when you listen a change in value. e.g. onCheckedChanged()
SharedPreferences sp = getSharedPreferences(getPackageName(), MODE_PRIVATE);
sp.edit.putBoolean("check_status", checkBox.isChecked()).apply();

Android: setImgVisibility() error

In my app I have a header with icon hidden, I have a adapter with a listview when I click the listview I go to a login screen using listener, when the login is successful is should come back to listview(adapter) and icon should get visible on header.
In the login activity I have the following code:
public void onClick(View v) {
String password = etPassword.getText().toString();
if(password.equals("guest")){
SearchAdapter.setImgVisibility();
} else {
//-----
}
finish();
}
In my adapter I am calling the setImgVisibility() as follows, but it is not working
public static void setImgVisibility() {
img.setVisibility(View.VISIBLE);
}
I am getting a Nullpointerexception near the line img.setVisibility(View.VISIBLE);
I am stuck here and don't know what I am doing wrong. Any suggestions or help is appreciated
I would imagine that img is null. You need to look at where this value is set and make sure happens before you call the method setImgVisibility.
Show more of your complete code for people to help further.
Additionally, i've just noticed you've used a static reference to your search adapter, you should be really careful using statics, especially where any referencing of images is concerned as images can be bound to the context, as such unless you nullify the static you will end up with a memory leak. (this used to be an old problem, not sure its still valid, but i would still avoid using a static reference).
Without more code we're not likely to be able to properly help you. For example are you switching activities when logging in? If you are, this won't work at all.
[given the comment below] If you switch activities then your activity containing the list view is going to be destroyed and then rebuilt then you navigate back to it. or it will at least go through the activity lifecycle. This means you can set the icon during the instantiation of the header img.
You could store your logged in state as a property of the Application or a preference. Grab this value when you set the header image and set the image accordingly.
your img object is null. Is your img object is same as View v then you can pass v in setImgVisibility() and then set v.setVisibility(View.VISIBLE)

Cannot refresh ListView in Android Contacts

I have added a new setting to the Android 4.0.4 Contacts source, it's called useCompactView. What it does is reduce the size of the contact photos so you can fit twice as many contacts on the screen in list view.
<CheckBoxPreference
android:key="useCompactView"
android:defaultValue = "false"
android:title="#string/display_options_use_compact_view"
android:summary="#string/display_options_use_compact_view_summary" />
In ContactsPreferenceActivity I added a listener for my new checkbox and this does get fired off, I tested with a Log.d message. I tried to get the listview and call invalidateViews() on it but that doesn't work either. I am sure there has to be a way to get the adapter and force a refresh on it.
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if("useCompactView".equals(key)) {
getListView().invalidateViews(); // This does not work
}
}
});
What I am trying to accomplish is; when the user selects Use compact view in settings, the display will be refreshed automatically. Basically I need to redraw the screen. If I go into settings, check Use compact, then also change the sort order, I get the compact view when I hit the back button. So changing the sort order does refresh the display/listview. But I don't know how to do this from my preference activity.
If you need more code, please tell me and I will put whatever you need. This is a real head scratcher.

Android UI shows RadioButton as selected, although it is not

When my UI is recreated on orientation change, I use super.onCreate(savedInstanceState) and getLastNonConfigurationInstance() to access custom data I stored to fill the dynamic parts of my layout.
I have a RadioGroup which has two RadioButtons and is already defined in the XML file. The XML automatically makes the first one selected.
When an orientation change happens and the SECOND RadioButton is selected, everything seems to work fine; the second RadioButton is still selected in the UI.
But RadioGroup.getCheckedRadioButtonId() says the first RadioButton is selected. And I actually WANT the first one to be selected. But nothing changes when I call rb1.setChecked(true) - second one still shown as selected, and still the RadioGroup tells me the first one is selected (now it would make sense, but it's not shown).
This is REALLY strange behavior, does anyone have tips?
(edit)
Parts of my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.itemselected);
(...)
radioGroupServingType = (RadioGroup) findViewById(R.id.radioGroupServingType);
(...)
RadioButton radioOwnServing = (RadioButton) findViewById(R.id.radioOwnServing);
RadioButton radioUseServing = (RadioButton) findViewById(R.id.radioUseServing);
radioOwnServing.setOnClickListener(this);
radioUseServing.setOnClickListener(this);
//FIXME WTF
Log.d("", radioOwnServing.isChecked()+"/"+radioUseServing.isChecked()+" own/use checked");
radioOwnServing.setChecked(true);
Log.d("", radioOwnServing.isChecked()+"/"+radioUseServing.isChecked()+" own/use checked");
If I select radioUseServing in the UI and change the orientation, the log says true/false own/use checked both times - although radioUseServing is shown as selected in the UI.
By the way, logcat also outputs
W/asset(4040): deep redirect failure from 0x0103003e => 0x02060007, defStyleAttr=0x0101007e, defStyleRes=0x0103001a, style=0x00000000
when changing the orientation, sometimes multiple times. I haven't found anything with google on what that means.
I already spoke with you on IRC, but I believe that if you get the view, and post a runnable to it that will call .setChecked(), this will in effect cause the setChecked call to occur at the proper time, and thus avoiding having called setChecked before the view hierarchy was ready for it.
Something like this:
final View myRadioButton = findViewById(R.id.myradiobutton);
myRadioButton.post(
new Runnable() {
#Override
public void run() { myRadioButton.setChecked(true); }
}
);

Can I have an android activity run only on the first time an application is opened?

OK, so I'm playing around with an android app.
The 90% use case is that users want to go straight to the primary list screen to find what they're looking for. That's what I want as my default screen.
The first time a user loads the app however, some configuration is required before their list screen is of any value to them.
So my question, is how I can go about displaying the configuration activity the first time the app is opened up, and then the list screen for future openings.
I also want to put a demo button on the configuration screen, so I suppose more than just detecting that it's the first time, I specifically want to detect whether the user has performed certain configurations within the first screen.
After the first time the user has loaded the app you could store the details of whether user has performed the configurations in SharedPreferences.
protected void storeSharedPrefs(String value) {
/*
* Storing in Shared Preferences
*/
editor.putString("first", value);
editor.commit(); //Commiting changes
}
Check each on time application is loaded, whether its the first time and configuration details has been entered correctly by checking SharedPreferences
private boolean first_time_check() {
/*
* Checking Shared Preferences if the user had pressed
* the remember me button last time he logged in
* */
String first = uPreferences.getString("first", null);
if((first == null)){
return false;
}
else
return true;
}
i like dweebsonduty's method. a similar way to do this is to save their configuration information in files on the SD card. your app could start out by checking for those files and loading the information. if the load is successful, it moves on to the next activity, if not it starts the appropriate activity to prompt the user for input.
I have done this same thing, but instead of swiching activities i just switch views until i have all the info i need, and then move on.
Many applications actually store the current version in SharedPreferences, and check against it for if an update has been installed. Its a clever way of achieving a "what's changed" popup, or making sure that some settings get set (I would be wary of just having a boolean flag because if you ever want to add an additional setting, you will need a second flag and it gets messy after the third, etc.).
String VersionValue = "v.1.0";
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean(VersionValue, true)) {
//the app is being launched for first time, do something
NewDialogFragment newFragment = new NewDialogFragment();
newFragment.show(getFragmentManager(), "New");
// record the fact that the app has been started at least once
settings.edit().putBoolean(VersionValue, false).commit();
}
You could do it this way and still get the same result I tried it its a small workaround if u do not fully understand how to check if the app is updated. Instead with this code you can just simply change the String VersoinValue to your current app version and android will think the app is a new first time app and will only display the code u wrote once until you change VersionValue on your next update. (:
How will you be storing the configuration?
If it is in SQLlite you could just create a table called firstuse and put a field in there called hasbeenused and make it null. Then when the app is used you can put a 1 in there. Then you can read it each time your app loads and if that field = 1 then go to your next activity.

Categories

Resources