Android EditText has fixed input - java

This part of my program is supposed to be a user input field for the quantity of an item to purchase. What I'm unable to do is to make it so when the program finally runs on the emulator and I change the textfield number in the EditText, named "etxtQuantity" in my case, the number I use is ignored and it reverts to using the default entry. Also my if statement isn't working like I expect either, it accepts everything.
private void setupAddRecordButton() {
Button button = (Button) findViewById(R.id.btnAddCart);
button.setOnClickListener(new View.OnClickListener() {
final TextView countText = (TextView) findViewById(R.id.txtAddCartCount);
EditText quantity = (EditText) findViewById(R.id.etxtQuantity);
String quantity2 = quantity.getText().toString();
final TextView text2 = (TextView) findViewById(R.id.txtQuantityCheck);
#Override
public void onClick(View v) {
if (! quantity2.equals(".") || quantity2.equals("") || quantity2.equals("-")) {
count++;
long newId = myDb.insertRow("GTX 950", 140, quantity2);
myDb.getRow(newId);
countText.setText("Successfully added " + count + " Times");
}
else
{
text2.setText("Quantity needed!");
}
}
});
}

initailize your edit text in onCreate() callback function of your activity and use String quantity2 = quantity.getText().toString(); in onClick() function of your button
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText quantity = (EditText) findViewById(R.id.etxtQuantity);
Button button = (Button) findViewById(R.id.btnAddCart);
TextView text2 = (TextView) findViewById(R.id.txtQuantityCheck);
TextView countText = (TextView) findViewById(R.id.txtAddCartCount);
button.setOnClickListener(new View.OnClickListener() {
String quantity2 = quantity.getText().toString();
#Override
public void onClick(View v) {
if (! quantity2.equals(".") || quantity2.equals("") ||quantity2.equals("-")) {
count++;
long newId = myDb.insertRow("GTX 950", 140, quantity2);
myDb.getRow(newId);
countText.setText("Successfully added " + count + " Times");
}
else
{
text2.setText("Quantity needed!");
}
}
});
}

please move the this line
String quantity2 = quantity.getText().toString();
inside the onClick()

Try to use
quantity .addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
quantity2=charSequence.toString();
if (! quantity2.equals(".") || quantity2.equals("") || quantity2.equals("-")) {
count++;
long newId = myDb.insertRow("GTX 950", 140, quantity2);
myDb.getRow(newId);
countText.setText("Successfully added " + count + " Times");
}
else
{
text2.setText("Quantity needed!");
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});

Related

Wrong calculation after using sharedpreferences

I'm building an app to check prime numbers and display them. the user need to be able to save the number and load it upon restart of the app.
I have problem when retrieving the saved int from Sharedprefrences. the codes saves the int and loads it on the "loaddata" function. But when I start checking if the saved in is a primenumber, the code jumps 2 primenumbers. Eg if I save "11", the next primenumber should be "13" but it jumps to "19".
Would be great if someone could point into the right direction since i'm a bit of newbie.
public class MainActivity extends AppCompatActivity {
private TextView textView;
private EditText editText;
private Button applyPrimeButton;
private Button saveButton;
private Button loadButton;
public static final String SHARED_PREFS = "sharedPrefs";
int max = 500;
int j = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
editText = (EditText) findViewById(R.id.edittext);
applyPrimeButton = (Button) findViewById(R.id.apply_prime_button);
saveButton = (Button) findViewById(R.id.save_button);
loadButton = (Button) findViewById(R.id.load_button);
applyPrimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = j; i <= max; i++) {
if (isPrimeNumber(i)) {
textView.setText(i+"");
j = i+1;
break;
}
}
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
loadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
}
public boolean isPrimeNumber(int nummer) {
for (int i = 2; i <= nummer / 2; i++) {
if (nummer % i == 0) {
return false;
}
}
return true;
}
public void saveData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
int nummer = Integer.parseInt(textView.getText().toString());
editor.putInt("prime_save", nummer);
editor.commit();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
int nummer = sp.getInt("prime_save",0);
textView.setText(String.valueOf(nummer));
}
}
Several issues:
You are not updating j to the correct value when loading data, and instead relying on what you are displaying in the textview.
To find prime number, it is enough to check until the square root of the original number and not half of it.
Try this:
applyPrimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(j<max ){
if (isPrimeNumber(j)) {
textView.setText(j+"");
j++;
}
}
}
});
public void saveData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("prime_save", j);
editor.commit();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
int nummer = sp.getInt("prime_save",0);
j = nummer;
textView.setText(String.valueOf(nummer));
}

Could we define unknown amount of clickable texts which have different outputs in for loop?

I want all ClickableSpans to have toasts show their own text. But whatever I write in Toast in onClick in for loop, all ClickableSpans show same Toast output. Briefly, I just want ClickableSpans to show different Toasts in for loop. How can I do it? I want all words have clickable. And when all words are clicked, they do different thing. Thank you for your help.
public class MainActivity extends AppCompatActivity {
private String[] textArray;
private String text = "1981 senesinde kuantum bilgisayar fikrini Paul Beniof, Max Planck’ın " +
"enerjinin sürekli olmadan kesikli değerlerde yer alan m, n, k enerji kuantlarıyla ";
private Chronometer chronometer;
private int hold=0;
private TextView textView;
private int i;
private MediaPlayer player;
private long pauseOffset;
private boolean running;
private boolean start=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textArray = text.split(" ");
final SpannableString ss = new SpannableString(text);
chronometer = findViewById(R.id.chronometer);
chronometer.setFormat("Time: %s");
chronometer.setBase(SystemClock.elapsedRealtime());
textView = findViewById(R.id.text_view);
textView.setText(text);
textView.setTextColor(Color.BLACK);
final ClickableSpan[] clickableSpans = new ClickableSpan[textArray.length];
for(i = 0; i<textArray.length; i++){
clickableSpans[i] = new ClickableSpan() {
#Override
public void onClick(View widget) {
Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(Color.BLACK);
ds.setUnderlineText(false);
}
};
final boolean[] c = {true};
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
if ((SystemClock.elapsedRealtime() - chronometer.getBase()) >= 5000&& c[0]) {
for(int i=0; i<textArray.length;i++){
ss.setSpan(clickableSpans[i], hold, hold + textArray[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
hold+=textArray[i].length();
hold++;
}
start=false;
hold=0;
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
if (running) {
chronometer.stop();
pauseOffset = SystemClock.elapsedRealtime() - chronometer.getBase();
running = false;
}
c[0]=false;
}
}
});
hold=0;
}
i=0;
}
public void play(View v) {
if(start){
if (!running) {
chronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
chronometer.start();
running = true;
}
}
}
public void stop(View v) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}

when i press dot button i want that dot button press only one time in input 1?

package com.deitel.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
double input1 = 0, input2 = 0d ,count=0;
Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn_dot, btn_equal, btn_subtract, btn_multi, btn_add, btn_devision, btn_clear, btn_back;
TextView text_result;
boolean Addition, Subtraction, Multiplication, Devision, decimal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btn_dot = findViewById(R.id.btn_dot);
btn_equal = findViewById(R.id.btn_equal);
btn_add = findViewById(R.id.btn_add);
btn_subtract = findViewById(R.id.btn_subtract);
btn_multi = findViewById(R.id.btn_multi);
btn_devision = findViewById(R.id.btn_devision);
btn_clear = findViewById(R.id.btn_clear);
btn_back = findViewById(R.id.btn_back);
text_result = findViewById(R.id.text_result);
btn0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "9");
}
});
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Addition = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Subtraction = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_multi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Multiplication = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_devision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Devision = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText("");
input1 = 0.0;
input1 = 0.0;
}
});
btn_dot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
count=1;
text_result.setText(text_result.getText()+".");
return;
}
else{
text_result.setText(text_result.getText()+"0.");
decimal=true;
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number = text_result.getText().toString();
int input = number.length();
if (input > 0) {
text_result.setText(number.substring(0, input - 1));
}
}
});
btn_equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count=0;
if ((Addition || Subtraction || Multiplication || Devision) ) {
if (text_result.getText().toString().trim().equals("")){
input2=0;
return;
}else {
input2 = Float.parseFloat(text_result.getText() + "");
}
}
if (Addition) {
text_result.setText(input1 + input2 + "");
Addition = false;
}
if (Subtraction) {
text_result.setText(input1 - input2 + "");
Subtraction = false;
}
if (Multiplication) {
text_result.setText(input1 * input2 + "");
Multiplication = false;
}
if (Devision) {
text_result.setText(input1 / input2 + "");
Devision = false;
}
}
});
}
}
When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
But this code doesn't meet that requirements - it displays 2.3.4.5 etc..but I want only one dot in one input. When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
Here you can manage that with simple flag.
public class MainActivity extends AppCompatActivity {
// IDs of all the numeric buttons
private int[] numericButtons = {R.id.btnZero, R.id.btnOne, R.id.btnTwo, R.id.btnThree, R.id.btnFour, R.id.btnFive, R.id.btnSix, R.id.btnSeven, R.id.btnEight, R.id.btnNine};
// IDs of all the operator buttons
private int[] operatorButtons = {R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide};
// TextView used to display the output
private TextView txtScreen;
// Represent whether the lastly pressed key is numeric or not
private boolean lastNumeric;
// Represent that current state is in error or not
private boolean stateError;
// If true, do not allow to add another DOT
private boolean lastDot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
/**
* Find and set OnClickListener to numeric buttons.
*/
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
/**
* Find and set OnClickListener to operator buttons, equal button and decimal point button.
*/
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
lastDot = false; // Reset the DOT flag
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Decimal point
findViewById(R.id.btnDot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lastNumeric && !stateError && !lastDot) {
txtScreen.append(".");
lastNumeric = false;
lastDot = true;
}
}
});
// Clear button
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
}
});
// Equal button
findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});
}
/**
* Logic to calculate the solution.
*/
private void onEqual() {
// If the current state is error, nothing to do.
// If the last input is a number only, solution can be found.
if (lastNumeric && !stateError) {
// Read the expression
String txt = txtScreen.getText().toString();
// Create an Expression (A class from exp4j library)
Expression expression = new ExpressionBuilder(txt).build();
try {
// Calculate the result and display
double result = expression.evaluate();
txtScreen.setText(Double.toString(result));
lastDot = true; // Result contains a dot
} catch (ArithmeticException ex) {
// Display an error message
txtScreen.setText("Error");
stateError = true;
lastNumeric = false;
}
}
}
}

How to disable button if ANY EditText is empty?

Ive tried using TextWatcher, but if i create multiple TextWatchers(one for each EditText), the button enables when I start filling out any of the EditText.
Example:
public class MainActivity extends AppCompatActivity {
EditText numberOneEditText;
EditText numberTwoEditText;
EditText numberThreeEditText;
TextView sumTextView;
public void calculate(View view) {
String numberOneString = numberOneEditText.getText().toString();
String numberTwoString = numberTwoEditText.getText().toString();
String numberThreeString = numberThreeEditText.getText().toString();
double numberOneDouble = Double.parseDouble(numberOneString);
double numberTwoDouble = Double.parseDouble(numberTwoString);
double numberThreeDouble = Double.parseDouble(numberThreeString);
double sum = numberOneDouble + numberTwoDouble + numberThreeDouble;
sumTextView.setText(sum.getText().toString())
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberOneEditText = findViewById(R.id.numberOneEditText);
numberTwoEditText = findViewById(R.id.numberTwoEditText);
numberThreeEditText = findViewById(R.id.numberThreeEditText);
sumTextView = findViewById(R.id.sumTextView);
}
}
Use TextWatcher. It will solve your problem:
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length()==0){
btn.setEnabled(false);
} else {
btn.setEnabled(true);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
This must solve your problem:
public class AppActivity extends Activity {
private EditText editText1;
private EditText editText2;
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
checkFieldsForEmptyValues();
}
#Override
public void afterTextChanged(Editable editable) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_activity);
editText1 = (EditText) findViewById(R.id.reg_password);
editText2 = (EditText) findViewById(R.id.reg_password2);
editText1.addTextChangedListener(textWatcher);
editText2.addTextChangedListener(textWatcher);
checkFieldsForEmptyValues();
}
private void checkFieldsForEmptyValues(){
Button btn = (Button) findViewById(R.id.btnId);
String s1 = editText1.getText().toString();
String s2 = editText2.getText().toString();
if (s1.length() > 0 && s2.length() > 0) {
btn.setEnabled(true);
} else {
btn.setEnabled(false);
}
}
}
Thanks.
Your text watcher should check that all three EditTexts have data (preferably also make sure that they are double, and display a label with an error message if otherwise)
Something like this:
TextWatcher watcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void afterTextChanged(Editable s) {
for (EditText et : new EditText[] {numberOneEditText,
numberTwoEditText, numberThreeEditText}) {
try {
Double.parseDouble(et.getText());
} catch (NumberFormatException e) {
// Disable button, show error label, etc.
button.setEnabld(false);
return;
}
}
//Enable buttton, hide error label if available
button.setEnabled(true);
}
};
}
numberOneEditText.addTextChangedListener(watcher);
numberTwoEditText.addTextChangedListener(watcher);
numberThreeEditText.addTextChangedListener(watcher);
You only have to declare one textwatcher which you assign to all edittexts. Then :
btn.setEnabled(!(str1.isEmpty || str2.isEmpty() || str3.isEmpty));
You could also directly check if it is a valid double and not enable if not.
EditText numberOneEditText;
EditText numberTwoEditText;
EditText numberThreeEditText;
TextView sumTextView;
public void calculate(View view) {
boolean isValid = true;
String numberOneString = numberOneEditText.getText().toString();
String numberTwoString = numberTwoEditText.getText().toString();
String numberThreeString = numberThreeEditText.getText().toString();
if(numberOneString.trim().isEmpty ||numberTwoString.trim().isEmpty()
|| numberThreeString.trim().isEmpty()){
isValid = false;}
if(isValid){
double numberOneDouble = Double.parseDouble(numberOneString);
double numberTwoDouble = Double.parseDouble(numberTwoString);
double numberThreeDouble = Double.parseDouble(numberThreeString);
double sum = numberOneDouble + numberTwoDouble + numberThreeDouble;
sumTextView.setText(sum.getText().toString())
}
}

Java global int

In an Android Studio app, I have following code:
boolean clicked = true;
Button btnumb1 = (Button) this.findViewById(R.id.numb1);
Button btnumb2 = (Button) this.findViewById(R.id.numb2);
Button btnumb3 = (Button) this.findViewById(R.id.numb3);
Button btnumb4 = (Button) this.findViewById(R.id.numb4);
btnumb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked = false;
}
});
Button Start = (Button) this.findViewById(R.id.Start);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
Random rand = new Random();
int n = rand.nextInt(4) + 1;
TextView textView = (TextView) findViewById(R.id.randOutput);
textView.setText("" + n);
}
else{
Toast.makeText(getApplicationContext(), "You have to choose a number", Toast.LENGTH_LONG).show();
}
}
});
The idea is that when one of the 4 buttons is clicked, the int clicked is set to 1 and so the final button can only be clicked when it is 1.
But the code doesn't work like this; int clicked = 0; can't be accessed in other public void.
If one of the numbers 1,2,3,4 is clicked then final button can be clicked
The fix: Put public static boolean clicked = false;
under your public class YourClassName { line.
Reasoning: You need to learn how to scope your variables properly. You declared boolean clicked inside the onCreate() function, so the variable is gone after onCreate() is done running.
You should have put the clicked variable inside the class scope level, via public boolean clicked or public static boolean clicked so that even after the function returns, the value is saved.
I highly recommend a beginners java course or textbook before continuing on with your project(s).
Java does not have any concept of global variables. There is either an instance variable or a class variable. To define Global Variable you can make use of static Keyword.
static boolean clicked = true;
Button btnumb1 = (Button) this.findViewById(R.id.numb1);
Button btnumb2 = (Button) this.findViewById(R.id.numb2);
Button btnumb3 = (Button) this.findViewById(R.id.numb3);
Button btnumb4 = (Button) this.findViewById(R.id.numb4);
btnumb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked = false;
}
});
Button Start = (Button) this.findViewById(R.id.Start);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
Random rand = new Random();
int n = rand.nextInt(4) + 1;
TextView textView = (TextView) findViewById(R.id.randOutput);
textView.setText("" + n);
}
else{
Toast.makeText(getApplicationContext(), "You have to choose a number", Toast.LENGTH_LONG).show();
}
}
});
Yes the variable int clicked = 0; has to be declared final before it is accessible in the other public void functions.
Try this declared a class say ClassClicked
public class ClassClicked {
int clicked;
public int getClicked() {
return clicked;
}
public void setClicked(int clicked) {
this.clicked = clicked;
}
}
Then changed
int clicked = 0;
to
final ClassClicked clicked = new ClassClicked();
clicked.setClicked(0);
And
clicked = 1;
to
clicked.setClicked(1);
Finally
clicked == 1
to
clicked.getClicked() == 1

Categories

Resources