how to verify if checkbox is checked in android studio? - android

i would like to implement some code under the condition checkbox is checked or not, here is my code:
CheckBox checkBox=findViewById(R.id.checkBox);
if(checkBox.isChecked()){
Log.v("checked","true");
spin.setVisibility(View.VISIBLE);
montant2.setVisibility(View.VISIBLE);
txtVw.setVisibility(View.VISIBLE);
try {
auth3();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
normally i should be able to view the log inside the if condition but nothing appears.

Is the Check Box checked by default? when does the code run?
you're only printing a log when the checkBox is checked, but you won't get any log if the statement is false.
Try to add this line before your if statement:
checkBox.setChecked(true);
If you're getting the log after adding this line, it means that your checkbox is not checked when running the code.
EDIT:
You're running the code in the OnCreate method where the checkBox.getChecked() is set to false by default. To make it work, you need to create a listener that will run the code every time that the checkBox is checked.
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
// Everytime you check the checkBox, the following code will execute:
// Your code here //
}
}
});

Instead of Log, you can use one boolean variable to identify like:
Boolean checkbox = false;
CheckBox checkBox=findViewById(R.id.checkBox);
if(checkBox.isChecked()){
checkbox = true;
}else{
checkbox = false;
}

use this code
public void itemClicked(View yourView) {
CheckBox checkBox = (CheckBox)yourView;
if(checkBox.isChecked()){
}
}

Related

Reverting an android preference's value when a statement in another thread fails

I have settings in my app that I allow the user to manipulate using a PreferenceScreen with Preferences. However, I want to store the settings on a server so that the settings can persist over multiple devices. I have the following code that lets me do this:
private void updateSettingOnPrefChange(final Preference pref, final Setting setting) {
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, final Object newValue) {
try {
setting.update(newValue, new Callback<Boolean>() {
#Override
public void call(Boolean succeeded) {
if (!succeeded) {
Toast.makeText(getActivity(), "Setting failed to update. Please try again.", Toast.LENGTH_LONG).show();
//here I need to revert the value of the Preference without again calling the onChangeListener
}
}
}, getActivity());
} catch (Exception ex) {
if (BuildConfig.DEBUG)
ex.printStackTrace();
Toast.makeText(getActivity(), "Setting failed to update. Please try again.", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
});
}
As you can see in the code the request is being run on a different thread using a custom Callback class to clean up based on the result of the call. The issue is the code will have already return true on the main thread.
How can I revert the value of the Preference in the callback function (preferably without also calling the onPrefChangeListener function so I don't get infinite recursion)?
Use the OnPreferenceClickListener instead of OnPreferenceChangeListener to listen for user taps on the setting field and then make your rpc request accordingly. If you have to update the value (in the case of a server failure) you can change the setting without firing the click listener and having the infinite loop.
https://developer.android.com/reference/android/preference/Preference.html#setOnPreferenceClickListener(android.preference.Preference.OnPreferenceClickListener)

Saving switch button state isn't working

I have a switch button for setting the sound of the app On and OFF, although it works normally but when I close the app then open it again.. the switch becomes false automatically..!?
I've tried to save the last state via Shared Preference library Hawk , but it not clear to me how to do it right.!?
That's when I've tried to use Hawk
// ....
bool soundON = Hawk.get("sound"); // NPE !!!
if (soundON) {
soundSwitch.setChecked(true);
soundSwitch.setSelected(true);
} else {
soundSwitch.setChecked(false);
soundSwitch.setSelected(false);
}
soundSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
isSoundEnabled = true;
Hawk.put("sound", true);
} else {
isSoundEnabled = false;
}
Log.i("is checked sound", isChecked + "");
}});
UPDATE - Solution
I used #Shrikant answer, but with just a small change.! I used Boolean instead boolean so I can check for null values which Boolean allows you to do since it can be true or false or null unlike boolean which can be either true or false.
Here's the code
Boolean isSound = Hawk.get("sound");
if (isSound == null) {
// I want the sound to be ON by default so I set it to true
soundSwitch.setChecked(true);
soundSwitch.setSelected(true);
} else {
soundSwitch.setChecked(isSound);
soundSwitch.setSelected(isSound);
Log.i("Sound State > ", isSound + "");
}
Try this
In onCreate() init that Hawk
Hawk.init(context).build();
after this get your sound value from Hawk and set it to switch
boolean isSound = Hawk.get("some",false);
soundSwitch.setChecked(isSound);
soundSwitch.setSelected(isSound);
there is not to check boolean by if else
soundSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("is checked sound", isChecked + "");
Hawk.put("sound", isChecked);
}
});
I have used 2.0.1 version of Hawk.
In onCreate() method you have to check isSoundEnabled from shared preference whether you checked it from your local variable.
try this:
bool soundValue = Hawk.get("sound");
if (soundValue) {
soundSwitch.setChecked(true);
soundSwitch.setSelected(true);
} else {
soundSwitch.setChecked(false);
soundSwitch.setSelected(false);
}
instead of :
if (isSoundEnabled) {
soundSwitch.setChecked(true);
soundSwitch.setSelected(true);
} else {
soundSwitch.setChecked(false);
soundSwitch.setSelected(false);
}
in onCreate()
You should save the check state at the time of the setOnCheckedChangeListener call. And get the check state at the time of the onCreate call.

add or remove a string from a list based on an if statement

I have the below code:
if(cb.isChecked())
{
selectedPlanets.add(planet.getDisplayName());
}
if (!cb.isChecked())
{
selectedPlanets.remove(planet.getDisplayName());
}
testing();
}
private void testing() {
serverString.setText(null);
Iterator<String>i = selectedPlanets.iterator();
while(i.hasNext()){
String aNum1 = i.next();
serverString.append(aNum1+",");
}
I then need to iterate through selectedPlanets but the removed ones show up too. By setting the TextView null again, it works if three or more are selected. However, if two are selected, the checked planet also gets removed from the list.
EDIT: for anyone who runs into this problem, I solved it by using the else (programmer's block made me lose sense!) and then implementing some other methods that I needed to make it work.
Why don't you just do it like this?
if (cb.isChecked()) {
selectedPlanets.add(planet.getDisplayName());
} else {
selectedPlanets.remove(planet.getDisplayName());
}
Why not do this:
for(int i=0; i<selectedPlanet.size(); i++) {
if(planet.isChecked()) {
selectedPlanets.add(planet.getDisplayName());
} else {
selectedPlanets.remove(planet.getDisplayName());
}
}
What you are trying to do is
if isChecked true then add something
if(cb.isChecked())
{
selectedPlanets.add(planet.getDisplayName());
}
if isChecked is not true then remove something
if (!cb.isChecked())
{
selectedPlanets.remove(planet.getDisplayName());
}
Instead of using not true condition you must use else case like
if(cb.isChecked()) {
selectedPlanets.add(planet.getDisplayName());
} else {
selectedPlanets.remove(planet.getDisplayName());
}

Check box refresh not working when Activity not reloaded - Android

I have created an activity that refresh quotes when the user clicks a button. Within the same activity there is a check box which the users can click if they like the quote.
Everything works perfectly apart from the check box. When the user clicks they like the quote, I want that check box checked. This only happens when the user moves away from the activity and returns at a later stage.
However when the user stays within the activity and returns to the quote, the old state is shown instead of the users preference.
The check box is configured from the values even in the database, if the value is 1, the check box should be ticked, if not, check box should be clear.
The code is shown below:
When the user clicks the next button, the following code is executed:
Button nextGenerateButton = (Button) findViewById(R.id.btn_next_quotes);
nextGenerateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String nextQuote = myDbHelper.getnextQuote();
setQuoteDisplay(nextQuote);
btn_favorite.setChecked(myDbHelper.getFavouriteCheckBoxValue());
}
});
The button retrieves the next quote and the getFavouriteCheckBoxValue() confirms whether the favourite column is marked in the database and either returns a true of false which sets the check box value.
public boolean getFavouriteCheckBoxValue()
{
int laballedFavourite = cursor.getInt(0);
if(laballedFavourite == 0)
{
return false;
}
else
{
return true;
}
}
if the user likes the quote, the code executes the addFavourite() which updates the table where the favourite column will be modified on one.
btn_favorite.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked == true)
{
myDbHelper.addFavourite();
}
if(isChecked == false)
{
myDbHelper.removeFavourite();
}
}
});
public void addFavourite()
{
ContentValues vals = new ContentValues();
vals.put("favouriteQuote", 1);
db.update(TABLE_NAME, vals, "columnId = " + cursor.getInt(1), null);
}
Again this only works perfectly when I resume the quote activity and not when I am currently live in the quote activity.
Hope this makes sense.
Any help would be greatly appreciated.
You need to refresh your checkbox to see the changement because you made a changement in you db but not on the UI. You need to observe the db and refresh the checkbox after a modification.
Refreshing cursor solved the problem.

Android CheckBox isChecked() or editing SharedPreferences causing forced close

I'm writing a flash card app in Android, and I tried to add the ability to add a word to a review list by having a checkbox. When the user goes to the next word, I see whether the checkbox is checked. If it is, I add the word to the review list, and if it isn't, I remove the word. When I tested it on my phone and the emulator, I got a forced close every time I try to go to the next word or to the home page when the checkbox is checked. I don't know what's causing the error because in the LogCat page, it doesn't show the line number or what error happened.
I can flip through the words without a problem when I don't have them checked; checking it and going to another word is what causes a problem, so I'm guessing it has to do with the SharedPreferences.
Here are the important methods I have:
public void onCreate(Bundle savedInstanceState)
{
//other code
reviewCheckBox = (CheckBox) findViewById(R.id.reviewCheckBox);
prefs = getPreferences(MODE_PRIVATE);
editor = prefs.edit();
reviewCards = prefs.getAll().keySet();
}
public void home(View v)
{
if (flashCardPage.getVisibility() == View.VISIBLE)
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
updateReviewCards();
}
//other code
}
public void nextWord(View v)
{
currentPosition++;
if (currentPosition == flashCards.size())
{
home(wordTV);
}
else
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
//other code
if (reviewCards.contains(currentCard.getTerm()))
reviewCheckBox.setChecked(true);
else
reviewCheckBox.setChecked(false);
}
}
public void previousWord(View v)
{
if (currentPosition > 0)
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
//other code
if (reviewCards.contains(currentCard.getTerm()))
reviewCheckBox.setChecked(true);
else
reviewCheckBox.setChecked(false);
}
}
public void updateReviewCards()
{
editor.clear();
for (String card : reviewCards)
editor.putString(card, card);
editor.commit();
}
The set returned by getPreferences().getAll().keySet() does not support adding.

Categories

Resources