I am working with an Arduino and trying use two toggle buttons to connect and enable the Arduino. I don't want to be able to press the enable button until I have connected the robot. Here is my main activity:
public class MainActivity extends Activity {
Arduino arduino = null;
ToggleButton enable, connect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton connect = (ToggleButton) findViewById(R.id.buttonConnect);
ToggleButton enable = (ToggleButton) findViewById(R.id.buttonEnable);
}
public void onToggleClicked(View view) {
switch(view.getId()) {
case R.id.buttonConnect:
boolean on = ((ToggleButton) view).isChecked();
if(on){
//Take the text from editText1 and make it the IP Address
EditText text = (EditText)findViewById(R.id.editText1);
String ip = text.getText().toString();
arduino = new Arduino(ip);
arduino.connect();
arduino.disable();
} else {
arduino.disable();
arduino.disconnect();
enable.setChecked(false);
}
break;
case R.id.buttonEnable:
boolean click = ((ToggleButton) view).isChecked();
if(click && connect.isChecked()) {
arduino.enable();
}else {
System.out.println("Not Connected");
enable.setChecked(False);
arduino.disable();
}
break;
default:
break;
}
}
I know the program is not reaching the else statement in the buttonEnable case because it is not printing out "Not Connected." I have also tried to use connect.isEnabled()in my if statement but that doesn't work either. Does anybody have answer? Thank you!
Try to set on click listener to attach the code execution to you button
Related
I made simple dark/light mode switcher. The application OnCreate detects the mode you are on and than changes the boolean. I'm toggling this boolean and theme with button but for some reason it changes to false after second click. It only does that when the boolean is true. On false it works fine. Here's my code:
ImageButton dark_light;
boolean isDarkMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dark_light = findViewById(R.id.dark_light);
int nightModeFlags =
getApplicationContext().getResources().getConfiguration().uiMode &
Configuration.UI_MODE_NIGHT_MASK;
switch (nightModeFlags) {
case Configuration.UI_MODE_NIGHT_YES:
dark_light.setImageResource(R.drawable.light);
isDarkMode = true;
break;
case Configuration.UI_MODE_NIGHT_NO:
dark_light.setImageResource(R.drawable.dark);
isDarkMode = false;
break;
}
dark_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isDarkMode) {
dark_light.setImageResource(R.drawable.light);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
isDarkMode = true;
} else {
dark_light.setImageResource(R.drawable.dark);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
isDarkMode = false;
}
Log.d("Dark_Light", String.valueOf(isDarkMode));
}
});
}
Whenever night mode is toggled, onCreate will be called again.
getApplicationContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK; always gives you the initial configuration so you are always writing the same value to isDarkMode whenever the night mode is toggled.
To get the current night mode configuration, use AppCompatDelegate.getDefaultNightMode() instead
int nightModeFlags = AppCompatDelegate.getDefaultNightMode();
switch (nightModeFlags) {
case AppCompatDelegate.MODE_NIGHT_YES:
dark_light.setImageResource(R.drawable.light);
isDarkMode = true;
break;
case AppCompatDelegate.MODE_NIGHT_NO:
dark_light.setImageResource(R.drawable.dark);
isDarkMode = false;
break;
}
how to clear the checked box after we get the checked result ?
something like selection.clear(); but, that only clear the output, not the checkbox.
what i am trying to do is, to set the checkbox to the original state, which is unchecked.
after user checked the checkbox then click button to get result of checked checkbox, i wish to clear all the selection in the checkbox. how please help?
public class DessertIngAvail extends Dessert {
ArrayList<String> selection = new ArrayList<String>();
TextView final_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dessert_ing_avail);
final_text = (TextView)findViewById(R.id.final_result);
final_text.setEnabled(false);
}
public void selectItem(View view){
boolean checked = ((CheckBox) view).isChecked();
switch (view.getId()) {
case R.id.checkBox181:
if(checked) {
if(!selection.contains("Tebaloi"))
selection.add("Tebaloi");
if(!selection.contains("Tumpik"))
selection.add("Tumpik");
}
break;
case R.id.checkBox182:
if(checked) {
if(!selection.contains("Ambuyat"))
selection.add("Ambuyat");
}
break;
case R.id.checkBox183:
if(checked) {
if(!selection.contains("Tumpik"))
selection.add("Tumpik");
}
break;
case R.id.checkBoxCM:
if(checked) {
if(!selection.contains("Honey Frankincense Cake"))
selection.add("Honey Frankincense Cake");
if(!selection.contains(" Ray Heart Cake"))
selection.add(" Ray Heart Cake");
}
break;
}
}
public void finalSelection(View view) {
String final_fruit_selection = "";
for(String Selection : selection) {
final_fruit_selection = final_fruit_selection + Selection + "\n";
}
final_text.setText(final_fruit_selection);
selection.clear();
final_text.setEnabled(true);
}
}
You can use
checkBox.setChecked(boolean);
//to clear the check box
checkBox.setChecked(false);
Updated finalSelection(View view) method;
public void finalSelection(View view){
String final_fruit_selection = "";
for(String Selection : selection){
final_fruit_selection = final_fruit_selection + Selection + "\n";
}
final_text.setText(final_fruit_selection);
selection.clear();
final_text.setEnabled(true);
//now clear checkboxes
checkBox181.setChecked(false);
checkBox182.setChecked(false);
checkBox183.setChecked(false);
checkBoxCM.setChecked(false);
}
Changing really really really basic things
//right below TextView final_text; at the top add this
CheckBox checkBox181,checkBox182,checkBox183,checkBoxCM;
//declare then in onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dessert_ing_avail);
final_text = (TextView)findViewById(R.id.final_result);
final_text.setEnabled(false);
checkBox181=(CheckBox)findViewById(R.id.checkBox181);
checkBox182=(CheckBox)findViewById(R.id.checkBox182);
checkBox183=(CheckBox)findViewById(R.id.checkBox183);
checkBoxCM=(CheckBox)findViewById(R.id.checkBoxCM);
}
I suggest you to follow up some java course online. This is a good place to start.
To start learning android development check here.
To check:
checkBox.setChecked(true);
and to uncheck:
checkBox.setChecked(false);
Use setChecked():
checkBox.setChecked(true/false)
Docs: https://developer.android.com/reference/android/widget/CheckBox.html
I'm not sure I understand your question but you can set a checkbox by using checkBox.setChecked(false). To uncheck all checked checkboxes, simply loop over them and uncheck the checked ones.
If you'r sure checkbox are checked, You can toggle them.
checkbox.toggle();
Otherwise
checkBox.setChecked(false); // pass true if you want to select.
Hi I'm a college student and I'm struggling with an app I have to make. The app is a subtraction app and I can't seem to get it to work. Every time I press the subtraction button it crashes.
My code:
public void onClick(View view){
switch (view.getId()) {
case R.id.subtract_button:
setContentView(R.layout.activity_main);
EditText firstNumber = (EditText) findViewById(R.id.input_box_1);
int num1 = Integer.parseInt(firstNumber.getText().toString());
EditText secondNumber = (EditText) findViewById(R.id.input_box_2);
int num2 = Integer.parseInt(secondNumber.getText().toString());
int result = num1 - num2;
setContentView(R.layout.activity_result);
TextView subResult = (TextView)findViewById(R.id.result_view);
subResult.setText(Integer.toString(result));
break;
case R.id.exit_button: // the 'exit' button has been pressed.
// Delay the exit by 1 second at this time!
new Handler().postDelayed(new Runnable() {
public void run() {
//Finish the app
finish();
}
}, 1000);
break; // End of case.
}
}
At First Post your Logcat
Problem for your wrong setContentView placing .
Why multiple setContentView ?? Must be One .
Don't
switch (view.getId()) {
case R.id.subtract_button:
setContentView(R.layout.activity_main); // Problem here i guess
Do
setContentView call in your onCreate(Bundle savedInstanceState) section.
An activity is a single, focused thing that the user can do. Almost
all activities interact with the user, so the Activity class takes
care of creating a window for you in which you can place your UI with
setContentView(View).
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_name);
I thought you missed button declaration check it
Button button;
button=(Button) findViewById(R.id.buttonid);
or else post ur log
I have an Activity in which I want to ask for a PIN code. In this Activity the user can go to a separate Activity in which he can set the PIN. If no PIN is set, then a default PIN should be used.
This is the code of the first Activity:
public class activity_identification extends AppCompatActivity {
SharedPreferences pins_pref = null;
EditText pin_entry = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_identification);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
pin_eingabe = (EditText) findViewById(R.id.et_pin_entry);
pins_pref = getApplicationContext().getSharedPreferences("UserPin", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = pins_pref.edit();
edit.putString("default_pin", "0000");
edit.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_pin_identifikation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_change_pin) {
startActivity(new Intent(this, pin_settings.class));
return true;
}
else if (id == R.id.home) {
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClickPinSummit(View button){
if(pin_entry.getText().toString().equals( pins_pref.getString("user_pin", null).toString())) {
Toast.makeText(this, "Authorization Right", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Authorization Wrong", Toast.LENGTH_SHORT).show();
}
}
}
And this is the second Activity:
public class pin_settings extends AppCompatActivity {
EditText et_old_pin = null;
EditText et_new_pin = null;
EditText et_new_pin_repeat = null;
Button btn_pin_save = null;
TextView tv_sharedPIN = (TextView) null;
SharedPreferences pins_prefs = null;
private String default_pin = null;
private String user_pin = null;
private String old_pin = null;
private String new_pin = null;
private String new_pin_repeat = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pin_einstellungen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
et_old_pin = (EditText) findViewById(R.id.et_old_pin);
et_new_pin = (EditText) findViewById(R.id.et_new_pin);
et_new_pin_repeat = (EditText) findViewById(R.id.et_new_pin_repeat);
btn_pin_save = (Button) findViewById(R.id.btn_pin_save);
tv_sharedPIN = (TextView) findViewById(R.id.sharedPIN);
pins_prefs = getApplicationContext().getSharedPreferences("UserPin", Context.MODE_PRIVATE);
general_pin = pins_prefs.getString("default_pin", null);
tv_sharedPIN.setText(pins_prefs.getString("general_pin", null));
}
public void onClickNewPinSave(View button){
old_pin = et_old_pin.getText().toString();
new_pin = et_new_pin.getText().toString();
new_pin_repeat = et_new_pin_repeat.getText().toString();
if(old_pin.equals(pins_prefs.getString("default_pin",null).toString())){
if (new_pin.equals(new_pin_repeat)){
SharedPreferences.Editor edit = pins_prefs.edit();
edit.putString("user_pin", user_pin);
edit.commit();
tv_sharedPIN.setText(pins_prefs.getString("user_pin", null));
} else {
Toast.makeText(this, "New Pins are not the same", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Old Pin is wrong.", Toast.LENGTH_LONG).show();
}
}
}
Now the problem is that the app does not save the PIN which is set in the second Activity. It works as long as the app is open, but as soon as I restart it the PIN reverts back to the default PIN. I think this is because I set the default PIN in the onCreate() method of the first Activity, but I just can't figure out how to get around doing that.
Of course the PIN will always be reset to the default since you set it each time on startup. All you need to do to fix that is remove that line and instead use the default value which is passed into getString() correctly.
You don't need to set the default PIN at all! Remove all of that from onCreate()
getString() accepts a default value as second parameter. This default value is returned if no value is set. Let me repeat that: The default value is return if no value has been set.
So instead of setting the default PIN in onCreate() you can simply pass in the default PIN into getString() and if no PIN has been set, getString() will then return the default PIN. So what you are looking for is this:
String pin = preferences.getString("default_pin", "0000");
On a side note: Please adhere to the common Java naming conventions. Also don't hardcode so many Strings. Use constants instead.
EDIT: As Xaver Kapeller pointed out my earlier solution wont work. Although his one is simpler, i'll fix mine just because
Set default_pin to 0000 if getString(default_pin, "-1") returns "-1".
OLD: Try only setting the default_pin to 0000 if default_pin is null, which will only happen at the very first launch of your activity
If anybody can tell me different way to do this, I would appreciate. How to reset class variable to 0, or default value? I use class variable cause I don't know another way to do this. After my game ends I place result in class variable, cause I have two rounds of my game, and after first round ends I add the result, and class variable is good for this cause even after I restart my game method it still holds my previous result. After second round is over I add that result to previous result and then close the activity and set text result as text to a button. But when I click New game, that button still holds that text, cause class variable still holds it. How to reset that class variable when I go on New game?
Here's my game code, some of it (100 points are start amount, and it gets lower in game progress):
public class Asocijacije extends Activity implements OnClickListener{
int brojPoenaAsocijacije = 100;
public static int brojPoenaUkupno;
Then I skip here a lot of code and here's where I add points. brojPoenaAsocijacije are points earned in that round:
brojPoenaUkupno = brojPoenaUkupno + brojPoenaAsocijacije;
Here's my main activity where I set points from my class variable to a button (where I added comment):
public class Izbor extends Activity implements OnClickListener{
Asocijacije poeni = new Asocijacije();
Button toploHladno, asocijacije, cigle, spojnice, nazad, poeniTH, poeniAso, poeniCigle, poeniSpojnice;
TextView naslov;
public boolean music;
MediaPlayer buttonClicks, buttonBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.izbor);
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
music = getPrefs.getBoolean("checkbox", true);
addListenerOnButton();
}
private void addListenerOnButton() {
buttonClicks = MediaPlayer.create(this, R.raw.click);
buttonBack = MediaPlayer.create(this, R.raw.button31);
Typeface naslovType = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
naslov = (TextView) findViewById(R.id.tvIzborNaslov);
toploHladno = (Button) findViewById(R.id.bIzbor1);
asocijacije = (Button) findViewById(R.id.bIzbor2);
cigle = (Button) findViewById(R.id.bIzbor3);
spojnice = (Button) findViewById(R.id.bIzbor4);
nazad = (Button) findViewById(R.id.bIzborNazad);
poeniTH = (Button) findViewById(R.id.bPoeniTH);
poeniAso = (Button) findViewById(R.id.bPoeniAso);
poeniCigle = (Button) findViewById(R.id.bPoeniCigle);
poeniSpojnice = (Button) findViewById(R.id.bPoeniSpojnice);
naslov.setTypeface(naslovType);
toploHladno.setTypeface(dugmad);
asocijacije.setTypeface(dugmad);
cigle.setTypeface(dugmad);
spojnice.setTypeface(dugmad);
nazad.setTypeface(dugmad);
poeniAso.setTypeface(dugmad);
toploHladno.setOnClickListener(this);
asocijacije.setOnClickListener(this);
cigle.setOnClickListener(this);
spojnice.setOnClickListener(this);
nazad.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
poeniAso.setText("" + poeni.brojPoenaUkupno); //I do it here
}
public void onClick(View v) {
switch(v.getId()){
case R.id.bIzbor1:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.GAME"));
break;
case R.id.bIzbor2:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.ASOCIJACIJE"));
break;
case R.id.bIzbor3:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzbor4:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzborNazad:
if(music == true){
buttonBack.start();
}
poeniAso.setText("");
finish();
break;
}
}
}
Because I don't find the piece of code where you start the new game, I can only say:
Asocijacije.brojPoenaUkupno = 0;
Probably want to reset your state when you close the in-game activity.
#Override
protected void onDestroy() {
super.onDestroy();
Asocijacije.brojPoenaUkupno = 0;
//whatever other things need to be reset.
}