简体   繁体   中英

How to pass json array from recyclerView to Another activity

I want to do Show the JsonArray data in list view getting from MainActivity Recycler view by Volley which is passed to another activity. that means My MainActivity hosted with recyclerView on click recyclerView Item I got a specific array and I want pass the targeted array to another Activity and show as ListView/RecyclerView

I can't understanding how to do this: Those are my codes: MainActivity

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import android.widget.*;
import android.support.fragment.*;
import com.mycompany.myapp2.R;
import android.net.*;
import android.content.*;
import com.mycompany.myapp2.*;
import com.android.volley.toolbox.*;
import com.android.volley.*;
import org.json.*;
import com.mycompany.myapp2.adapters.*;
import android.app.*;
import com.mycompany.myapp2.Model.*;

/////
//

/*

 /**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment
{

    /* privates  */
    //"https://gogoanime.now.sh/api/v1/OngoingSeries"; //"http://jakir.me/files/user.json";
    private RecyclerView mRecyclerView;
    private ExampleAdapter mExampleAdapter;
    private ArrayList<ExampleItem> mExampleList;
    private RequestQueue mRequestQueue;
    private ProgressDialog loadingPop;
    public HomeFragment()
    {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);


    mRecyclerView = view.findViewById(R.id.recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mExampleList = new ArrayList<>();
    mRequestQueue = Volley.newRequestQueue(getActivity());

    loadingPop = new ProgressDialog(getActivity());
    loadingPop.setTitle("Loading...");
    loadingPop.setMessage("Please wait retrieving data from server");
    loadingPop.setCanceledOnTouchOutside(false);
    loadingPop.show();


    String url = "https://gogoanime.now.sh/api/v1/OngoingSeries";
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
        new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response)
        {
            try
            {



            JSONArray jsonArray = response.getJSONArray("anime");

            for (int i = 0; i < jsonArray.length(); i++)
            {
                JSONObject hit = jsonArray.getJSONObject(i);
                String title = hit.getString("title");
                String img = hit.getString("img");
                String synopsis = hit.getString("synopsis");



                /*JSONArray genresArray = hit.getJSONArray("genres");
                String[] genres = new String[genresArray.length()];
                for(int j = 0; j < genresArray.length(); j++){
                genres[j] = genresArray.getString(i);
                }*/

                        String release = hit.getString("released");
                        String status = hit.getString("status");
                        String otherName = hit.getString("otherName");
                        String totalEpisodes = hit.getString("totalEpisodes");

                JSONArray episodesArray = hit.getJSONArray("episodes");
                String[] ids = new String[episodesArray.length()];
                for(int e = 0; e < episodesArray.length(); e++){
                ids[e] = episodesArray.getJSONObject(e).getString("id");
                }

                mExampleList.add(new ExampleItem(title,img, synopsis,// genres,
                release, status, otherName, totalEpisodes));
                loadingPop.dismiss();
                Toast.makeText(getActivity(), "Data Refreshed", Toast.LENGTH_SHORT).show();
            }
            mExampleAdapter = new ExampleAdapter(getActivity(), mExampleList);
            mRecyclerView.setAdapter(mExampleAdapter);
            Toast.makeText(getActivity(), "Added Data", Toast.LENGTH_SHORT).show();
            //loadingPop.dismiss();

            }
            catch (JSONException e)
            {
            e.printStackTrace();
            Toast.makeText(getActivity(), "Catch" + e, Toast.LENGTH_LONG).show();
            loadingPop.dismiss();

            }}
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            if (error instanceof NetworkError)
            {
            }
            else if (error instanceof ServerError)
            {
            }
            else if (error instanceof AuthFailureError)
            {
            }
            else if (error instanceof ParseError)
            {
            }
            else if (error instanceof NoConnectionError)
            {
            }
            else if (error instanceof TimeoutError)
            {
            Toast.makeText(getContext(),
                       "Oops. Timeout error!",
                       Toast.LENGTH_LONG).show();
            }
        }
        }
    );
    request.setRetryPolicy(new DefaultRetryPolicy(
                   10000,
                   DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                   DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    mRequestQueue.add(request);
        //ids
    return view;
    }}

Adapter

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


import java.util.ArrayList;
import com.mycompany.myapp2.R;
import com.bumptech.glide.*;
import com.mycompany.myapp2.*;
import com.mycompany.myapp2.Model.*;
import android.content.*;


public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
    private Context mContext;
    private ArrayList<ExampleItem> mExampleList;

  public ExampleAdapter(Context context, ArrayList<ExampleItem> exampleList) {
    mContext = context;
    mExampleList = exampleList;
    }

   @Override
    public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(mContext).inflate(R.layout.example_item, parent, false);
    return new ExampleViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ExampleViewHolder holder, int position) {
    final ExampleItem currentItem = mExampleList.get(position);

    String title = currentItem.getTitle();
    String img = currentItem.getImg();
    String synopsis = currentItem.getSynopsis();
    //String[] genres = currentItem.getGenre();
    String release = currentItem.getRelease();
    String status = currentItem.getStatus();
    String otherName = currentItem.getOtherName();
    String totalEpisodes = currentItem.getTotalEpisodes();

    holder.mTitle.setText(title);
    holder.mSynopis.setText(synopsis);
    //holder.mGenre.setText(genres);
    holder.mRelease.setText(release);
    holder.mStatus.setText(status);
    holder.mOtherName.setText(otherName);
    holder.mTotalEpisodes.setText(totalEpisodes);


    Glide.with(mContext).
    load(img).
    into(holder.mImg);

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // user selected product now you can show details of that product 
            Intent intent = new Intent(view.getContext(), OnGoingDetails.class);

            String SName = currentItem.getTitle();
            String SGenre = currentItem.getSynopsis();
            String SRating = currentItem.getImg();

            intent.putExtra("Name",SName);
            intent.putExtra("Genre", SGenre);
            intent.putExtra("Rating",SRating);

            view.getContext().startActivity(intent);
        }
        });




    }

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

    public class ExampleViewHolder extends RecyclerView.ViewHolder {
    public ImageView mImg;

    public TextView mTitle ;
    public TextView mSynopis;
    public TextView mGenre ;
    public TextView mRelease ;
    public TextView mStatus ;
    public TextView mOtherName ;
    public TextView mTotalEpisodes ;

    public ExampleViewHolder(View itemView) {
        super(itemView);
        mTitle = itemView.findViewById(R.id.title);
       mImg=itemView.findViewById(R.id.thumbnail);
        mSynopis = itemView.findViewById(R.id.synopsis);
        mGenre = itemView.findViewById(R.id.genre);
        mRelease = itemView.findViewById(R.id.released);
        mStatus = itemView.findViewById(R.id.status);
        mOtherName = itemView.findViewById(R.id.otherName);
        mTotalEpisodes=itemView.findViewById(R.id.totalEpisodes);

}}}

Model Class


public class ExampleItem {
   private String mTitle;
    private String mImg;
    private String mSynopsis;
   // private String[] mGenre;
    private String mRelease;
    private String mStatus;
    private String mOtherName;
    private String mTotalEpisodes;
   // private String mIds[];
   // private String mEP;


    public ExampleItem(String title,String img,String synopsis,//String[] genres,
    String released,String status,String otherName,String totalEpisodes){


    /*public ExampleItem(String title, String img, String synopsis, String[] genres, String release, String status, String otherName, String totalEpisodes
 ,String[] ids  )*/ 
       mTitle = title;
    mImg=img;
        mSynopsis = synopsis;
      //  mGenre = genres;
    mRelease = released;
    mStatus = status;
    mOtherName = otherName;
    mTotalEpisodes = totalEpisodes;

    }

  public String getTitle() {
        return mTitle;
    }

    public String getImg() {
        return mImg;
    }

    public String getSynopsis() {
        return mSynopsis;
    }

  /*  public String[] getGenre() {
        return mGenre;

    }*/
    public String getRelease() {
        return mRelease;
    }
    public String getStatus() {
        return mStatus;

    }
    public String getOtherName() {
        return mOtherName;
    }
   public String getTotalEpisodes() {
        return mTotalEpisodes;
    }

}

Please solve my problem

you can modify your model to implement Parcelable to look like this

public class ExampleItem implements Parcelable {
private String mTitle;
private String mImg;
private String mSynopsis;
private String mRelease;
private String mStatus;
private String mOtherName;
private String mTotalEpisodes;



public ExampleItem(String title,String img,String synopsis,
                   String released,String status,String otherName,String totalEpisodes){



    mTitle = title;
    mImg=img;
    mSynopsis = synopsis;
    //  mGenre = genres;
    mRelease = released;
    mStatus = status;
    mOtherName = otherName;
    mTotalEpisodes = totalEpisodes;

}

protected ExampleItem(Parcel in) {
    mTitle = in.readString();
    mImg = in.readString();
    mSynopsis = in.readString();
    mRelease = in.readString();
    mStatus = in.readString();
    mOtherName = in.readString();
    mTotalEpisodes = in.readString();
}

public static final Creator<ExampleItem> CREATOR = new Creator<ExampleItem>() {
    @Override
    public ExampleItem createFromParcel(Parcel in) {
        return new ExampleItem(in);
    }

    @Override
    public ExampleItem[] newArray(int size) {
        return new ExampleItem[size];
    }
};

public String getTitle() {
    return mTitle;
}

public String getImg() {
    return mImg;
}

public String getSynopsis() {
    return mSynopsis;
}

/*  public String[] getGenre() {
      return mGenre;

  }*/
public String getRelease() {
    return mRelease;
}
public String getStatus() {
    return mStatus;

}
public String getOtherName() {
    return mOtherName;
}
public String getTotalEpisodes() {
    return mTotalEpisodes;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(mTitle);
    dest.writeString(mOtherName);
    dest.writeString(mImg);
    dest.writeString(mRelease);
    dest.writeString(mStatus);
    dest.writeString(mSynopsis);
    dest.writeString(mTotalEpisodes);
}}

and in your adapter do this

Intent intent = new Intent(view.getContext(), OnGoingDetails.class);
       intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) exampleItems)); 
        view.getContext().startActivity(intent);

and in your OnGoingDetails activity

 List<ExampleItem> exampleItems = getIntent().getParcelableArrayListExtra("list");

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