mayra
mayra

Reputation: 71

recycler view is not shown in fragment

I changed my activity to fragment for some reason but now my recycler view is not shown I have also checked the ArrayList that I want to show on recycler view it was not empty. The same code is working in another activity and fragments but not in this fragment. Please someone help me out!! Thank you in advance

my fragment code

    public class HomeSkillsFragment extends Fragment {

    private EditText Search;
    private ImageView back;
    private RecyclerView recyclerView;
    private ArrayList<Post> postItem;
    private postAdapter adapter;
    private GridLayoutManager gridLayoutManager;
    private DatabaseReference reference;
    private BottomNavigationVisibility bottomNavigationVisibility;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home_skills, container, false);
    }


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

        bottomNavigationVisibility = new BottomNavigationVisibility(getActivity());
        bottomNavigationVisibility.hideBottomNavigation();

        //init Views
        Search = getActivity().findViewById(R.id.search_editText);
        back = getActivity().findViewById(R.id.back);
        recyclerView = getActivity().findViewById(R.id.recyclerView);
        gridLayoutManager = new GridLayoutManager(getContext(),2,GridLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(gridLayoutManager);

        //getting Data from Database
        getDataFromDB();

        //click handle, back
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomNavigationVisibility.showBottomNavigation();
                NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
                navController.navigate(R.id.navigation_home);

            }
        });
    }


    private void getDataFromDB(){

        postItem = new ArrayList<>();
        //initialize database
        reference = FirebaseDatabase.getInstance().getReference("Posts");
        reference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        for(DataSnapshot dataSnapshot: snapshot.getChildren()){
                            Post post = dataSnapshot.getValue(Post.class);
                            if(post.getCategory().equals("Skills, M" ) || post.getCategory().equals("Skills, S"))
                                postItem.add(post);
                        }

                        adapter = new postAdapter(getContext(),postItem);
                        recyclerView.setAdapter(adapter);
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        Toast.makeText(getContext(),"Something went Wrong",Toast.LENGTH_SHORT).show();

                    }
                });

    }
}

my adapter code:

 public class postAdapter extends RecyclerView.Adapter<postAdapter.PostViewHolder> {

    LayoutInflater mInflater;
    private ArrayList<Post> mPost;
    Context context;

    public postAdapter(Context context, ArrayList<Post> posts) {
        mInflater = LayoutInflater.from(context);
        this.mPost = posts;
        this.context=context;
    }

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = mInflater.inflate(R.layout.list_item,parent,false);
        return new PostViewHolder(itemView,this);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {

        //setting post title
        Post currentPost = mPost.get(position);
        holder.itemNameTextView.setText(currentPost.getPost_Title());

        //setting InExchange
        if(currentPost.getCategory().equals("Skills, M") || currentPost.getCategory().equals("Educational Accessories, M")){
            holder.inExchangeTextView.setText("Rs. " + currentPost.getIn_Exchange());
            holder.inExchangeTextView.setTextColor(context.getColor(R.color.blue));
            holder.exchangeIcon.setVisibility(View.VISIBLE);
        }
        else if(currentPost.getCategory().equals("Skills, S") || currentPost.getCategory().equals("Educational Accessories, A")){
            holder.inExchangeTextView.setText(currentPost.getIn_Exchange());
            holder.inExchangeTextView.setTextColor(context.getColor(R.color.blue));
            holder.exchangeIcon.setVisibility(View.VISIBLE);
        }
        else{
            holder.inExchangeTextView.setText(currentPost.getIn_Exchange());
            holder.inExchangeTextView.setTextColor(context.getColor(R.color.green));
            holder.exchangeIcon.setVisibility(View.INVISIBLE);
        }

        //setting image
        Picasso.get().load(currentPost.getImage_Url_1()).into(holder.image);
        holder.image.setClipToOutline(true);

        //setting institution name
        FirebaseDatabase.getInstance().getReference("Users/"+currentPost.getUid()+"/").getRef().addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    holder.institutionName.setText(snapshot.child("institution").getValue(String.class));
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(context,"Something went wrong",Toast.LENGTH_SHORT).show();

            }
        });

        //handle click of item
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("currentPost", currentPost);
                Navigation.findNavController(view).navigate(R.id.action_navigation_home_to_homeDetailFragment, bundle);
            }
        });

    }

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

    class PostViewHolder extends  RecyclerView.ViewHolder{

        TextView itemNameTextView;
        TextView inExchangeTextView ;
        TextView institutionName;
        ImageView image, exchangeIcon ;
        RecyclerView.Adapter mAdapter;

        public PostViewHolder(@NonNull View itemView, postAdapter adapter) {
            super(itemView);
            itemNameTextView = itemView.findViewById(R.id.itemName_TextView);
            inExchangeTextView = itemView.findViewById(R.id.inExchange_TextView);
            image = itemView.findViewById(R.id.imageView);
            institutionName = itemView.findViewById(R.id.institutionName);
            exchangeIcon = itemView.findViewById(R.id.exchange_icon);
            mAdapter = adapter;
        }
    }


}

my XML :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.home.HomeSkillsFragment">


    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintLayoutTop"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_130sdp"
        android:background="@drawable/top_background_rounded"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:id="@+id/back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/_10sdp"
            android:layout_marginStart="@dimen/_12sdp"
            android:foreground="?android:attr/selectableItemBackgroundBorderless"
            android:src="@drawable/arrow_back"
            android:padding="@dimen/_8sdp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <EditText
            android:id="@+id/search_editText"
            style="@style/searchView"
            android:layout_width="0dp"
            android:layout_height="@dimen/_35sdp"
            android:layout_marginStart="@dimen/_10sdp"
            android:layout_marginTop="@dimen/_8sdp"
            android:inputType="text"
            android:includeFontPadding="false"
            android:singleLine="true"
            android:layout_marginEnd="@dimen/_16sdp"
            android:layout_marginBottom="@dimen/main_start_end_margin"
            android:hint="Search"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/back"
            app:layout_constraintTop_toTopOf="parent" />



    <ImageView
        android:id="@+id/skills_imageView"
        android:layout_width="@dimen/_50sdp"
        android:layout_height="@dimen/_50sdp"
        android:background="@drawable/searchview_bg"
        android:src="@drawable/ic_skills"
        android:scaleType="centerInside"
        android:layout_marginTop="@dimen/_8sdp"
        app:layout_constraintTop_toBottomOf="@id/search_editText"
        app:layout_constraintEnd_toEndOf="@+id/constraintLayoutTop"
        app:layout_constraintStart_toStartOf="@+id/constraintLayoutTop" />
<TextView
    android:id="@+id/skills_TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/_4sdp"
    android:fontFamily="@font/poppins_regular"
    android:text="Skills"
    android:textColor="@android:color/black"
    android:textSize="@dimen/_12ssp"
    android:includeFontPadding="false"
    app:layout_constraintTop_toBottomOf="@id/skills_imageView"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

    </androidx.constraintlayout.widget.ConstraintLayout>


<TextView
    android:id="@+id/inExchange_TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="In Exchange"
    android:textSize="@dimen/_10ssp"
    android:textColor="@color/black"
    android:fontFamily="@font/poppins_medium"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@id/constraintLayoutTop"
    android:layout_marginTop="@dimen/_8sdp" />

<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/_20sdp"
    app:layout_constraintTop_toBottomOf="@id/inExchange_TextView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    android:orientation="horizontal">

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="See All"
        android:scaleX="0.9"
        android:scaleY="0.9"
        android:textStyle="bold"
        style="@style/radioButton"
        android:fontFamily="@font/poppins_medium"
        android:includeFontPadding="false"
        android:id="@+id/radioButtonAll"
        android:checked="true"
        android:textSize="@dimen/_10sdp" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Give Money"
        style="@style/radioButton"
        android:scaleX="0.9"
        android:scaleY="0.9"
        android:textStyle="bold"
        android:includeFontPadding="false"
        android:fontFamily="@font/poppins_medium"
        android:id="@+id/radioButtonMoney"
        android:checked="false"
        android:textSize="@dimen/_10sdp" />

    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:includeFontPadding="false"
        android:scaleX="0.9"
        android:scaleY="0.9"
        android:text="Teach Other Skill"
        style="@style/radioButton"
        android:textStyle="bold"
        android:fontFamily="@font/poppins_medium"
        android:id="@+id/radioButtonSkill"
        android:checked="false"
        android:textSize="@dimen/_10sdp" />
</RadioGroup>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginTop="@dimen/_10sdp"
    android:paddingLeft="@dimen/_12sdp"
    android:paddingRight="@dimen/_12sdp"
    android:paddingTop="@dimen/_8sdp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/radioGroup"
    app:layout_constraintVertical_weight="1" />

</androidx.constraintlayout.widget.ConstraintLayout>

Upvotes: 0

Views: 346

Answers (1)

Yura
Yura

Reputation: 383

In your code, you will try to get views from an activity, but not from a Fragment.

    Search = getActivity().findViewById(R.id.search_editText);
    back = getActivity().findViewById(R.id.back);
    recyclerView = getActivity().findViewById(R.id.recyclerView);

And instead of onActivityCreated use onViewCreated

Updated HomeSkillFragment.class.

public class HomeSkillsFragment extends Fragment {

    private EditText Search;
    private ImageView back;
    private RecyclerView recyclerView;
    private ArrayList<Post> postItem;
    private postAdapter adapter;
    private GridLayoutManager gridLayoutManager;
    private DatabaseReference reference;
    private BottomNavigationVisibility bottomNavigationVisibility;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home_skills, container, false);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        bottomNavigationVisibility = new BottomNavigationVisibility(getActivity());
        bottomNavigationVisibility.hideBottomNavigation();

        //init Views
        Search = view.findViewById(R.id.search_editText);
        back = view.findViewById(R.id.back);
        recyclerView = view.findViewById(R.id.recyclerView);
        gridLayoutManager = new GridLayoutManager(getContext(), 2, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(gridLayoutManager);

        //getting Data from Database
        getDataFromDB();

        //click handle, back
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomNavigationVisibility.showBottomNavigation();
                NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
                navController.navigate(R.id.navigation_home);

            }
        });
    }

    private void getDataFromDB() {

        postItem = new ArrayList<>();
        //initialize database
        reference = FirebaseDatabase.getInstance().getReference("Posts");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                    Post post = dataSnapshot.getValue(Post.class);
                    if (post.getCategory().equals("Skills, M") || post.getCategory().equals("Skills, S"))
                        postItem.add(post);
                }

                adapter = new postAdapter(getContext(), postItem);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getContext(), "Something went Wrong", Toast.LENGTH_SHORT).show();

            }
        });
    }
}

Upvotes: 2

Related Questions