簡體   English   中英

TextView.setText 拋出 NullPointerException 盡管給定的字符串不是 null

[英]TextView.setText throws NullPointerException despite given String not being null

當我嘗試為我的程序設置作者和日期時,TextView.setText 方法拋出 NullPointerException:自定義內容 Object

錯誤一:

E/AndroidRuntime:致命異常:主進程:com.example.jokestarapplication,PID:10886 java.lang.RuntimeException:無法啟動活動ComponentInfo {com.example.jokestarapplication/com.example.jokestarapplication.ActivityJokeDetail}:88215382869 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) 在 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) 在 android.app.Activity.performCreate(Activity.java:7136) 在 android.app.Activity.performCreate(Activity.882132469 45888: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) 在 java.lang.reflect.Method.invoke(Native Method) 在 88 168970007088.android.internal.os.os.runtimeinit $ MethodAndArgScaller.run(RuntimeInit.java8888888888888888888888888883),位於881689700088.8888888888888.MIN.INTENTER

錯誤二:

E/AndroidRuntime:致命異常:主進程:com.example.jokestarapplication,PID:11116 java.lang.RuntimeException:無法啟動活動ComponentInfo {com.example.jokestarapplication/com.example.jokestarapplication.ActivityJokeDetail}:88215828469 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) 在 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) 在 android.app.Activity.performCreate(Activity.java:7136) 在 android.app.Activity.performCreate(Activity.882132469 45888: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) 在 java.lang.reflect.Method.invoke(Native Method) 在 88 168970007088.android.internal.os.os.runtimeinit $ MethodAndArgScaller.run(RuntimeInit.java8888888888888888888888888883),位於881689700088.8888888888888.MIN.INTENTER

活動


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>

假設您在一個文件中有整個布局用於活動,並假設它們確實存在於布局中。

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

代替:

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

利用:

tvAuthor = findViewById(R.id.tvAuthor);

您不能為 TextView 字段設置 int 值,它會使應用程序崩潰。 您需要與字符串連接或使用 String.valueof

int value = 23;
 tvAuthor.setText(String.valueof(value));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM