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

前端 未结 6 1324
攒了一身酷
攒了一身酷 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 01:56

    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.

    0 讨论(0)
  • 2020-12-05 01:57

    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));
    
    0 讨论(0)
  • 2020-12-05 02:00
    tv.setText( a1 + " ");
    

    This will resolve your problem.

    0 讨论(0)
  • 2020-12-05 02:01

    Other possible solution:

    tv.setText(Integer.toString(a1));  // where a1 - int value
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 02:12

    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()}" .../>

    0 讨论(0)
提交回复
热议问题