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

pokxtpni  于 2023-05-18  发布在  Android
关注(0)|答案(3)|浏览(182)

实际上,我从RecyclerAdapter向ArrayList中添加对象,并且我已经编写了一个函数来获取adapter中的arraylist。我从MainActivity中的该函数获取arraylist。但是每当我试图将该arraylist从MainActivity传递到Fragment时,它都会给出NullPointer(Null值)。
帮帮我

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

    }
}
pu82cl6c

pu82cl6c1#

在适配器中编写一个get方法,然后从Activity或片段中调用它。

public ArrayList<Object> getArrayList() {

return yourArrayList;

 }

在你的activity中你可以得到这样的,yourAdapterObject.getArrayList();

aij0ehis

aij0ehis2#

尝试通过bundle传递。
首先创建一个模型类,它将被传递。它应该实现Serializable

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

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

然后将您的数据放到捆绑包中

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

最后把那个bundle示例放到你的片段中

myFragment.setArguments(bundle);
ncecgwcz

ncecgwcz3#

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

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()来获得你的arraylist。另外,请确保检查空参数。示例代码如下:

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

现在,通过使这个列表全局化,您可以在片段中的任何地方访问它。希望,这有帮助。

相关问题