TextView.setText 抛出 NullPointerException 尽管给定的字符串不为空

TextView.setText throws NullPointerException despite given String not being null

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

错误 1:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.jokestarapplication, PID: 10886 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jokestarapplication/com.example.jokestarapplication.ActivityJokeDetail}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.jokestarapplication.ActivityJokeDetail.onCreate(ActivityJokeDetail.java:44) at android.app.Activity.performCreate(Activity.java:7136) at android.app.Activity.performCreate(Activity.java:7127) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:193)  at android.app.ActivityThread.main(ActivityThread.java:6669)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

错误 2:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.jokestarapplication, PID: 11116 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jokestarapplication/com.example.jokestarapplication.ActivityJokeDetail}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:6669) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.jokestarapplication.ActivityJokeDetail.onCreate(ActivityJokeDetail.java:45) at android.app.Activity.performCreate(Activity.java:7136) at android.app.Activity.performCreate(Activity.java:7127) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)  at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)  at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:193)  at android.app.ActivityThread.main(ActivityThread.java:6669)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

Activity


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>

假设您在一个文件中有 activity 的整个布局,并假设它们确实存在于布局中。

你真的不需要使用 include 变量。

而不是:

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

使用:

tvAuthor = findViewById(R.id.tvAuthor);