I am new to android programming. And I wanted to set the value of x in edittext and display it on the toast through edittext.The main problem is in x.getText().It gives an error Cannot invoke getText() on the primitive type int. plz can anyone help me its an emergency..?
Button butt;
EditText edi;
final int x=10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edi=(EditText)findViewById(R.id.ed);
final int y = Integer.parseInt(x.getText().toString());
edi.setText(" "+y);
butt=(Button)findViewById(R.id.but);
butt.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String s= edi.getText().toString();
Toast.makeText(this, ""+s, 0).show();
}
try this code:
in oncreate method:
edi=(EditText)findViewById(R.id.ed);
final int y = x;
edi.setText(" "+y);
butt=(Button)findViewById(R.id.but);
butt.setOnClickListener(this);
The reason for getting error is you are tried to convert the int as int actually the function Integer.parseInt(String s)
is used to convert the string to int.in your case it is in int type. So that you got an error.
you should be using
final int y = Integer.parseInt(edi.getText().toString());
instead of
final int y = Integer.parseInt(x.getText().toString());
PROBLEM
final int y = Integer.parseInt(x.getText().toString()); // delete this line, getText() is used on objects, to fetch the text from it.
CHANGE THIS
edi.setText(" "+y);
TO
edi.setText(" "+x);
Instead of " " +
, it's good practice to use String.valueOf(int)
.
edi.setText(String.valueOf(x));
you got error at this line
final int y = Integer.parseInt(x.getText().toString());
because x is Integer there is no getText()
method for Integer
you use this
edi.setText(" "+x);
final int y = Integer.parseInt(edi.getText().toString());
or
final int y = x;
edi.setText(" "+y);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.