简体   繁体   中英

How to pass an arraylist to a fragment from adapter?

Actually, I am adding objects in ArrayList from a RecyclerAdapter and I have written a function for getting the arraylist in adapter.And I am getting the arraylist from that function in MainActivity.But whenever I am trying to pass that arraylist from MainActivity to a Fragment it is giving NullPointer(Null value).

Help me.

package com.example.codingmounrtain.addtocartbadgecount.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.codingmounrtain.addtocartbadgecount.activity.MainActivity;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;



public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {

    ArrayList<Movie> cartmovies = new ArrayList<>();

    public interface Listener {
        void onSelectMovie(int position);
    }


     Context context;
    private final ArrayList<Movie> movies;
    private final Listener listener;

    public RecyclerAdapter(Context context, ArrayList<Movie> movies,Listener listener) {
        this.context = context;
        this.movies = movies;
        this.listener = listener;
    }




    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
        return new MyViewHolder(view);
    }

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

        holder.productName.setText(movies.get(position).getTitle());
        Picasso.with(context).load(movies.get(position).getPhoto()).centerCrop().resize(400,400).into(holder.productImage);
        holder.productImage.setImageResource(movies.get(position).getPhoto());
        holder.productImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.onSelectMovie(position);
            }
        });

        holder.addRemoveBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if(!movies.get(position).isAddedTocart())
                {
                    Log.v("tej","tej");
                    movies.get(position).setAddedTocart(true);
                    Log.v("t","t");
                    holder.addRemoveBt.setText("Remove");
                    Movie movie = movies.get(position);
                    cartmovies.add(movie);
                    Log.v("t","t");
                    if(context instanceof MainActivity)
                    {
                        ((AddorRemoveCallbacks)context).onAddProduct();

                    }

                }
                else
                {
                    movies.get(position).setAddedTocart(false);
                    Movie movie = movies.get(position);
                    cartmovies.remove(movie);
                    holder.addRemoveBt.setText("Add");
                    ((AddorRemoveCallbacks)context).onRemoveProduct();
                }
            }
        });

    }

    public ArrayList<Movie> getArrayList(){
        return cartmovies;
    }

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

    class MyViewHolder extends RecyclerView.ViewHolder{

        ImageView productImage;
        TextView productName;
        Button addRemoveBt;

        public MyViewHolder(View itemView) {
            super(itemView);
            productImage=(ImageView) itemView.findViewById(R.id.productImageView);
            productName=(TextView) itemView.findViewById(R.id.productNameTv);
            addRemoveBt=(Button)itemView.findViewById(R.id.addButton);
        }
    }
}

MainActivity.java

package com.example.codingmounrtain.addtocartbadgecount.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;

import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.example.codingmounrtain.addtocartbadgecount.Converter;
import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
import com.example.codingmounrtain.addtocartbadgecount.fragment.CartFragment;
import com.example.codingmounrtain.addtocartbadgecount.fragment.SearchFragment;
import com.example.codingmounrtain.addtocartbadgecount.interfaces.AddorRemoveCallbacks;

import java.util.ArrayList;
import java.util.Iterator;

public class MainActivity extends AppCompatActivity implements AddorRemoveCallbacks,RecyclerAdapter.Listener{
    ArrayList<Movie> cartmovies = new ArrayList<>();
    ArrayList<Movie> movies = new ArrayList<>();
    RecyclerView mRecyclerView;
    RecyclerAdapter mAdapter;

    private static int cart_count=0;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("MovieShop");
        getSupportActionBar().show();

        movies.add(new Movie("Stree","A town is held in the grip of terror by tales of a mysterious woman who calls men by their name and then abducts them, leaving their clothes behind.","Rajkummar Rao","Shraddha Kapoor","Amar Kaushik",4.0f,R.drawable.stree));
        movies.add(new Movie("Nun","When a young nun at a cloistered abbey in Romania takes her own life, a priest with a haunted past and a novitiate on the threshold of her final vows are sent by the Vatican to investigate. ","Demián Bichir","Taissa Farmiga","Corin Hardy",2.5f,R.drawable.nun));
        movies.add(new Movie("Savita Damodar Paranjpe","The lives of a married couple are turned upside down when hard truths come to light.","Subodh Bhave","Trupti Madhukar Toradmal","Swapna Waghmare Joshi",3.5f,R.drawable.savita));
        movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));

        movies.add(new Movie("MI","Ethan Hunt and the IMF team join forces with CIA assassin August Walker to prevent a disaster of epic proportions.","Tom Cruise","Rebecca Ferguson","Christopher McQuarrie",4.0f,R.drawable.mi));
        movies.add(new Movie("Searching","After David Kim (John Cho)'s 16-year-old daughter goes missing, a local investigation is opened and a detective is assigned to the case.  ","John Cho","Debra Messing","Aneesh Chaganty",2.5f,R.drawable.searching));
        movies.add(new Movie("SURYA"," Indian Telugu-language action film written and directed by Vakkantham Vamsi in his directorial debut. ","Allu Arjun","Anu Emmanuel","Vakkantham Vamsi",3.5f,R.drawable.surya));
        movies.add(new Movie("TC GN"," A recently retired professional is cheated of a large sum of money through a digital fraud. ","Sachin Khedekar","Iravati Harshe","Girish Jayant Joshi",3.0f,R.drawable.tcgn));


        mRecyclerView = findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
        GridLayoutManager mLayoutManager = new GridLayoutManager(this,2);
        mRecyclerView.setLayoutManager(mLayoutManager);

        // specify an adapter (see also next example)
        mAdapter = new RecyclerAdapter(this, movies,this);
        mRecyclerView.setAdapter(mAdapter);
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem menuItem = menu.findItem(R.id.cart_action);
        menuItem.setIcon(Converter.convertLayoutToImage(MainActivity.this,cart_count,R.drawable.ic_shopping_cart_white_24dp));

        MenuItem menuItem2 = menu.findItem(R.id.search_action);
        menuItem2.setIcon(R.drawable.ic_search_black_24dp);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        cartmovies = mAdapter.getArrayList();

        Movie movie = null;
        Iterator<Movie> iter = cartmovies.iterator();
        while ( iter .hasNext() == true )
        {
            movie = iter.next();
            Log.v("tejjjj",movie.getTitle());
        }

//        cartmovies.get(0).getTitle();

        if(id==R.id.cart_action){

            Bundle bundle = new Bundle();
            bundle.putSerializable("catmovies",cartmovies);
            Fragment fragment = new CartFragment();
            fragment.setArguments(bundle);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.contentLayout, fragment)
                    .addToBackStack("MainActivity")
                    .commit();



        }
        if(id==R.id.search_action){
            Bundle bundle = new Bundle();
            //   bundle.putString("query", editSearch.getText().toString());

            bundle.putSerializable("movies",movies);
            Fragment fragment = new SearchFragment();
            fragment.setArguments(bundle);
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.contentLayout, fragment)
                    .addToBackStack("MainActivity")
                    .commit();


            //  search(searchStr, movies);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onAddProduct() {
        cart_count++;
        Log.v("stej",""+cart_count);

        invalidateOptionsMenu();
        Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie added to cart !!", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();


    }

    @Override
    public void onRemoveProduct() {
        cart_count--;
        Log.v("tej",""+cart_count);
        invalidateOptionsMenu();
        Snackbar.make((CoordinatorLayout)findViewById(R.id.parentlayout), "Movie removed from cart !!", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

    }


    @Override
    public void onSelectMovie(int position) {
        Movie movie = movies.get(position);
        // Toast.makeText(this, "selected movie: " + movie.getTitle(), Toast.LENGTH_SHORT).show();

        Intent intent = new Intent(this, DetailActivity.class);
        intent.putExtra("title",movie.getTitle());
        intent.putExtra("director",movie.getDirector());
        intent.putExtra("actors",movie.getActors());
        intent.putExtra("actresses",movie.getActresses());
        intent.putExtra("info",movie.getDescription());
        intent.putExtra("photo",movie.getPhoto());
        intent.putExtra("rating",movie.getRating());
        startActivity(intent);

    }
}

CartFragment.java

    package com.example.codingmounrtain.addtocartbadgecount.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
import com.example.codingmounrtain.addtocartbadgecount.R;
import com.example.codingmounrtain.addtocartbadgecount.activity.DetailActivity;
import com.example.codingmounrtain.addtocartbadgecount.adapter.MovieListAdapter;
import com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;

import java.util.ArrayList;
import java.util.Iterator;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


public class CartFragment extends Fragment implements View.OnClickListener, MovieListAdapter.Listener {



    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    Unbinder unbinder;
    MovieListAdapter adapter;
    RecyclerAdapter madapter;
    ArrayList<Movie> movies = new ArrayList<>();
    ArrayList<Movie> movies1 = new ArrayList<>();
    public CartFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.fragment_cart, null);
        unbinder = ButterKnife.bind(this, layout);

        adapter = new MovieListAdapter(getActivity(),movies,this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Movie Cart");


        //       movies1 =(ArrayList<Movie>) savedInstanceState.getParcelable("movies");
     //   buttonSearch.setOnClickListener(this);

        return layout;
    }
    @Override
    public void onResume() {
        super.onResume();
        getList();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    void getList(){

        Bundle bundle = getArguments();
        movies1 =(ArrayList<Movie>)   bundle.getSerializable("cartmovies");
        Iterator<Movie> iter = movies1.iterator();
        Movie movie = null;
        while(iter.hasNext() == true){
            movie = iter.next();
            movies.add(movie);
            adapter.notifyDataSetChanged();
        }
    }
    @Override
    public void onClick(View view) {


    }

    @Override
    public void onSelectMovie(int position) {
        Movie movie = movies.get(position);
        Intent intent = new Intent(getActivity(),DetailActivity.class);
        intent.putExtra("title",movie.getTitle());
        intent.putExtra("director",movie.getDirector());
        intent.putExtra("actors",movie.getActors());
        intent.putExtra("actresses",movie.getActresses());
        intent.putExtra("info",movie.getDescription());
        intent.putExtra("photo",movie.getPhoto());
        intent.putExtra("rating",movie.getRating());
        startActivity(intent);

    }
}

Write a get method inside your adapter then call it from your activity or fragment.

public ArrayList<Object> getArrayList() {

return yourArrayList;

 }

Inside your activity you can get this like, yourAdapterObject.getArrayList();

Try to pass it via bundle.

First create a model class which will be passed. It should implement Serializable

public class MyModel implements Serializable {
  private ArrayList<Data> datas;

  public MyModel(ArrayList<Data> datas) {
    this.datas = datas
  }
}

Then put your data to the bundle

Bundle bundle = new Bundle();
bundle.putSerializable();

Finally put that bundle instance to your fragment

myFragment.setArguments(bundle);

You can pass your array list to fragment by setting arguments for that fragment. But for that, the type of object your array list contains should extend Serializable. Then make a getInstance() method in your fragment that returns an instance of your fragment and wherever you are opening your fragment call that getInstance() method and pass your Array list.

 getSupportFragmentManager().beginTransaction()
                .add(containerId, YourFragment.getInstance(yourArrayList), tag)
                .commitAllowingStateLoss();

The sample code snippet for getInstance() method in your fragment is:

public static YourFragment getInstance( ArrayList<Object> yourArrayList) {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(Constants.YOUR_LIST,yourArrayList);
        YourFragment yourFragment = new YourFragment();
        yourFragment.setArguments(bundle);
        return yourFragment;
    }

Now, you can get your arraylist by calling getArguments() wherever need in your fragment. Also, make sure to check for null Arguments. The sample code for this is:

if (getArguments()!=null && getArguments().containsKey(Constants.YOUR_LIST) && getArguments().getParcelableArrayList(Constants.YOUR_LIST) != null){
      ArrayList<Object> yourlist = getArguments().getParcelableArrayList(Constants.YOUR_LIST);
}

Now, by making this list global you can access it anywhere in the fragment. Hope, it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM