簡體   English   中英

帶有 RecycleView + CardView 的片段(致命例外)

[英]Fragment with RecycleView + CardView (FATAL EXCEPTION)

我是編程新手,我很難設置這個 RECYCLEVIEW。 請幫我。 如果可以的話,主要問題出在片段中。 我相信。

ERROR Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager) ' on a null object reference at com.example.application. Fragments.Home.HomeFragment.onCreate(HomeFragment.java:32)

@Shay kin修復

ERROR Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference at com.example.application. Fragments.Home.HomeFragment.onCreateView(HomeFragment.java:36)

@Shay kin修復

主要活動

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>

你得到這個錯誤是因為在onCreate()方法之前調用了onCreateView()方法,所以你嘗試在初始化RecyclerView之前設置AdapterLayoutManager ,所以你需要在OnCreateView()方法中添加AdapterLayoutManager 請在此處查看片段生命周期https://developer.android.com/guide/fragments/lifecycle#states

而且您還創建了兩個RecyclerView實例,一個在Fragment上,另一個在onCreateView()中,因此您需要將所有代碼從onCreate()移動到Fragment中的onCreateView()

暫無
暫無

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

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