【问题标题】:why does my app crash when I use the setText Mehod? [duplicate]为什么我的应用程序在使用 setText 方法时会崩溃? [复制]
【发布时间】:2017-09-10 09:26:58
【问题描述】:

问题:
为什么每当我尝试使用 setText() 方法将随机数字分配为按钮文本时,我的应用程序就会崩溃?

我的目标是为按钮设置随机数字,如果用户单击数字较大的按钮,他/她将获得一分。

我调试了程序,发现逻辑工作正常。但是,该应用程序在启动时不断崩溃,我不知道根本问题到底是什么。

主要活动:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private static int points, rand1, rand2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        points =0;
        randomize();
    }


    public void onLeftClick(View view) {

        if(rand1 > rand2)
            points++;
        else
            points--;

        TextView text = (TextView) findViewById(R.id.pointText);
        text.setText("Points : "+points);

        randomize();
    }

    public void onRightClick(View view) {

        if(rand2 > rand1)
            points++;
        else
            points--;

        TextView text = (TextView) findViewById(R.id.pointText);
        text.setText("Points : "+points);

        randomize();
    }

    private void randomize() {

        Random random = new Random();
        rand1= random.nextInt(10);
        rand2 = 0;

        while (true) {
            rand2 = random.nextInt(10);
            if (rand1 != rand2)
                break;
        }


        Button leftButton = (Button)findViewById(R.id.leftButton);
        leftButton.setText((char)rand1);   **ERROR HERE**
        Button rightButton = (Button)findViewById(R.id.rightButton);
        rightButton.setText((char)rand2);
    }

}

XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.clickgame.MainActivity">

    <TextView
        android:layout_width="119dp"
        android:layout_height="24dp"
        android:text="CLICK GAME"
        android:textAlignment="center"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.032"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintLeft_creator="1" />

    <Button
        android:id="@+id/leftButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="215dp"
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="216dp"
        android:onClick="onLeftClick"
        android:text="0"
        app:layout_constraintBottom_toTopOf="@+id/pointText"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintTop_creator="1" />

    <Button
        android:id="@+id/rightButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="215dp"
        android:layout_marginEnd="18dp"
        android:layout_marginRight="18dp"
        android:layout_marginTop="216dp"
        android:onClick="onRightClick"
        android:text="0"
        app:layout_constraintBottom_toTopOf="@+id/pointText"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout_constraintBottom_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintTop_creator="1" />

    <TextView
        android:id="@+id/pointText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="POINTS : 0"
        android:textStyle="bold"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintBottom_creator="1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_constraintLeft_creator="1"
        android:layout_marginBottom="16dp"
        app:layout_constraintLeft_toLeftOf="parent" />

</android.support.constraint.ConstraintLayout>

错误日志:

09-10 14:51:53.742 478-478/? E/AndroidRuntime: FATAL EXCEPTION: main
                                               Process: com.example.clickgame, PID: 478
                                               java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.clickgame/com.example.clickgame.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x6
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                   at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                   at android.os.Handler.dispatchMessage(Handler.java:102)
                                                   at android.os.Looper.loop(Looper.java:154)
                                                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x6
                                                   at android.content.res.Resources.getText(Resources.java:335)
                                                   at android.widget.TextView.setText(TextView.java:4555)
                                                   at com.example.clickgame.MainActivity.randomize(MainActivity.java:66) //THIS LINE
                                                   at com.example.clickgame.MainActivity.onCreate(MainActivity.java:22) //THIS LINE
                                                   at android.app.Activity.performCreate(Activity.java:6679)
                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                                                   at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                                                   at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                   at android.os.Looper.loop(Looper.java:154) 
                                                   at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                   at java.lang.reflect.Method.invoke(Native Method) 
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

【问题讨论】:

  • 错误是什么?向我们展示 logcat 错误
  • @MahdiNouri 添加了错误日志!

标签: android events settext


【解决方案1】:

为了补充 Amirhossein Naghshzan 的答案,这里发生的是 TextView 的 setText 方法能够使用 resourceId 作为参数。当您将整数传递给此方法时,它会尝试查找具有该 ID 的字符串资源。如果找不到,则会引发异常,因此需要使用 String.valueOf() 包装一个数字值

【讨论】:

  • 谢谢!这清除了它!
【解决方案2】:

使用String.valueof() 将int 转换为字符串:

leftButton.setText(String.valueof(rand1));
rightButton.setText(String.valueof(rand2));

【讨论】:

    【解决方案3】:

    使用String.valueof(),在.settext()的括号内

    示例:

     TextView text = (TextView) findViewById(R.id.pointText);
        text.setText("Points : "+ String.valueof(points));
    

    如果你看一眼这个java documentation,你会看到String.valueOf()返回:

    如果参数是null,则字符串等于"null";否则返回obj.toString()的值。

    所以除了额外的方法调用之外应该没有什么区别。

    此外,如果实例为 null,则在 Object#toString, 的情况下,将抛出 NullPointerException,因此可以说它不太安全。

    【讨论】:

    • 为什么在这种情况下 toString() 方法不起作用?
    • 我已经编辑了我的答案,进一步解释了 toString 和 String.ValueOf 之间的区别
    【解决方案4】:

    我已经清理了你的活动,请改用这个:

    public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    
        private int 
                 points = 0, 
                 rand1, 
                 rand2;
    
        private TextView text;
    
        private Button leftButton, rightButton;
    
        private Random random = new Random();
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            text = (TextView) findViewById(R.id.pointText);
    
            leftButton = (Button)findViewById(R.id.leftButton);
            leftButton.setOnClickListener(this);
    
            rightButton = (Button)findViewById(R.id.rightButton);
            rightButton.setOnClickListener(this);
    
            randomize();
        }
    
        private void randomize() {
    
            rand1 = random.nextInt(10);
            rand2 = 0;
    
            while (true) {
                rand2 = random.nextInt(10);
                if (rand1 != rand2)
                    break;
            }
            leftButton.setText(String.valueOf(rand1));
            rightButton.setText(String.valueOf(rand2));
        }
    
        @Override
        public void onClick(View v){
    
            switch(v.getId()){
    
                case R.id.leftButton{
    
                    if(rand1 > rand2)
                        points++;
                    else
                        points--;
    
    
                    text.setText("Points : " + String.valueOf(points));
    
                    randomize();
    
                }break;
    
                case R.id.rightButton:{
    
                    if(rand2 > rand1)
                        points++;
                    else
                        points--;
    
    
                    text.setText("Points : " + String.valueOf(points));
    
                    randomize();
    
                }break;
    
         }
    
     }
    

    }

    【讨论】:

      【解决方案5】:

      你的错误是:

      Resources$NotFoundException: 字符串资源 ID

      您必须在您的查看项目上设置 ID:

      <TextView
      android:id="@+id/pointText"
      

      【讨论】:

      • 已经设置好了。原来我必须使用 String.tovalues() 方法。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多