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
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.