【问题标题】:setText() not work [duplicate]setText()不起作用[重复]
【发布时间】:2017-10-20 10:52:42
【问题描述】:

我在 Activity.java 中有这段代码:

 public void scan(View view){
    EditText text = (EditText) findViewById(R.id.editText3);
    text.setText("asdas");
}

这在 Activity xml 中:

<Button
    android:id="@+id/button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:onClick="scan"
    android:text="Scane"
    android:textColor="#fff"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    tools:layout_editor_absoluteY="271dp"
    tools:layout_editor_absoluteX="8dp" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name"
    tools:layout_editor_absoluteX="89dp"
    tools:layout_editor_absoluteY="165dp" />

当点击按钮时应用程序崩溃:

Attempt to invoke virtual method 'void 
android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference

为什么,我用的是 Android Studio 最新版本??

【问题讨论】:

  • EditText 文本 = (EditText)view.findViewById(R.id.editText3);并检查您在同一活动或其他活动中的编辑文本 ID

标签: java android nullpointerexception


【解决方案1】:

似乎findViewById 返回null:即由于某种原因它没有找到您的编辑文本。

也许你只需要重建项目:Build - Rebuild Project

否则你搞砸了,必须发布更多信息

【讨论】:

    【解决方案2】:

    把这个Edittext初始化代码放在onCreate方法中。

    EditText text;
    protected void onCreate(Bundle savedInstanceState) {
     text = (EditText) findViewById(R.id.editText3);
    }
    
    public void scan(View view){
        text.setText("asdas");
    }
    

    【讨论】:

      【解决方案3】:

      您的 findViewById 正在返回 null,因为它没有上下文。 我认为您正在传递 view 对象作为上下文但没有使用它。 尝试改变

      EditText text = (EditText) findViewById(R.id.editText3);
      

      EditText text = (EditText) view.findViewById(R.id.editText3);
      

      【讨论】:

        【解决方案4】:

        在下面的代码中,你得到了相关的 EditText 对象

        EditText text = (EditText) findViewById(R.id.editText3);
        

        然后,您调用了该对象的 setText() 方法,但获取了空对象引用

        text.setText("asdas");
        

        这意味着您无法正确获取 EditText 对象。因此,错误的根源来自以下行:

        EditText text = (EditText) findViewById(R.id.editText3);
        

        请务必在正确的上下文中调用 scan() 方法。尝试在 onCreate() 方法中调用它。如果您从其他地方调用 findViewById() 方法,请务必从正确的上下文中调用它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-23
          • 1970-01-01
          • 1970-01-01
          • 2018-11-14
          • 2021-12-27
          相关资源
          最近更新 更多