如何将数组列表从适配器传递到片段?

时间:2018-09-21 12:43:38

标签: java android android-fragments arraylist android-activity

实际上,我是通过RecyclerAdapter在ArrayList中添加对象的,我写了一个在适配器中获取arraylist的函数,我也在MainActivity中从该函数获取了arraylist,但是每当我尝试从MainActivity传递该arraylist时片段,它给出了NullPointer(Null value)。

救救我。

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);

    }
}

3 个答案:

答案 0 :(得分:4)

  

在适配器内编写一个get方法,然后从您的活动或片段中调用它。

public ArrayList<Object> getArrayList() {

return yourArrayList;

 }
  

在您的活动中,您可以像yourAdapterObject.getArrayList();

答案 1 :(得分:1)

尝试通过分发包传递它。

首先创建一个将要传递的模型类。它应该实现Serializable

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

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

然后将您的数据放入捆绑包

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

最后将该捆绑包实例放入您的片段

myFragment.setArguments(bundle);

答案 2 :(得分:1)

您可以通过为片段设置参数来将数组列表传递给片段。但是为此,数组列表包含的对象类型应扩展为Serializable。然后在片段中创建一个getInstance()方法,该方法返回片段的一个实例,无论您在打开片段的任何位置,都将调用该getInstance()方法并传递数组列表。

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

片段中getInstance()方法的示例代码片段为:

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;
    }

现在,您可以通过在片段中需要的地方调用getArguments()来获取数组列表。另外,请确保检查空参数。示例代码为:

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

现在,通过将此列表全局设置,您可以在片段中的任何位置访问它。希望有帮助。