I\'ve been trying to make a simple program that fetches a small random number and displays it to the user in a textview. After finally getting the random number to generate
You tried to do a.setText(a1). a1 is an int value, but setText() requires a string value. For this reason you need use String.valueOf(a1) to pass the value of a1 as a String and not as an int to a.setText(), like so:
a.setText(String.valueOf(a1))
that was the exact solution to the problem with my case.
You are trying to set int value to TextView
so you are getting this issue.
To solve this try below one option
option 1:
tv.setText(no+"");
Option2:
tv.setText(String.valueOf(no));
tv.setText( a1 + " ");
This will resolve your problem.
Other possible solution:
tv.setText(Integer.toString(a1)); // where a1 - int value
Move
Random pp = new Random();
int a1 = pp.nextInt(10);
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(a1);
To inside onCreate()
, and change tv.setText(a1);
to tv.setText(String.valueOf(a1));
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random pp = new Random();
int a1 = pp.nextInt(10);
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(String.valueOf(a1));
}
First issue: findViewById()
was called before onCreate()
, which would throw an NPE.
Second issue: Passing an int directly to a TextView calls the overloaded method that looks for a String resource (from R.string
). Therefore, we want to use String.valueOf()
to force the String
overloaded method.
This always can happen in DataBinding. Try to stay away from adding logic in your bindings, including appending an empty string. You can make your own custom adapter, and use it multiple times.
@BindingAdapter("numericText")
fun numericText(textView: TextView, value: Number?) {
value?.let {
textView.text = value.toString()
}
}
<TextView app:numericText="@{list.size()}" .../>