【问题标题】:Error while using recycler view inside a fragment在片段内使用回收器视图时出错
【发布时间】:2021-12-07 06:01:57
【问题描述】:

我试图在我的仪表板片段中使用回收器视图,但是当我尝试运行应用程序并在 logcat 窗口中显示此错误时应用程序崩溃 -> 尝试调用虚拟方法 'void androidx.recyclerview.widget .RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' 在空对象引用上

这是我的片段代码

package com.example.bookhub;
import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.Arrays;
import java.util.List;

public class Dashboard_Fragment extends Fragment {

    RecyclerView Recycler;
    RecyclerView.LayoutManager layoutManager;
    Dashboard_Recycler_Adapter recyclerAdapter;
    List<String> bookList = Arrays.asList(
            "P.S. I love You",
            "The Great Gatsby",
            "Anna Karenina",
            "Madame Bovary",
            "War & Peace",
            "Middlemarch",
            "The Adventures of Huckleberry Finn",
            "Moby-Dick",
            "The Lord of the Rings");

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        Recycler = getActivity().findViewById(R.id.Recycler);

        layoutManager = new LinearLayoutManager(getActivity());

        recyclerAdapter = new Dashboard_Recycler_Adapter((Context) getActivity(),bookList);

        Recycler.setLayoutManager(layoutManager);
        Recycler.setAdapter(recyclerAdapter);

        return inflater.inflate(R.layout.fragment_dashboard, container, false);
    }
}


这是适配器的代码

package com.example.bookhub;

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 java.util.ArrayList;
import java.util.List;

public class Dashboard_Recycler_Adapter extends 
RecyclerView.Adapter<Dashboard_Recycler_Adapter.DashboardViewHolder>{

List<String> bookList;
public Dashboard_Recycler_Adapter(Context context, List<String> list)
{
    this.bookList = list;
}


@NonNull
@Override
public DashboardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_view_single_row, parent, false);
    return new DashboardViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull DashboardViewHolder holder, int position)
{
    holder.textView.setText(bookList.get(position));
}

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

public static class DashboardViewHolder extends RecyclerView.ViewHolder
{
    TextView textView;
    public DashboardViewHolder(@NonNull View itemView) {
        super(itemView);

        textView = itemView.findViewById(R.id.txtRecyclerRowItem);
    }
}

}

这是仪表板片段中回收站视图的 XML 代码

<?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=".Dashboard_Fragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        android:text="@string/dashboard_fragment"
        android:textSize="20sp" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/Recycler"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="35dp"
        android:padding="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.088"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.075" />

</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

    标签: java android xml android-fragments android-recyclerview


    【解决方案1】:

    您的布局尚未膨胀,并且您之前正在使用它。表示布局创建尚未完成,您在此之前正在使用它。在 onViewCreated() 方法中编写代码以获取布局的所有组件。

    你把你的代码放在了错误的method()中。从 onCreatview() 中删除以下代码。

    Recycler = getActivity().findViewById(R.id.Recycler);
    
    layoutManager = new LinearLayoutManager(getActivity());
    
    recyclerAdapter = new Dashboard_Recycler_Adapter((Context) 
    getActivity(),bookList);
    
    Recycler.setLayoutManager(layoutManager);
    Recycler.setAdapter(recyclerAdapter);
    

    覆盖片段中的 onViewCreated() 方法并将上面的代码复制并粘贴到其中。

    更改后,您的片段类将如下面的代码所示。

    public class Dashboard_Fragment extends Fragment {
    
    public Dashboard_Fragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup 
    container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_dashboard, 
    container, false);
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle 
    savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    
        Recycler = getActivity().findViewById(R.id.Recycler);
    
        layoutManager = new LinearLayoutManager(getActivity());
    
        recyclerAdapter = new Dashboard_Recycler_Adapter((Context) 
        getActivity(),bookList);
    
        Recycler.setLayoutManager(layoutManager);
        Recycler.setAdapter(recyclerAdapter);
    
       }
    }
    

    【讨论】:

    • 兄弟你能给我你的号码吗?我无法解决这个错误,如果我能得到你的帮助,那将是非常好的。
    • 兄弟,我不能提供不。但你可以问我任何我会回答的问题。
    • 看,我已经更新了我的答案并在您进行更改的地方添加了代码。
    • 天哪,兄弟!它奏效了,我真的很感激。
    • Bhai 实际上是缅因州 abhi android 开发 shuru kiya hai toh agar koi hoga jisse mai 怀疑 puchh paau toh 它会非常有帮助。有什么方法可以联系到你吗?任何社交媒体手柄或任何东西?您可以稍后删除该评论,以免其他人向其发送垃圾邮件。拜托了。
    【解决方案2】:

    你应该在获取它的 RecyclerView 之前对视图进行膨胀。

    import java.util.Arrays;
    import java.util.List;
    
    public class Dashboard_Fragment extends Fragment {
    
        RecyclerView recycler;
        
        Dashboard_Recycler_Adapter recyclerAdapter;
        List<String> books= Arrays.asList(
            "P.S. I love You",
            "The Great Gatsby",
            "Anna Karenina",
            "Madame Bovary",
            "War & Peace",
            "Middlemarch",
            "The Adventures of Huckleberry Finn",
            "Moby-Dick",
            "The Lord of the Rings");
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_dashboard, container, false);
        }
    
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle 
            savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
    
            recycler = view.findViewById(R.id.Recycler);
    
            recyclerAdapter = new Dashboard_Recycler_Adapter(requiredContext(), books);
    
            recycler.setLayoutManager(new LinearLayoutManager(requiredActivity()));
            recycler.setAdapter(recyclerAdapter);
        }
    }
    

    建议:您应该以驼峰式格式命名您的类(DashboardFragment、DashboardRecyclerAdapter 等)。 当您需要上下文或活动时,在片段中使用 resquiredContext 和 requiredActivity。

    【讨论】:

    • 试过了,但什么也没发生,还是一样
    • @ShresthaNand 添加你的代码到 onViewCreated() 然后它会工作。
    • 我尝试将 onCreateView 函数重命名为 onViewCreated() 并且应用程序正在运行,但回收器视图不可见,片段完全为空..
    • 已编辑。 onCreateView 方法在 onViewCreated 之前调用,它的作用是初始化视图(膨胀布局)并返回它。 onViewCreated 的作用是设置 onCreateView 返回的视图。这是设置视图的好地方。
    【解决方案3】:

    改变这一行

    RecyclerView Recycler;
    

    到这里

    RecyclerView recycler;
    

    还有这一行

    Recycler = getActivity().findViewById(R.id.Recycler);
    

    到这里

    recycler= getActivity().findViewById(R.id.Recycler);
    

    【讨论】:

    • 没有解决错误。
    • 你的 recyclerView 在哪里?在片段或活动中?
    • 如果你从片段中膨胀 recyclerView 那么你不需要包含 getActivity() 只需将其替换为 view.findViewById()
    • 为什么改变变量的大小写会有什么作用?没有意义
    • Recycler 不能用作变量名,因为它是一个类,而且他在绑定视图时通过传递活动引用犯了错误,他应该使用view.findViewById(),因为 recyclerView处于片段中,未处于活动状态。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2017-05-19
    相关资源
    最近更新 更多