java – Why won't my CardView appear in my fragment?-ThrowExceptions

Exception or error:

I am following this tutorial on how to create Swipe Views using a View Pager and am trying to convert it to work with fragments.

My issue is that the cards are not appearing when I select my fragment.

I think the issue lies in this line of code

adapter = new Adapter(models, getActivity());

(originally adapter = new Adapter(models, this); in the tutorial), but I could be wrong.

I am relatively new to android studio and this is my first time using fragments, any help would be greatly appreciated!

Here is my code:

fragment_cards.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"
    android:background="@android:color/background_light"
    >

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:foregroundGravity="center"
        android:overScrollMode="never"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"></androidx.viewpager.widget.ViewPager>

    <Button
        android:id="@+id/button_shuffle"
        android:text="SHUFFLE"
        android:textColor="#fff"
        android:background="@drawable/round"
        android:paddingLeft="30dp"
        android:paddingRight="30dp"
        android:layout_marginBottom="60dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        app:layout_constraintBottom_toBottomOf="@+id/viewPager"
        app:layout_constraintEnd_toEndOf="@+id/viewPager"
        app:layout_constraintStart_toStartOf="@+id/viewPager">

    </Button>


</androidx.constraintlayout.widget.ConstraintLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="20dp"
        android:layout_margin="8dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="300dp">

            <ImageView
                android:id="@+id/image"
                android:src="@drawable/brochure"
                android:scaleType="centerCrop"
                android:layout_width="match_parent"
                android:layout_height="200dp"/>

            <TextView
                android:id="@+id/title"
                android:textColor="#262626"
                android:layout_below="@id/image"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="16dp"
                android:text="Brochure"
                android:textSize="16sp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />

            <TextView
                android:id="@+id/desc"
                android:layout_below="@id/title"
                android:layout_marginTop="3dp"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:maxLines="3"
                android:drawablePadding="10dp"
                android:ellipsize="end"
                android:text="Description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>

        </RelativeLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>
CardsFragment.java
package com.example.musicassistant;

import android.animation.ArgbEvaluator;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class CardsFragment extends Fragment {

    ViewPager viewPager;
    Adapter adapter;
    List<Model> models;
    Integer[] colors = null;
    ArgbEvaluator argbEvaluator = new ArgbEvaluator();

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

        models = new ArrayList<>();
        models.add(new Model(R.drawable.brochure, "Brochure", "oooooo"));
        models.add(new Model(R.drawable.sticker, "Sticker", "oooooo"));
        models.add(new Model(R.drawable.poster, "Poster", "oooooo"));
        models.add(new Model(R.drawable.namecard, "Namecard", "oooooo"));

        adapter = new Adapter(models, getActivity());

        viewPager = inflater.inflate(R.layout.fragment_cards, container, false).findViewById(R.id.viewPager);
        viewPager.setAdapter(adapter);
        viewPager.setPadding(130,0,130,0);

        Integer[] colors_temp = {
                getResources().getColor(R.color.color1),
                getResources().getColor(R.color.color2),
                getResources().getColor(R.color.color3),
                getResources().getColor(R.color.color4)

        };

        colors = colors_temp;

        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (position < (adapter.getCount() -1) && position < (colors.length -1)) {
                    viewPager.setBackgroundColor(
                            (Integer) argbEvaluator.evaluate(
                                    positionOffset,
                                    colors[position],
                                    colors[position + 1]
                            )
                    );
                } else {
                    viewPager.setBackgroundColor(colors[colors.length - 1]);
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        return inflater.inflate(R.layout.fragment_cards, container, false);
    }
}
Adapter.java
package com.example.musicassistant;


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

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import java.util.List;

public class Adapter extends PagerAdapter {

    private List<Model> models;
    private LayoutInflater layoutInflater;
    private Context context;

    public Adapter(List<Model> models, Context context) {
        this.models = models;
        this.context = context;
    }

    @Override
    public int getCount() {
        return models.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view.equals(object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        layoutInflater = LayoutInflater.from(context);
        View view = layoutInflater.inflate(R.layout.item, container, false);

        ImageView imageView;
        TextView title, desc;

        imageView = view.findViewById(R.id.image);
        title = view.findViewById(R.id.title);
        desc = view.findViewById(R.id.desc);

        imageView.setImageResource(models.get(position).getImage());
        title.setText(models.get(position).getTitle());
        desc.setText(models.get(position).getDesc());

        container.addView(view, 0);
        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View)object);
    }
}
Model.java
package com.example.musicassistant;

public class Model {

    private int image;
    private String title;
    private  String desc;

    public Model(int image, String title, String desc) {
        this.image = image;
        this.title = title;
        this.desc = desc;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

It is worth noting that the fragment itself is working, as the button in it is appearing correctly.
The only issue is that my cards are not showing up at all.

Any help would be greatly appreciated as this is driving me absolutely insane!

Thank you very much for your time I greatly appreciate it,

Roman

How to solve:

Inflate will create a new layout object(view object) eveytime you use it so this is one view layout

viewPager = inflater.inflate(R.layout.fragment_cards, container, false).findViewById(R.id.viewPager);

and you are returning a new view object which has nothing

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

so you need to store a single reference of view after inflating then use it and return it, as

View root  = inflater.inflate(R.layout.fragment_cards, container, false).findViewById(R.id.viewPager);
viewPager = root.findViewById(R.id.viewPager);
// ... code
return root;

Leave a Reply

Your email address will not be published. Required fields are marked *