I'm kinda new to Android developing and I hope you can help me. I have one RecyclerView, with each cardview showing one image, two text views and one switch button. This app is for myself and I wanted to organize my card collection so the switch is there for letting me know if I have a card or not, so I wanted to update database with a 1, if it's checked, or with a 0 if it's not. I was trying to test the buttons with some Toast but I get an error. Here the code:
aSwitch = (Switch) findViewById(R.id.switch1);
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
Toast.makeText(StockActivity.this, "On", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(StockActivity.this, "Off", Toast.LENGTH_SHORT).show();
}
}
});
This is my code for the switch button, I thought this was fine but I got an error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.battlespiritsdb/com.example.battlespiritsdb.StockActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Switch.setOnCheckedChangeListener(android.widget.CompoundButton$OnCheckedChangeListener)' on a null object reference
The error points at first line of setOnCheckedChangeListener, and I don't know why, is it because I'm using them on RecyclerView or something?
#Kinda --Try This code
sw1 = (Switch)findViewById(R.id.switch1);
sw2 = (Switch)findViewById(R.id.switch2);
btnGet = (Button)findViewById(R.id.getBtn);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str1, str2;
if (sw1.isChecked())
str1 = sw1.getTextOn().toString();
else
str1 = sw1.getTextOff().toString();
if (sw2.isChecked())
str2 = sw2.getTextOn().toString();
else
str2 = sw2.getTextOff().toString();
Toast.makeText(getApplicationContext(), "Switch1 - " + str1 + " \n" + "Switch2 - " + str2,Toast.LENGTH_SHORT).show();
}
});
}`enter code here`
}
You can try this snippet of code.
switchButton = (Switch) findViewById(R.id.switch1);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked) {
// if 'isChecked' is true do whatever you need...
// To show a toast use only 'this' (for activity) or 'getActivity()'
// (for fragment) nothing else.
Toast.makeText(this, "On", Toast.LENGTH_SHORT).show(); // or getActvity()
} else {
Toast.makeText(this, "Off", Toast.LENGTH_SHORT).show(); // or getActvity()
}
}
}
});
Hope it will help.
Related
I added a switch button to my app and created a setOnCheckChangeListener the will pop up toast message..
But it works only after the second click.
Any ideas?
MainActivity:
public void checkSwitch (View view)
{
addBeeps.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
beeps = true;
Toast.makeText(MainActivity.this,"beeps is True",Toast.LENGTH_LONG).show();
}else
{
beeps = false;
Toast.makeText(MainActivity.this,"beeps is False",Toast.LENGTH_LONG).show();
}
}
});
}
I think in xml file which contains addBeeps switch you are using this code.
<Switch
android:id="#+id/addBeeps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="checkSwitch"/>
Root cause: For the first time when you check the switch, a listener will be set on it and do nothing, the second time when you check the switch again the listener is triggered and the Toast showed.
Solution: Here is a solution for you.
Remove onClick from the switch in xml file
<Switch
android:id="#+id/addBeeps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Delete or comment-out checkSwitch method from MainActivity and move set listener block code to onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addBeeps = findViewById(R.id.addBeeps);
// TODO: Put set listener block code here
addBeeps.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
beeps = true;
Toast.makeText(MainActivity.this, "beeps is True", Toast.LENGTH_LONG).show();
} else {
beeps = false;
Toast.makeText(MainActivity.this, "beeps is False", Toast.LENGTH_LONG).show();
}
}
});
}
// TODO: Delete or comment-out this method
// public void checkSwitch(View view) {
// addBeeps.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// #Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// if (isChecked) {
// beeps = true;
// Toast.makeText(MainActivity.this, "beeps is True", Toast.LENGTH_LONG).show();
// } else {
// beeps = false;
// Toast.makeText(MainActivity.this, "beeps is False", Toast.LENGTH_LONG).show();
// }
// }
// });
// }
Been trying to use a ToggleButton to act as a bookmark kind of thing in my application. I am using this for the first time. I have declared my toggle button under onCreateView() as below:
bmark = (ToggleButton) v.findViewById(R.id.bmark);
bmark.setChecked(false);
I am trying to just toggle the state and show a Toast message! I tried the below:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
bmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean status;
if (bmark.isChecked()) status = true;
else status = false;
Log.w("Bmark status",String.valueOf(status));
if (status) {
bmark.setChecked(false);
Log.w("Bmark after true",String.valueOf(bmark.isChecked()));
Toast.makeText(getActivity(), "Bookmark removed!", Toast.LENGTH_SHORT).show();
} else {
bmark.setChecked(true);
Log.w("Bmark after false",String.valueOf(bmark.isChecked()));
Toast.makeText(getActivity(), "Post Bookmarked..!", Toast.LENGTH_SHORT).show();
}
}
});
Every time I press the button, the status is initially read "true", although I've set it to "false". After I call setChecked(false), it also becomes false. But when I click it again, it again reads "true" and instead of "false"
I dont know why its happening like this. I just want to toggle it every time I click it. Pls help me out! Thanks in advance :)
Change code to:
if (bmark.isChecked()){
status = true;
Toast.makeText(getActivity(), "Post Bookmarked..!",Toast.LENGTH_SHORT).show();
}
else {
status = false;
Toast.makeText(getActivity(), "Bookmark removed!", Toast.LENGTH_SHORT).show();
}
Toggle changes self checked status, You done that again so status was changed two times.
The problem is you're inverting the state of your button by the setChecked() calls in onClick().
Use an OnCheckedChangeListener instead of an OnClickListener, so you don't have to bother with keeping track of the status:
bmark.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// checked
Toast.makeText(getActivity(), "Post Bookmarked!", Toast.LENGTH_SHORT).show();
} else {
// not checked
Toast.makeText(getActivity(), "Bookmark removed!", Toast.LENGTH_SHORT).show();
}
}
});
You seem to be switching the button back to what it was previously in your statements. If you stop changing the button's state in the onClickListener, it should work just fine.
private boolean bmarkStatus = false;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
bmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bmarkStatus = bmark.isChecked();
if (bmark.isChecked()) Toast.makeText(getActivity(), "Bookmark removed!", Toast.LENGTH_SHORT).show();
else Toast.makeText(getActivity(), "Bookmark added!", Toast.LENGTH_SHORT).show();
}
});
}
I got multiple buttons which are managed by this code:
ToggleButton.OnCheckedChangeListener listener = new ToggleButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton v, boolean isChecked) {
int index;
for(index = 0; index < viewIds.length; index++) {
if (v.getId() == viewIds[index]) {
getSharedPreferences("PREFS_NAME", MODE_PRIVATE)
.edit()
.putBoolean(stringIds[index], isChecked)
.apply();
break;
}
}
}
};
i've created method
scanButton();
like this:
private void scanButton() {
Button scan = (Button)findViewById(R.id.button_scan);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here what will be done when button is clicked
Log.d(TAG, "Button \"SCAN\" is pressed");
Toast.makeText(RandDActivity.this, "Scan pressed", Toast.LENGTH_LONG)
.show();
//WHAT HERE
}
});
}
now Question: what to put here to get only those buttons which are isChecked with "true" state to do something?
Firstly you need to see whether the user has checked the button or not for that you can Load your SharedPreferences that you already saved in your onCheckedChanged() method, save it to a Boolean variable and then put a condition Like this:
if(isChecked){
//do your stuff with the button
}
I am assuming isChecked is your boolean variable that you just set with the value that you got from SharedPreferences.
I am making an app that toggles off and on a switch. I have 4 switches in total and at the bottom I would like to have a button that will toggle them all off at the same time - like an override switch. I'm trying to follow the same format as when creating the 4 switches, but I can't wrap my head around how it would be. I already tried looking through stackOverFlow and I can't find anything on it, maybe I just don't know the key words.
Switch toggleapp1 = (Switch) findViewById(R.id.app1);
toggleapp1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
toggleapp1(true);
Toast.makeText(getApplicationContext(), "[Application1] Enabled!", Toast.LENGTH_LONG).show();
} else {
toggleapp1(false);
Toast.makeText(getApplicationContext(), "[Application1] Disabled!", Toast.LENGTH_LONG).show();
}
}
});
Is how one of the switches look. toggleapp1 is switched with 2,3,4.
public boolean toggleapp1(boolean status) {
if (status == true) {
return true;
}
else if (status == false) {
return false;
}
return status;
}
I have 4 switches in total and at the bottom I would like to have a button that will toggle them all off at the same time - like an override switch.
If i understood the problem you have something like:
toggleapp1 = (Switch) findViewById(R.id.app1);
toggleapp2 = (Switch) findViewById(R.id.app2);
toggleapp3 = (Switch) findViewById(R.id.app3);
toggleapp4 = (Switch) findViewById(R.id.app4);
And you want to disable all of them togheter.
You can create a method that do this:
private toggleOffSwitches(boolean state) {
toggleapp1.setChecked(state);
toggleapp2.setChecked(state);
toggleapp3.setChecked(state);
toggleapp4.setChecked(state);
}
And call it in the OnClickListener of the button:
Button yourButton = (Button) findViewById(R.id.yourButton);
yourButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
toggleOffSwitches(false);
}
});
Remember to declare your Switches as field class variables in order to use them in the toggleOffSwitches method!
UPDATE
For example:
public class MainActivity extends Activity {
private Switch toggleapp1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
....
toggleapp1 = (Switch) findViewById(R.id.app1);
....
}
I want to inspect something before CheckBox's state changed. If user has logged in, change the state and post data to server. Otherwise, keep the state and show a log-in activity.
OnCheckedChangeListener does not fit. Is there anything like PreferenceChangeListener (return false to keep stateļ¼ in CheckBox.
Or other methods.
Thank you!
Update:
OnClickListener work for me.
#Override
public void onClick(View view) {
boolean isChecked = checkBox.isChecked();
checkBox.setChecked(!isChecked);
if (loggedIn) {
checkBox.setChecked(isChecked);
// push data to server
} else {
// show log-in activity
}
}
If I'm not misunderstood your question, you can still achieve it by using OnCheckedChangeListener:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isLogin) {
buttonView.setChecked(true);
Toast.makeText(this, "Sending data", Toast.LENGTH_SHORT).show();
} else {
buttonView.setChecked(false);
Toast.makeText(this, "Show login activity", Toast.LENGTH_SHORT)
.show();
}
}
You can do something like this:
CheckBox repeatChkBx = ( CheckBox ) findViewById( R.id.repeat_checkbox );
repeatChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
or if you just want to see if the checkbox has been checked or not, then you can use this
CheckBox checkBox = (CheckBox)v.findViewById(R.id.Checkbox);
checkBox.setChecked(!checkBox.isChecked());
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// awesome code you may use
// if (isChecked)
// (buttonView.getId() == R.id.check1 ? check2 : check1)
// .setChecked(false);
//Or use the code below
if (isChecked) {
switch (buttonView.getId()) {
case R.id.check1:
check2.setChecked(false);
Toast.makeText(getApplicationContext(), "Check1 is selected!!! =)",
Toast.LENGTH_LONG).show();
break;
case R.id.check2:
check1.setChecked(false);
Toast.makeText(getApplicationContext(), "Check2 is selected!!! =)",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}