当前位置: 首页 > 知识库问答 >
问题:

Java空对象引用的空异常[重复]

宣俊豪
2023-03-14

我在使用recycler视图启动活动时出错,因此我有3个文件java类、一个适配器和要执行的活动。

java类只是一个具有3个变量的简单对象

package com.ignaciojose.mestre.workboard.modelos;

public class Tarea {

    private String titulo;
    private String texto;
    private int prioridad;

    public int getPrioridad() {
        return prioridad;
    }

    public void setPrioridad(int prioridad) {
        this.prioridad = prioridad;
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getTexto() {
        return texto;
    }

    public void setTexto(String texto) {
        this.texto = texto;
    }

    public Tarea(String titulo, String texto) {
        this.prioridad = 5;
        this.titulo = titulo;
        this.texto = texto;
    }

    public Tarea(String titulo, String texto, int prioridad) {
        this.titulo = titulo;
        this.texto = texto;
        this.prioridad = prioridad;
    }

}

回收器视图的适配器

package com.ignaciojose.mestre.workboard.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.ignaciojose.mestre.workboard.R;
import com.ignaciojose.mestre.workboard.modelos.Tarea;

import java.util.ArrayList;

public class TareaAdapter extends RecyclerView.Adapter<TareaAdapter.TareaVH> {

    private Context context;
    private int resource;
    private ArrayList<Tarea> tareas;

    public TareaAdapter(Context context, int resource, ArrayList<Tarea> Tareas) {
        this.context = context;
        this.resource = resource;
        this.tareas = Tareas;
    }

    @NonNull
    @Override
    public TareaVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View TareaView = LayoutInflater.from(context).inflate(resource, null);
        TareaView.setLayoutParams(new RecyclerView.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
        ));
        return new TareaVH(TareaView);
    }

    @Override
    public void onBindViewHolder(@NonNull TareaVH holder, int position) {
        holder.lblNombre.setText(tareas.get(position).getTitulo());
        holder.lblTexto.setText(tareas.get(position).getTexto());
    }

    @Override
    public int getItemCount() {
        return tareas.size();
    }

    public class TareaVH extends RecyclerView.ViewHolder{
        TextView lblNombre, lblTexto;
        public TareaVH(@NonNull View itemView) {
            super(itemView);
            lblNombre = itemView.findViewById(R.id.txtTituloModel);
            lblTexto = itemView.findViewById(R.id.txtTextoModel);
        }

    }
}

以及活动

package com.ignaciojose.mestre.workboard;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.ignaciojose.mestre.workboard.adapters.TareaAdapter;
import com.ignaciojose.mestre.workboard.databinding.ActivityWorkBoardBinding;
import com.ignaciojose.mestre.workboard.modelos.Tarea;
import com.ignaciojose.mestre.workboard.ui.notificaciones;
import com.ignaciojose.mestre.workboard.ui.settings;

import java.util.ArrayList;

@SuppressWarnings("ALL")
public class WorkBoard extends AppCompatActivity {

    // El binding y el navigation
    private BottomNavigationView bottomNavigationView;
    private ActivityWorkBoardBinding binding;


    private ArrayList<Tarea> tareas;
    private TareaAdapter adapter;


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

        //Establezco el bottom navigation
        bottomNavigationView = findViewById(R.id.bottom_navigation);
        //Le digo en que ventana estoy para que lo marque visualmente en el menu
        bottomNavigationView.setSelectedItemId(R.id.Menu_MainMenu);
        //El switch para cambiar entre los diferentes botones del menu
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.Menu_Settings:
                        startActivity(new Intent(getApplicationContext(), settings.class));
                        overridePendingTransition(1,1);
                        return true;
                    case R.id.Menu_Notificacions:
                        startActivity(new Intent(getApplicationContext(), notificaciones.class));
                        overridePendingTransition(0,0);
                        return true;
                    case R.id.Menu_MainMenu:
                        return true;
                }
                return false;
            }
        });

        tareas = new ArrayList<>();
        adapter = new TareaAdapter(this, R.layout.tarea_model, tareas);

        binding.Content.recyclerTareas.setAdapter(adapter);
        binding.Content.recyclerTareas.setLayoutManager(new LinearLayoutManager(this));

        binding.btntest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tareas.add(new Tarea("hola","adios"));
                adapter.notifyItemInserted(tareas.size()-1);
            }
        });
    }
}

我得到的错误是:

2022-05-23 08:50:29.541 18766-18766/com.ignaciojose.mestre.workboard E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.ignaciojose.mestre.workboard, PID: 18766
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ignaciojose.mestre.workboard/com.ignaciojose.mestre.workboard.WorkBoard}: java.lang.NullPointerException: Attempt to read from field 'com.ignaciojose.mestre.workboard.databinding.ContentWorkboardBinding com.ignaciojose.mestre.workboard.databinding.ActivityWorkBoardBinding.Content' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.NullPointerException: Attempt to read from field 'com.ignaciojose.mestre.workboard.databinding.ContentWorkboardBinding com.ignaciojose.mestre.workboard.databinding.ActivityWorkBoardBinding.Content' on a null object reference
        at com.ignaciojose.mestre.workboard.WorkBoard.onCreate(WorkBoard.java:65)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:223) 
        at android.app.ActivityThread.main(ActivityThread.java:7656) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 

我在一个空项目上做了同样的配置,一切看起来都是正确的,

共有1个答案

白翰海
2023-03-14

是的,问题是您应该在方法setContentView中设置绑定视图,而不是布局id,并且您需要首先初始化绑定,请尝试以下操作

binding = ActivityWorkBoardBinding.inflate(getLayoutInflater())    
setContentView(binding.root)
 类似资料:
  • 因此,我试图从firebase向recyclerview显示图像,但它抛出了一个错误。错误提示E/nite competitive:[qarth _ debug:]get patch store::createDisableExceptionQarthFile方法失败。E/AndroidRuntime:致命异常:主进程:com . example . fortnite competitive,PI

  • 问题内容: 我不知道我的代码有什么问题 这是我的片段课 这是我的SessionManager.java 运行项目时出现的错误: java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ void com.example.gandi.symanlub.SessionManager.logoutUser()” 问题答案: 您收到错误消息是因为在此行您正在调用: 会

  • 我正试图从这个链接将数据从Android应用程序发送到Raspberry pi。我已经执行了其中提到的所有步骤,但当我尝试运行该应用程序时,在android studio logcat中会出现一个错误。 错误类似于:java.lang.NullPointerExcture:尝试在空对象引用上调用虚拟方法'intorg.json.JSONObject.getInt(java.lang.String)

  • 我有一个计时器在第二个活动中。我想从main activity访问它,所以我将chronometer作为public static放在第二个activity中,并将“secondactivity.chronometer”放在main activity中,但是当启动应用程序时,它在空对象引用上显示,我已经检查了xml id是否正确。有人知道怎么解决这个问题吗?

  • 我正在尝试使用Reform2调用API获取数据。当我打开应用程序时,它会立即崩溃。我尝试了很多解决方案。我使用postman,但仍然可以看到所有数据都是json格式的。有人能帮我吗?非常感谢你 这是我的日志 ApiClient公司 } aip调用接口 这里是我的家片段。

  • 问题内容: 我正在尝试制作2D切片游戏,当制作包含切片的阵列时,我得到了NullPointerException,这是一些代码。抱歉,如果格式不正确,请第一时间 公共类世界{ 然后在本课程中被称为(我相信这是问题的一部分) 公共类worldDraw { 问题答案: 创建对象数组时,将创建引用数组,但未分配引用。在尝试使用它们之前,必须先执行此操作。认为它类似于创建鸡蛋纸箱。在先将鸡蛋装满纸箱之前,