I'm trying to make an app that only allows a user to enter between 1 and 10, I've tried writing my own method where if the number is out of that range, it changes the text views to ERROR and clears what's in the edit text, however it crashes the app. Does anyone know what's wrong with it? New to android.
Code:
public void buttonClick (View v)
{
TextView tvNum = (TextView) findViewById(R.id.tvNumEnt);
TextView tvName = (TextView) findViewById(R.id.tvNumEnt);
TextView tvNameEnt = (TextView) findViewById(R.id.NameEnt);
TextView tvNumEnt = (TextView) findViewById(R.id.NumEnt);
EditText num = (EditText) findViewById(R.id.ETnumber);
EditText name = (EditText) findViewById(R.id.ETname);
String nameContent = name.getText().toString();
String numContent = num.getText().toString();
tvName.setText(nameContent);
int value = Integer.parseInt(num.getText().toString());
if (value > 10)
{
tvNum.setText("ERROR");
num.getText().clear();
name.getText().clear();
}
else if (value < 1)
{
tvNum.setText("ERROR");
num.getText().clear();
name.getText().clear();
}
else
{
tvNum.setText(numContent);
tvNameEnt.setVisibility(View.VISIBLE);
tvNumEnt.setVisibility(View.VISIBLE);
tvName.setVisibility(View.VISIBLE);
tvNum.setVisibility(View.VISIBLE);
}
}
The main problem here is that you are trying to get the number in the edittext with:
num.toString()
, instead you have to use:num.getText().toString()
You have issue on this line
change to:
Now you call
toString()
method fromObject
forEditText
object. You have to callgetText()
method for it as first and after then calltoString()
method forCharSequence
UPDATE: You find two times the same view with the same ids. Look at the code below:
there should be
R.id.tvNumEnt
in the second time, I think so...