首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >回收器视图:尝试在空对象引用上调用虚拟方法

回收器视图:尝试在空对象引用上调用虚拟方法
EN

Stack Overflow用户
提问于 2022-06-09 23:15:15
回答 1查看 391关注 0票数 0

我一直在试图解决这个问题,但我对Android并不熟悉,当我尝试运行该应用程序时,它会显示以下消息:

代码语言:javascript
复制
Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference

这是我的主要活动文件,原因是:

代码语言:javascript
复制
package com.sti.lazshop;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.sti.lazshop.databinding.ActivityMainBinding;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;
    ArrayList<ItemModel> itemModels = new ArrayList<>();
    int[] itemImages = {R.drawable.item_huion, R.drawable.item_iphone};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        RecyclerView recyclerView = findViewById(R.id.mRecyclerView);
        Item_RecyclerViewAdapter adapter = new Item_RecyclerViewAdapter(this, itemModels);
        setItemModels();
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        replaceFragment(new HomeFragment());

        binding.bottomNavigationView2.setOnItemSelectedListener(item -> {

            switch (item.getItemId()) {
                case R.id.home:
                    replaceFragment(new HomeFragment());
                    break;
                case R.id.cart:
                    replaceFragment(new CartFragment());
                    break;
                case R.id.account:
                    replaceFragment(new AccountFragment());
                    break;

            }
            return true;
        });

    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout, fragment);
        fragmentTransaction.commit();

    }

    private void setItemModels() {
        String[] itemNames = getResources().getStringArray(R.array.item_full_txt);
        String[] itemPrices = getResources().getStringArray(R.array.item_prices);

        for (int i = 0; i < itemNames.length; i++) {
            itemModels.add(new ItemModel(
                    itemNames[i],
                    itemPrices[i],
                    itemImages[i]));
        }

    }

}

这里是HomeFragment.java:

代码语言:javascript
复制
package com.sti.lazshop;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

public class HomeFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    public HomeFragment() {
    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

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

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

最后,fragment_home.xml:

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".HomeFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/mRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

有一个类似的问题,但我不知道如何应用,目前无法找到解决办法。我使用底部导航器在包含fragment_home.xml回收器视图的片段之间导航。谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-09 23:57:19

正如我从fragment_home.xml中了解到的,在HomeFragment xml布局中有一个RecyclerView。但是你正在试图找到ViewMainActivity里面。MainActivity's onCreate方法中的问题。当你打电话:

代码语言:javascript
复制
RecyclerView recyclerView = findViewById(R.id.mRecyclerView);

MainActivity中,它试图在activity_main.xml(用于MainActivity的xml布局)中找到一个id:R.id.mRecyclerViewView。但据我所知,它不在那里,因为它在fragment_home.xml内部。您可以在这里阅读find View::findViewById的工作原理:

https://developer.android.com/reference/android/view/View#findViewById(int)

查找具有给定ID的第一个子代视图,如果ID与getId()匹配,则查找视图本身;如果ID无效(< 0),则查找null,或者在层次结构中没有匹配的视图。

因此,当它无法通过id找到视图时,它返回null。

然后尝试将Adapter设置为RecyclerView的变量,实际上为null。

代码语言:javascript
复制
recyclerView.setAdapter(adapter); //recyclerView is null here

这就是你出问题的原因。

你有两个选择。

在我看来,worked.

  • Another选项比
  1. RecyclerViewfragment_home.xml移动到activity_main.xml更合适,因为您已经使用了片段:

将与RecyclerView处理相关的代码移动到HomeFragment类,并在HomeFragment中调用findViewById

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72567563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档