【问题标题】:Fragment with RecycleView + CardView (FATAL EXCEPTION)带有 RecycleView + CardView 的片段(致命例外)
【发布时间】:2021-03-06 12:52:34
【问题描述】:

我是编程新手,我很难设置这个 RECYCLEVIEW。请帮我!如果你可以。我相信主要问题出在片段中。

错误 引起:java.lang.NullPointerException:尝试调用虚拟方法'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager) ' 在空对象引用上 com.example.application.Fragments.Home.HomeFragment.onCreate(HomeFragment.java:32)

@Shay kin

修复

错误 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' 在 com.example.application.Fragments.Home.HomeFragment.onCreateView(HomeFragment.java:36)

@Shay kin

修复

MainActivity

class MainActivity extends AppCompatActivity {
    private BottomNavigationView bottomNavigationView;

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

        bottomNavigationView = findViewById(R.id.bottonNavigationView);

        loadFragment(new HomeFragment());
        setBottomNavigationView();

    }

    private void loadFragment(Fragment fragment) {
        // create a FragmentManager
        FragmentManager fragmentManager = getSupportFragmentManager();
        // create a FragmentTransaction to begin the transaction and replace the Fragment
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        // replace the FrameLayout with new Fragment
        fragmentTransaction.replace(R.id.idMainFrameLayout, fragment);
        fragmentTransaction.commit(); // save the changes
        //crédits abhiandroid
    }

    @SuppressLint("NonConstantResourceId")
    public void setBottomNavigationView() {
        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {

            switch (item.getItemId()) {
                case R.id.btnSearch:
                    loadFragment(new SearchFragment());
                    break;
                case R.id.btnFeed:
                    loadFragment(new FeedFragment());
                    break;
                case R.id.btnShedule:
                    loadFragment(new SheduleFragment());
                    break;
                case R.id.btnProfile:
                    loadFragment(new ProfileFragment());
                    break;
                default:
                    loadFragment(new HomeFragment());
            }
            return true;
        });
    }
}

片段

class HomeFragment extends Fragment {

    private RecyclerView recyclerView;

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

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = container.findViewById(R.id.recycleViewHome);

        recyclerView.setAdapter(new MyAdapter(getMyList()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        return view;
    }

    private ArrayList<Store> getMyList() {

        String mTitle = "Google", mSubTitle = "Description";
        int imageView = R.drawable.ic_google_svg;

        ArrayList<Store> storeArrayList = new ArrayList<>();

        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));
        storeArrayList.add(new Store(imageView, mTitle, mSubTitle));

        return storeArrayList;
    }
}

RecycleView(ADAPTERVIEW + VIEWHOLDER)

class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {

    private ArrayList<Store> storeArrayList;

    public MyAdapter(ArrayList<Store> storeArrayList) {
        this.storeArrayList = storeArrayList;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout_stores, null, false);
        return new MyHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder myholder, int position) {

        myholder.mImageView.setImageResource(storeArrayList.get(position).getPhotoId());
        myholder.mTitle.setText(storeArrayList.get(position).getmTitle());
        myholder.mSubTitle.setText(storeArrayList.get(position).getSubTitle());
    }

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


    public class MyHolder extends RecyclerView.ViewHolder {

        private ImageView mImageView;
        private TextView mTitle, mSubTitle;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            this.mImageView = itemView.findViewById(R.id.btnImageStore);
            this.mTitle = itemView.findViewById(R.id.txtTitleStore);
            this.mSubTitle = itemView.findViewById(R.id.txtsubTitle);
        }
    }
}

界面片段

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context=".Fragments.Home.HomeFragment">

    <androidx.recyclerview.widget.RecyclerView
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        android:id="@+id/recycleViewHome"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="20dp"
        android:orientation="vertical"
        tools:listitem="@layout/card_layout_stores" />
</LinearLayout>

项目清单

<?xml version="1.0" encoding="utf-8"?>

<androidx.cardview.widget.CardView 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:id="@+id/cardViewShop"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:backgroundTint="#F4511E"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:layout_marginStart="5dp"
        android:layout_marginTop="5dp"
        android:layout_marginEnd="5dp"
        android:layout_marginBottom="5dp"
        android:orientation="horizontal"
        android:padding="10dp">

        <ImageView
            android:id="@+id/btnImageStore"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerInside"
            tools:srcCompat="@tools:sample/avatars" />

        <LinearLayout
            android:layout_width="250dp"
            android:layout_height="match_parent"
            android:layout_marginStart="10dp"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txtTitleStore"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/NameStore"
                android:textSize="14sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/txtsubTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/DescriptionStore" />

        </LinearLayout>

    </LinearLayout>
</androidx.cardview.widget.CardView>

【问题讨论】:

    标签: java android android-fragments android-recyclerview


    【解决方案1】:

    你得到这个错误是因为onCreate()方法在onCreateView()方法之前被调用,所以你尝试在初始化之前设置AdapterLayoutManager >RecyclerView,所以需要在OnCreateView()方法中添加AdapterLayoutManager。请在此处查看片段生命周期https://developer.android.com/guide/fragments/lifecycle#states

    您还创建了两个 RecyclerView 实例,一个在您的 Fragment 上,另一个在 onCreateView() 中,因此您需要将所有代码从 @ 987654326@ 到 Fragment

    中的 onCreateView()

    【讨论】:

    • 谢谢!我试试看,我也发现代码有一些错误,让我们看看。
    • 我已修复,但我仍然无法解决 LayoutManager 的下一个问题。我会多读一点,不知道为什么,我很难理解 recyclewview。
    • 在第二个问题上尝试使用recyclerView = view.findViewById(R.id.recycleViewHome);,不要使用recyclerView = container.findViewById(R.id.recycleViewHome);
    • 我爱你!!有效!是的!谢谢!
    • 对不起,我不知道这个按钮。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2015-12-17
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2013-09-13
    • 2021-03-13
    相关资源
    最近更新 更多