Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将arraylist从适配器传递到片段?_Java_Android_Android Fragments_Arraylist_Android Activity - Fatal编程技术网

Java 如何将arraylist从适配器传递到片段?

Java 如何将arraylist从适配器传递到片段?,java,android,android-fragments,arraylist,android-activity,Java,Android,Android Fragments,Arraylist,Android Activity,实际上,我是从RecyclerAdapter在ArrayList中添加对象的,我已经编写了一个函数,用于在适配器中获取ArrayList。我是从MainActivity中的该函数获取ArrayList的。但每当我试图将该ArrayList从MainActivity传递到片段时,它都会给出NullPointer(空值) 帮帮我 package com.example.codingmounrtain.addtocartbadgecount.adapter; import android.conte

实际上,我是从RecyclerAdapter在ArrayList中添加对象的,我已经编写了一个函数,用于在适配器中获取ArrayList。我是从MainActivity中的该函数获取ArrayList的。但每当我试图将该ArrayList从MainActivity传递到片段时,它都会给出NullPointer(空值)

帮帮我

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);
        }
    }
}
package com.example.codingmounrtain.addtocartbadgecount.adapter;
导入android.content.Context;
导入android.support.v7.widget.RecyclerView;
导入android.util.Log;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.Button;
导入android.widget.ImageView;
导入android.widget.TextView;
导入com.example.codingmounrtain.addtocartbadgecount.activity.MainActivity;
导入com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
导入com.example.codingmounrtain.addtocartbadgecount.R;
导入com.example.codingmounrtain.addtocartbackcount.interfaces.AddorRemoveCallbacks;
导入com.squareup.picasso.picasso;
导入java.util.ArrayList;
公共类RecyclerAdapter扩展了RecyclerView.Adapter{
ArrayList=newArrayList();
公共接口侦听器{
无效选择电影(int位置);
}
语境;
私人电影;
私人最终倾听者;
公共回收器适配器(上下文、ArrayList电影、侦听器){
this.context=上下文;
这部电影=电影;
this.listener=listener;
}
@凌驾
公共MyViewHolder onCreateViewHolder(视图组父级,int-viewType){
View-View=LayoutInflater.from(parent.getContext()).flate(R.layout.row\u布局,parent,false);
返回新的MyViewHolder(视图);
}
@凌驾
公共无效onBindViewHolder(最终MyViewHolder,最终int位置){
holder.productName.setText(movies.get(position.getTitle());
毕加索.with(context).load(movies.get(position.getPhoto()).centerCrop().resize(400400).into(holder.productImage);
holder.productImage.setImageResource(movies.get(position.getPhoto());
holder.productImage.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
listener.onSelectMovie(位置);
}
});
holder.addRemoveBt.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
如果(!movies.get(position).isAddedTocart())
{
Log.v(“tej”、“tej”);
movies.get(position).setAddedTocart(true);
对数v(“t”、“t”);
holder.addRemoveBt.setText(“删除”);
Movie=movies.get(位置);
添加(电影);
对数v(“t”、“t”);
if(MainActivity的上下文实例)
{
((AddorRemoveCallbacks)上下文);
}
}
其他的
{
movies.get(position).setAddedTocart(false);
Movie=movies.get(位置);
cartmovies.remove(电影);
holder.addRemoveBt.setText(“添加”);
((AddorRemoveCallbacks)上下文).onRemoveProduct();
}
}
});
}
公共ArrayList getArrayList(){
返回电影;
}
@凌驾
public int getItemCount(){
返回电影。大小();
}
类MyViewHolder扩展了RecyclerView.ViewHolder{
图像视图产品图像;
TextView产品名称;
按钮addRemoveBt;
公共MyViewHolder(查看项目视图){
超级(项目视图);
productImage=(ImageView)itemView.findViewById(R.id.productImageView);
productName=(TextView)itemView.findViewById(R.id.productNameTv);
addRemoveBt=(按钮)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);

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

    }
}
package com.example.codingmounrtain.addtocartbadgecount.activity;
导入android.content.Intent;
导入android.os.Bundle;
导入android.support.design.widget.CoordinatorLayout;
导入android.support.design.widget.Snackbar;
导入android.support.v4.app.Fragment;
导入android.support.v7.app.AppActivity;
导入android.support.v7.widget.GridLayoutManager;
导入android.support.v7.widget.RecyclerView;
导入android.support.v7.widget.Toolbar;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入com.example.codingmounrtain.addtocartbadgecount.Converter;
导入com.example.codingmounrtain.addtocartbadgecount.ModelClasses.Movie;
导入com.example.codingmounrtain.addtocartbadgecount.R;
导入com.example.codingmounrtain.addtocartbadgecount.adapter.RecyclerAdapter;
导入com.example.codingmounrtain.addtocartbadgecount.fragment.CartFragment;
导入com.example.codingmounrtain.addtocartbadgecount.fragment.SearchFragment;
导入com.example.codingmounrtain.addtocartbackcount.interfaces.AddorRemoveCallbacks;
导入java.util.ArrayList;
导入java.util.Iterator;
公共类MainActivity扩展AppCompatActivity实现AddorRemoveCallbacks、RecyclerAdapter.Listener{
ArrayList=newArrayList();
ArrayList电影=新建ArrayList();
回收视图mRecyclerView;
回收器适配器;
私有静态int cart_计数=0;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
getSupportActionBar().setTitle(“MovieShop”);
getSupportActionBar().show();
电影。添加(新电影(“
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);
public ArrayList<Object> getArrayList() {

return yourArrayList;

 }
 getSupportFragmentManager().beginTransaction()
                .add(containerId, YourFragment.getInstance(yourArrayList), tag)
                .commitAllowingStateLoss();
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;
    }
if (getArguments()!=null && getArguments().containsKey(Constants.YOUR_LIST) && getArguments().getParcelableArrayList(Constants.YOUR_LIST) != null){
      ArrayList<Object> yourlist = getArguments().getParcelableArrayList(Constants.YOUR_LIST);
}