Home > Software engineering >  how to get particular recycler view ltem category and pass it to new activity
how to get particular recycler view ltem category and pass it to new activity

Time:09-17

I have created a movie app the app is almost complete but there is one shortcoming where if users click one particular category they have to see all the details of that particular category. I'm new to android so I don't know how to implement this. one of them told we can use sql fetch but i have used retro fit so i dont want to change my backend from json to sql .

I have tried a similar question but did not work uploading my main activity, adapter model class and JSON file data Mainacivity.Java

package com.example.movieapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.MenuItemCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Filter;

import com.example.movieapp.adapter.BannerMoviesPagerAdapter;
import com.example.movieapp.adapter.ItemRecyclerAdapter;
import com.example.movieapp.adapter.MainRecyclerAdapter;
import com.example.movieapp.listener.OnItemClickLIstener;
import com.example.movieapp.model.AllCategory;
import com.example.movieapp.model.BannerMovies;
import com.example.movieapp.model.CategoryItemList;
import com.example.movieapp.retrofit.RetrofitClient;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity  {

    BannerMoviesPagerAdapter bannerMoviesPagerAdapter;
    TabLayout IndicatorTab,categoryTab;
    ViewPager bannerMoviesViewpager;
    List<BannerMovies> homeBannerList;
    List<BannerMovies> tvBannerList;
    List<BannerMovies> songBannerList;
    List<BannerMovies> audioBannerList;
    NestedScrollView nestedScrollView;
    AppBarLayout appBarLayout;

    MainRecyclerAdapter mainRecyclerAdapter;
    ItemRecyclerAdapter itemRecyclerAdapter;
    RecyclerView mainRecycler;
    List<AllCategory> allCategoryList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Adding this line will prevent taking screenshot in your app
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
                WindowManager.LayoutParams.FLAG_SECURE);
        IndicatorTab =findViewById(R.id.tab_indicator);
        categoryTab =findViewById(R.id.tabLayout);
        nestedScrollView =findViewById(R.id.nested_scroll);
        appBarLayout =findViewById(R.id.appbar);
        homeBannerList=new ArrayList<>();
        tvBannerList=new ArrayList<>();
        songBannerList=new ArrayList<>();
        audioBannerList=new ArrayList<>();
        getBannerData();
        getAllMoviesData(1);




        categoryTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()){
                    case 1:

                        setBannerMoviesPagerAdapter(tvBannerList);
                        getAllMoviesData(2);



                        return;
                    case 2:

                        setBannerMoviesPagerAdapter(songBannerList);
                        getAllMoviesData(3);

                        return;

                        case 3:

                            setBannerMoviesPagerAdapter(audioBannerList);
                            getAllMoviesData(4);
                          return;
                    default:

                        setBannerMoviesPagerAdapter(homeBannerList);
                        getAllMoviesData(1);


                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        //titles
        allCategoryList=new ArrayList<>();


    }

    private void setBannerMoviesPagerAdapter(List<BannerMovies> bannerMoviesList) {
        bannerMoviesViewpager = findViewById(R.id.banner_viewPager);
        bannerMoviesPagerAdapter = new BannerMoviesPagerAdapter(this, bannerMoviesList);
        bannerMoviesViewpager.setAdapter(bannerMoviesPagerAdapter);
        IndicatorTab.setupWithViewPager(bannerMoviesViewpager);


    }


public void setMainRecycler(List<AllCategory>allCategoryList){
        mainRecycler=findViewById(R.id.main_recycler);
        RecyclerView.LayoutManager layoutManager= new LinearLayoutManager(this,RecyclerView.VERTICAL,false);
mainRecycler.setLayoutManager(layoutManager);
mainRecyclerAdapter =new MainRecyclerAdapter(this,allCategoryList);
mainRecycler.setAdapter(mainRecyclerAdapter);
    }
    private void getBannerData()
    {
        CompositeDisposable compositeDisposable = new CompositeDisposable();
        compositeDisposable.add(RetrofitClient.getRetroFitClient().getAllBanners()
                                 .subscribeOn(Schedulers.io())
                                 .observeOn(AndroidSchedulers.mainThread())
                                     .subscribeWith(new DisposableObserver<List<BannerMovies>>() {
                                         @Override
                                         public void onNext(List<BannerMovies> bannerMovies) {
                                            for ( int i=0; i < bannerMovies.size(); i   )
                                            {
                                                if(bannerMovies.get(i).getBannerCategoryId().toString().equals("1"))
                                                {
                                                    homeBannerList.add(bannerMovies.get(i));

                                                } else if (bannerMovies.get(i).getBannerCategoryId().toString().equals("2"))
                                                {
                                                    tvBannerList.add(bannerMovies.get(i));

                                                }  else if (bannerMovies.get(i).getBannerCategoryId().toString().equals("3"))
                                                {
                                                    songBannerList.add(bannerMovies.get(i));

                                                } else if  (bannerMovies.get(i).getBannerCategoryId().toString().equals("4"))
                                                {
                                                    audioBannerList.add(bannerMovies.get(i));

                                                }
                                                else
                                                {
                                                    homeBannerList.add(bannerMovies.get(i));
                                                }



                                            }
                                         }

                                         @Override
                                         public void one rror(Throwable e) {
                                             Log.d("bannerData","" e);
                                         }

                                         @Override
                                         public void onComplete() {
                                             setBannerMoviesPagerAdapter(homeBannerList);
                                         }
                                     })

        );
    }

    private void getAllMoviesData(Integer categoryId)
    {
        CompositeDisposable compositeDisposable = new CompositeDisposable();
        compositeDisposable.add(RetrofitClient.getRetroFitClient().getAllCategoryMovies(categoryId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<List<AllCategory>>() {
                    @Override
                    public void onNext(List<AllCategory> allCategoryList) {
                        for ( int i=0; i < allCategoryList.size(); i   )
                        {

                        }
                        setMainRecycler(allCategoryList);



                    }

                    @Override
                    public void one rror(Throwable e) {
                        Log.d("bannerData","" e);
                    }

                    @Override
                    public void onComplete() {

                    }
                })

        );
    }



}

Itemrecycleradpater

package com.example.movieapp.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.movieapp.MovieDetails;
import com.example.movieapp.R;
import com.example.movieapp.model.CategoryItemList;

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

public class ItemRecyclerAdapter extends RecyclerView.Adapter<ItemRecyclerAdapter.ItemViewHolder> implements Filterable {
    Context context;
    private List<CategoryItemList> categoryItemList;
     private List<CategoryItemList>allCategoryListFull;

    public ItemRecyclerAdapter(Context context, List<CategoryItemList> categoryItemList) {
        this.context = context;
        this.categoryItemList = categoryItemList;
        allCategoryListFull = new ArrayList<>(categoryItemList);
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ItemViewHolder(LayoutInflater.from(context).inflate(R.layout.cardview_movies,parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, final int position) {

        Glide.with(context).load(categoryItemList.get(position).getSmallThumb()).placeholder(R.drawable.image12).into(holder.image_item);


       holder.image_item.setOnClickListener(view -> {
               Intent i = new Intent(context, MovieDetails.class);
               i.putExtra("movieId",categoryItemList.get(position).getId());
               i.putExtra("movieName",categoryItemList.get(position).getMovieName());
           i.putExtra("smallThumb",categoryItemList.get(position).getSmallThumb());
               i.putExtra("movieImageUrl",categoryItemList.get(position).getImageUrl());
               i.putExtra("movieFile",categoryItemList.get(position).getFileUrl());
           i.putExtra("MovieDesc",categoryItemList.get(position).getMovieDesc());
           i.putExtra("Language",categoryItemList.get(position).getLanguage());
           i.putExtra("Singers",categoryItemList.get(position).getSingers());
           i.putExtra("TrailerUrl",categoryItemList.get(position).getTrailerUrl());
               context.startActivity(i);

       });

    }


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


    @Override
    public Filter getFilter() {
        return filterNew;
    }

    private Filter filterNew = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<CategoryItemList> filteredList = new ArrayList<>();
            if(constraint == null || constraint.length() ==0){
                filteredList.addAll(allCategoryListFull);
            }
            else{
                String filterPattern = constraint.toString().toLowerCase().trim();
                for(CategoryItemList item: allCategoryListFull)
                {
                    if(item.getMovieName().toLowerCase().contains(filterPattern))
                    {
                        filteredList.add(item);
                    }
                }

            }

            FilterResults results  = new FilterResults();
            results.values = filteredList;
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            categoryItemList.clear();
            categoryItemList.addAll((List)results.values);
            notifyDataSetChanged();

        }
    };

    public static final class ItemViewHolder extends RecyclerView.ViewHolder
    {
        ImageView image_item;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            image_item=itemView.findViewById(R.id.image_item);
        }
    }

}

package com.example.movieapp.adapter;

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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.movieapp.R;
import com.example.movieapp.model.AllCategory;
import com.example.movieapp.model.CategoryItemList;

import java.util.List;


public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {

    Context context;
    private List<AllCategory> allCategoryList;


    public MainRecyclerAdapter(Context context, List<AllCategory> allCategoryList) {
        this.context = context;
        this.allCategoryList = allCategoryList;
    }

    @NonNull
    @Override
    public MainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MainViewHolder(LayoutInflater.from(context).inflate(R.layout.main_recycler_row_item, parent, false));

    }

    @Override
    public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {
        holder.categoryName.setText(allCategoryList.get(position).getCategoryTitle());
        setItemRecycler(holder.itemRecycler,allCategoryList.get(position).getCategoryItemList());


    }

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


    public static final class MainViewHolder extends RecyclerView.ViewHolder {

        TextView categoryName;
        RecyclerView itemRecycler;


        public MainViewHolder(@NonNull View itemView) {
            super(itemView);
            categoryName = itemView.findViewById(R.id.item_category);
            itemRecycler = itemView.findViewById(R.id.item_recycler);

        }
    }

    private void setItemRecycler(RecyclerView recyclerview, List<CategoryItemList> categoryItemList) {

        ItemRecyclerAdapter itemRecyclerAdapter = new ItemRecyclerAdapter(context,categoryItemList);
        recyclerview.setLayoutManager(new LinearLayoutManager(context,RecyclerView.HORIZONTAL,false));
        //recyclerview.setLayoutManager(new GridLayoutManager(context,3));
        recyclerview.setAdapter(itemRecyclerAdapter);

    }
}

CodePudding user response:

package com.example.movieapp.adapter;

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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.movieapp.R;
import com.example.movieapp.model.AllCategory;
import com.example.movieapp.model.CategoryItemList;

import java.util.List;


public class MainRecyclerAdapter extends RecyclerView.Adapter<MainRecyclerAdapter.MainViewHolder> {

    Context context;
    private List<AllCategory> allCategoryList;
    
    public MainRecyclerAdapter(Context context, List<AllCategory> allCategoryList) {
        this.context = context;
        this.allCategoryList = allCategoryList;
    }

    @NonNull
    @Override
    public MainViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MainViewHolder(LayoutInflater.from(context).inflate(R.layout.main_recycler_row_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MainViewHolder holder, int position) {

        // Here is your call to an individual item or object like category name
        holder.categoryName.setText(allCategoryList.get(position).getCategoryTitle());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Stuff to open new activity
                List<CategoryItemList> categoryItemList = allCategoryList.get(position).getCategoryItemList()

                Intent i = new Intent(context, MopvieList.class); //New screen
                i.putExtra("itemList", categoryItemList); //passing serializable object
                //NOTE: CategoryItemList class must implement Serializable
            }
        });

        setItemRecycler(holder.itemRecycler, allCategoryList.get(position).getCategoryItemList());
    }

    @Override
    public int getItemCount() {
        return allCategoryList.size();
    }
    
    public static final class MainViewHolder extends RecyclerView.ViewHolder {

        TextView categoryName;
        RecyclerView itemRecycler;
        
        public MainViewHolder(@NonNull View itemView) {
            super(itemView);
            categoryName = itemView.findViewById(R.id.item_category);
            itemRecycler = itemView.findViewById(R.id.item_recycler);

        }
    }

    private void setItemRecycler(RecyclerView recyclerview, List<CategoryItemList> categoryItemList) {
        ItemRecyclerAdapter itemRecyclerAdapter = new ItemRecyclerAdapter(context, categoryItemList);
        recyclerview.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));
        //recyclerview.setLayoutManager(new GridLayoutManager(context,3));
        recyclerview.setAdapter(itemRecyclerAdapter);
    }
}

CodePudding user response:

 holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            List<CategoryItemList> categoryItemList = allCategoryList.get(position).getCategoryItemList();
            Intent i = new Intent(context, MovieCat.class); //my activity for showing all category
            i.putExtra("itemList", (Serializable) categoryItemList);
            context.startActivity(i);
        }

public class AllCategory implements Serializable {}// as instructed made it serializable.

public class MovieCat extends AppCompatActivity  {
    TextView MovieCat;
    String movieNameCat;

    ArrayList<CategoryItemList> catItems;
    RecyclerView recyclerView;
    MainRecyclerAdapter mainRecyclerAdapter;

Button button;
    String cat; //for item_list intent 
    String catId;// for intent
    int categoryId;// for get all movies data
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_movie_cat);
        MovieCat = findViewById(R.id.textView2);
        movieNameCat = getIntent().getStringExtra("categoryTitle");
        cat = getIntent().getStringExtra("itemList");
        button=findViewById(R.id.view_all_btn);
        MovieCat.setText(movieNameCat);
      catId = getIntent().getStringExtra("categoryId"); getAllMoviesData(categoryId);
        getAllMoviesData(categoryId);
    }




    private void getAllMoviesData(int categoryId) {
        {
            CompositeDisposable compositeDisposable = new CompositeDisposable();
            compositeDisposable.add(RetrofitClient.getRetroFitClient().getAllCategoryMovies(categoryId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeWith(new DisposableObserver<List<AllCategory>>() {
                        @Override
                        public void onNext(List<AllCategory> itemList) {
                            for (int i = 0; i < itemList.size(); i  ) {
                                setMainRecycler(itemList);

                            }
                        }
                        @Override
                        public void one rror(Throwable e) {
                            Log.d("bannerData", ""   e);
                        }
                        @Override
                        public void onComplete() {
                        }
                    })

            );
        }
    }

    public void setMainRecycler(List<AllCategory> catItems) {
        recyclerView = findViewById(R.id.item_cycle);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        mainRecyclerAdapter = new MainRecyclerAdapter(this, catItems);
        recyclerView.setAdapter(mainRecyclerAdapter);


    }

Updated my code @KGeeks

  • Related