android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

前端 未结 6 1332
攒了一身酷
攒了一身酷 2020-12-05 01:15

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

6条回答
  •  醉酒成梦
    2020-12-05 02:10

    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.

提交回复
热议问题