【问题标题】:TextView.setText throws NullPointerException despite given String not being null尽管给定的 String 不为 null,TextView.setText 仍会引发 NullPointerException
【发布时间】:2021-09-06 20:40:52
【问题描述】:

当我尝试为我的程序设置作者和日期时,TextView.setText 方法会引发 NullPointerException: Content of the Custom Object

错误 1:

E/AndroidRuntime: 致命异常: main 进程:com.example.jokestarapplication,PID:10886 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.jokestarapplication/com.example.jokestarapplication.ActivityJokeDetail}:java.lang.NullPointerException:尝试调用虚拟方法 'void android.widget.TextView.setText(java. lang.CharSequence)' 在空对象引用上 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:193) 在 android.app.ActivityThread.main(ActivityThread.java:6669) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)' 在 com.example.jokestarapplication.ActivityJokeDetail.onCreate(ActivityJokeDetail.java:44) 在 android.app.Activity.performCreate(Activity.java:7136) 在 android.app.Activity.performCreate(Activity.java:7127) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:193) 在 android.app.ActivityThread.main(ActivityThread.java:6669) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

错误 2:

E/AndroidRuntime: 致命异常: main 进程:com.example.jokestarapplication,PID:11116 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.jokestarapplication/com.example.jokestarapplication.ActivityJokeDetail}:java.lang.NullPointerException:尝试调用虚拟方法 'void android.widget.TextView.setText(java. lang.CharSequence)' 在空对象引用上 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:193) 在 android.app.ActivityThread.main(ActivityThread.java:6669) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)' 在 com.example.jokestarapplication.ActivityJokeDetail.onCreate(ActivityJokeDetail.java:45) 在 android.app.Activity.performCreate(Activity.java:7136) 在 android.app.Activity.performCreate(Activity.java:7127) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:193) 在 android.app.ActivityThread.main(ActivityThread.java:6669) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

活动


import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

public class ActivityJokeDetail extends AppCompatActivity {

    public static final String KEY_JOKEDETAILS = "JOKEDETAILS";
    private Joke joke;
    private TextView tvJokeText, tvJokeVote, tvAuthor, tvPostedDate;
    private EditText etNewComment;
    private Button btJokeUp, btJokeDown, btSendComment ;
    private RecyclerView recyclerView;
    private View include;
    private AdapterJokeDetail mAdapter;

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

        joke = getIntent().getParcelableExtra(KEY_JOKEDETAILS);

        include = findViewById(R.id.include);
        tvJokeText = include.findViewById(R.id.tvCommentText);
        tvJokeVote = include.findViewById(R.id.tvCommentVotes);
        tvAuthor = include.findViewById(R.id.tvAuthor);
        tvPostedDate = include.findViewById(R.id.tvPostDate);
        btJokeUp = include.findViewById(R.id.btCommentUp);
        btJokeDown = include.findViewById(R.id.btCommentDown);

        tvJokeText.setText(joke.getText());
        tvJokeVote.setText(Integer.toString(joke.getVotes()));
        // TODO: tvAuthor.setText(joke.getAuthor());
        // TODO: tvPostedDate.setText(joke.getPostedDate().toString());
        etNewComment = findViewById(R.id.etNewComment);
        btSendComment = findViewById(R.id.btSendComment);


        recyclerView = findViewById(R.id.rvComments);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);

        mAdapter = new AdapterJokeDetail(joke.getComments());
        recyclerView.setAdapter(mAdapter);

        btSendComment.setOnClickListener(v -> {
            SendComment();
            mAdapter.notifyDataSetChanged();
        });
    }


    private void SendComment() {
        Comment comment = new Comment(etNewComment.getText().toString(),0,"author"); //TODO: add author
        joke.getComments().add(comment);
    }
}

笑话

package com.example.jokestarapplication;

import android.os.Parcel;
import android.os.Parcelable;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Joke  implements Parcelable {
    private String text;
    private int votes;
    private Date postedDate;
    private String author;
    private String authorId;
    private String category;
    private List<Comment> comments;

    public Joke(String text, Date postedDate, String category, String author, String authorId, List<Comment> arrayList) {
        this.text = text;
        this.votes = 0;
        this.postedDate = postedDate;
        this.author = author;
        this.authorId = authorId;
        this.category = category;
        this.comments = arrayList;
    }


    protected Joke(Parcel in) {
        text = in.readString();
        votes = in.readInt();
        postedDate = new Date(in.readLong());
        author = in.readString();
        authorId = in.readString();
        category = in.readString();
        comments = in.createTypedArrayList(Comment.CREATOR);
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(text);
        dest.writeInt(votes);
        dest.writeLong(postedDate.getTime());
        dest.writeString(author);
        dest.writeString(authorId);
        dest.writeString(category);
        dest.writeTypedList(comments);
    }

    public static final Creator<Joke> CREATOR = new Creator<Joke>() {
        @Override
        public Joke createFromParcel(Parcel in) {
            return new Joke(in);
        }

        @Override
        public Joke[] newArray(int size) {
            return new Joke[size];
        }
    };

    public String getText() {
        return text;
    }

    public int getVotes() {
        return votes;
    }

    public Date getPostedDate() {
        return postedDate;
    }

    public String getAuthor() {
        return author;
    }

    public String getAuthorId() {
        return authorId;
    }

    public String getCategory() {
        return category;
    }

    public List<Comment> getComments() {
        return comments;
    }

    @Override
    public int describeContents() {
        return 0;
    }


    public void JokeVoteUp(){
        votes+=1;
    }
    public void JokeVoteDown(){
        votes-=1;
    }
}

有问题的行在 // TODO:

更新

布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".ActivityJokeDetail">

    <include
        android:id="@+id/include"
        layout="@layout/list_item_comment"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvPostedFrom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="32dp"
        android:text="@string/DEPostedFrom"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/include" />

    <TextView
        android:id="@+id/tvPostedOn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="16dp"
        android:text="@string/DEPostedOn"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvPostedFrom" />

    <TextView
        android:id="@+id/tvAuthor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="32dp"
        app:layout_constraintStart_toEndOf="@+id/tvPostedFrom"
        app:layout_constraintTop_toBottomOf="@+id/include" />

    <TextView
        android:id="@+id/tvPostDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintStart_toEndOf="@+id/tvPostedFrom"
        app:layout_constraintTop_toBottomOf="@+id/tvAuthor" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvComments"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etNewComment" />

    <EditText
        android:id="@+id/etNewComment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="32dp"
        android:ems="10"
        android:hint="@string/DEAddComment"
        android:inputType="textPersonName"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvPostDate" />

    <Button
        android:id="@+id/btSendComment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="@string/DESend"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvPostDate" />

</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

  • 奇怪!那么让我们玩捉迷藏吧,请对有问题的行进行空检查。在将字符串设置为 textview 之前检查字符串 null 并检查代码是否仍然崩溃。
  • 如果你能分享 repo url 会更好,这样我就可以在我这边运行代码来发现问题。

标签: java android nullpointerexception textview settext


【解决方案1】:

假设您将整个布局放在一个活动文件中,并假设它们确实存在于布局中。

您实际上不需要使用包含变量。

代替:

tvAuthor = include.findViewById(R.id.tvAuthor);

使用:

tvAuthor = findViewById(R.id.tvAuthor);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多