【问题标题】:App crashing because of setText being called on a null object reference由于在空对象引用上调用 setText,应用程序崩溃
【发布时间】:2018-07-21 22:18:22
【问题描述】:

我对编程非常陌生,因此非常感谢您的帮助,这是我第一次在这里寻求帮助,希望我做得对。

我正在尝试在应用程序中创建一个简单的笔记记录部分,但出现以下错误:

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

代码如下:

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

   
    et_memo =  (EditText) findViewById(R.id.et_memo);

    b_clear = (Button) findViewById(R.id.b_clear);
    b_save = (Button) findViewById(R.id.b_save);

    SharedPreferences preferences = getSharedPreferences("PREFS", 0);
    memo = preferences.getString("memo","");

    et_memo.setText(memo);

    b_clear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            memo ="";
            et_memo.setText(memo);
        }
    });

    b_save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            memo = et_memo.getText().toString();

            SharedPreferences preferences = getSharedPreferences("PREFS", 0);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("memo", memo);
            editor.commit();

            Toast.makeText(MainActivity.this, "Note saved!", 
Toast.LENGTH_SHORT).show();

这是我的 XML 文件:

<android.support.v7.widget.LinearLayoutCompat
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:orientation="vertical">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="70dp"
        android:inputType="textNoSuggestions"
        android:textSize="16sp"
        android:textColor="@color/black"
        android:id="@+id/et_memo"
        android:layout_marginStart="20dp"
        android:layout_marginLeft="20dp" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="CLEAR"
            android:id="@+id/b_clear"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="SAVE"
            android:id="@+id/b_save"/>
    </LinearLayout>
</android.support.v7.widget.LinearLayoutCompat>`

【问题讨论】:

  • 嗨 Rikits。您能否确认帖子中显示的 XML 文件在您的项目中被称为:“activity_main.xml”?谢谢。
  • 错误信息应该告诉你它来自哪一行。请指出它在您发布的代码中的哪一行。
  • 是的,这是正确的 Elltlar。它被称为 Activity_main。 @TylerV - 错误信息指向以下行 --> et_memo.setText(memo);

标签: java android android-layout android-edittext


【解决方案1】:

导致该特定错误的最常见原因是 XML 文件中缺少“et_memo”。问题是如果您的项目中的任何 XML 文件包含“@​​+id/et_memo”代码“findViewById(R.id.et_memo);”会编译得很好。但是,如果在调用“setContentView”时指定了一个不包含“et_memo”的 XML 文件,则不会找到该视图,而是将其设置为“null”。如果您调用空对象的任何方法,则会立即发生崩溃。另外,如果您在其他布局目录中有任何其他版本的“activity_main.xml”,请注意它们也具有所有必要的视图。

下面的这段代码在我的环境中运行得很好。

代码:

package com.example.elletlar.simpletests;

import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private String memo;

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


        final EditText et_memo =  findViewById(R.id.et_memo);

        final Button b_clear = findViewById(R.id.b_clear);
        final Button b_save = findViewById(R.id.b_save);

        SharedPreferences preferences = getSharedPreferences("PREFS", 0);
        memo = preferences.getString("memo","");

        et_memo.setText(memo);

        b_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_memo.setText("");

                SharedPreferences preferences = getSharedPreferences("PREFS", 0);
                SharedPreferences.Editor editor = preferences.edit();
                editor.remove("memo");
                editor.apply();

            }
        });

        b_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                memo = et_memo.getText().toString();

                SharedPreferences preferences = getSharedPreferences("PREFS", 0);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("memo", memo);
                editor.apply();

                Toast.makeText(MainActivity.this, "Note saved!",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

}

XML:

<android.support.v7.widget.LinearLayoutCompat
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="70dp"
        android:inputType="textNoSuggestions"
        android:textSize="16sp"
        android:textColor="#000000"
        android:id="@+id/et_memo"
        android:layout_marginStart="20dp"
        android:layout_marginLeft="20dp" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="2"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="CLEAR"
            android:id="@+id/b_clear"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="SAVE"
            android:id="@+id/b_save"/>
    </LinearLayout>
</android.support.v7.widget.LinearLayoutCompat>
  • 在 SharedPreferences 上将 commit() 更改为 apply():Apply 效率更高,因为它不会阻塞主线程。
  • 删除了不必要的强制转换:在较新版本的 Java 中,我们可以简单地编写“final EditText et_memo = findViewById(R.id.et_memo);”无需对 findViewById 进行强制转换
  • 我冒昧地完成了“清除”按钮的 onClick 处理程序
  • 对 XML 文件的微小更改

【讨论】:

  • 您好 Elletlar,感谢您的回复。应用程序仍然崩溃,但出现完全相同的错误,该错误指向以下行作为原因: (LINE 116) 这是 --> et_memo.setText(memo);只是想让你知道,我不在我的零件应用程序的任何其他部分中使用 et_memo id
  • 它对我来说很好用。您能否检查所有布局目录以确保没有其他标题为:activity_main.xml 的文件。另外,也许做一个 Build -> Clean Project。
  • 您可能还想使用我的 XML 文件,因为发布的文件缺少架构。我不确定为什么 Android Studio 允许这样做。
  • 嘿伙计,我实际上复制了你所有的代码,但它仍然给了我完全相同的错误。只有一个名为 activity_main 的文件,并且多次尝试清理项目但没有任何运气
  • 好的,谢谢老兄,会多玩一点,如果我不明白,会上传并让你知道。感谢您的时间和精力,非常感谢。
猜你喜欢
  • 2021-08-02
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
相关资源
最近更新 更多