android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main
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));
:
@Overrideprotected 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.
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.