简体   繁体   English

由于在空对象引用上调用 setText 而导致应用程序崩溃

[英]App crashing because of setText being called on a null object reference

I am extremely new to programming so your help will be greatly appreciated and this is the first time I am asking for help here so hope I am doing it right.我对编程非常陌生,因此非常感谢您的帮助,这是我第一次在这里寻求帮助,所以希望我做得对。

I am trying to create a simple notes taking section in an app but I am getting the following error:我正在尝试在应用程序中创建一个简单的笔记记录部分,但出现以下错误:

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

Here is the code:这是代码:

@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();

Here is my XML file:这是我的 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>`

The most common cause for that particular error is that "et_memo" is missing from the XML file.该特定错误的最常见原因是 XML 文件中缺少“et_memo”。 The problem is that if any XML file in your project contains "@+id/et_memo" the code "findViewById(R.id.et_memo);"问题在于,如果您的项目中的任何XML 文件包含“@​​+id/et_memo”,则代码“findViewById(R.id.et_memo);” will compile just fine.会编译得很好。 BUT, if when calling "setContentView" an XML file is specified that does not contain "et_memo", the view will not be found and instead it will be set to "null".但是,如果在调用“setContentView”时指定了不包含“et_memo”的 XML 文件,则不会找到该视图,而是将其设置为“null”。 If you invoke any methods of a null object an immediate crash will happen.如果您调用空对象的任何方法,则会立即发生崩溃。 Also, be ware if you have any other versions of "activity_main.xml" in other layout directories, make sure they have all the necessary views as well.另外,如果您在其他布局目录中有任何其他版本的“activity_main.xml”,请确保它们也具有所有必要的视图。

This code below runs just fine in my environment.下面的这段代码在我的环境中运行得很好。

Code:代码:

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();
            }
        });
    }

}

The XML: 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>
  • Changed commit() to apply() on SharedPreferences: Apply is more efficient because it doesn't block the main thread.在 SharedPreferences 上将 commit() 更改为 apply():Apply 效率更高,因为它不会阻塞主线程。
  • Removed unnecessary casts: In newer versions of Java, we can simply write "final EditText et_memo = findViewById(R.id.et_memo);"删除了不必要的强制转换:在较新版本的 Java 中,我们可以简单地编写“final EditText et_memo = findViewById(R.id.et_memo);” without putting a cast on findViewById没有对 findViewById 进行强制转换
  • I took the liberty of finishing the onClick handler for the "clear" button我冒昧地完成了“清除”按钮的 onClick 处理程序
  • Minor changes to the XML file对 XML 文件的细微更改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android应用程序中setText上的空对象引用 - Null object reference on setText in Android app 带有注释的空对象引用上的setText - setText on null object reference with Annotations 应用程式因空物件参照而当机 - App crashes because of null object reference 如何解决Textview setText()在空对象引用上 - How to solve Textview setText() is on a null object reference Android TextView SetText null 对象引用错误 - Android TextView SetText null object reference error 空对象引用上的navigationView setText致命异常 - navigationView setText fatal exception on a null object reference 空对象参考:应用程序崩溃 - Null Object Reference: Application Crashing Android App在setText上崩溃 - Android App crashing on setText 由于尝试在 null object 引用上调用虚拟方法“”,应用程序崩溃 - App crashes because of attempt to invoke virtual method ' ' on a null object reference TensorFlow Lite Android 应用程序在空对象引用上因 NullPointerException &#39;void android.widget.TextView.setText(java.lang.CharSequence)&#39; 崩溃 - TensorFlow Lite Android App crashes with NullPointerException 'void android.widget.TextView.setText(java.lang.CharSequence)' on null object reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM