java - 如何将数组列表从适配器传递到 fragment ?

标签 java android android-fragments arraylist android-activity

实际上,我正在从 RecyclerAdapter 向 ArrayList 添加对象,并且我编写了一个用于在适配器中获取数组列表的函数。并且我从 MainActivity 中的该函数获取数组列表。但是每当我尝试从 MainActivity 传递该数组列表时对于 Fragment,它给出 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);

    }
}

最佳答案

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

关于java - 如何将数组列表从适配器传递到 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52444083/

相关文章:

java - gridview 中的图像在滚动时改变其位置

java - "java.exe"退出代码 2 Xamarin.Android 项目

android - 向内置相机应用程序发送命令

java - 如何在片段中使用 findViewById?

android - 抽屉导航在单击菜单项时不会切换 fragment

java - 组合与继承

java - 如何创建从特定位置开始迭代的迭代器方法

java - ClassCastException,为什么我的保存按钮在单击时没有将选中的复选框保存到我的数据库中?

android - fragment 中的 setContentView

java - 使用凯撒密码进行加密