Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass value from recyclerview item to another activity

I'm trying to pass the value in recyclerview item to another activity when we click the recyclerview item. Here I use the OnItemTouchListener.

I retrieve data from JSON and parse it into ArrayList. I save 5 parameters. Title, ID, Rating, ReleaseDate, urlPoster, but right now i only show 2 parameters, Title, and image from urlposter.

I want to pass the other parameters to another activity, but i can't find out how to do that.

There's another question similar like this (Values from RecyclerView item to other Activity), but he uses OnClick, not OnItemTouch, and he do that in the ViewHolder. I read somewhere in the internet that it's not the right thing to do.

Here's my code

public class Tab1 extends Fragment {

    private static final String ARG_PAGE = "arg_page";
    private static final String STATE_MOVIES = "state movies";
    private TextView txtResponse;
    private String passID;

    // Progress dialog
    private ProgressDialog pDialog;


    //private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";
    private String urlJsonArry = "http://api.themoviedb.org/3/movie/popular?api_key=someapikeyhere";
    private String urlJsonImg = "http://image.tmdb.org/t/p/w342";

    // temporary string to show the parsed response
    private String jsonResponse = "";

    RecyclerView mRecyclerView;
    RecyclerView.LayoutManager mLayoutManager;
    RecyclerView.Adapter mAdapter;

    private ArrayList<Movies> movies = new ArrayList<Movies>();


    public Tab1() {
        // Required empty public constructor
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList(STATE_MOVIES, movies);
    }

    public static Tab1 newInstance(int pageNumber){

        Tab1 myFragment = new Tab1();
        Bundle arguments = new Bundle();
        arguments.putInt(ARG_PAGE, pageNumber);
        myFragment.setArguments(arguments);
        return myFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
    }


    /**
     * Method to make json object request where json response starts wtih {
     * */
    private void makeJsonObjectRequest() {

        showpDialog();

        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlJsonArry, new Response.Listener<JSONObject>() {


            @Override
            public void onResponse(JSONObject response) {
                //Log.d(TAG, response.toString());

                try {

                    JSONArray result = response.getJSONArray("results");

                    //Iterate the jsonArray and print the info of JSONObjects
                    for(int i=0; i < result.length(); i++){
                        JSONObject jsonObject = result.getJSONObject(i);

                        String id = jsonObject.getString("id");
                        String originalTitle = jsonObject.getString("original_title");
                        String releaseDate = jsonObject.getString("release_date");
                        String rating = jsonObject.getString("vote_average");
                        String urlThumbnail = urlJsonImg + jsonObject.getString("poster_path");

                        //jsonResponse = "";
                        jsonResponse += "ID: " + id + "\n\n";
                        jsonResponse += "Title: " + originalTitle + "\n\n";
                        jsonResponse += "Release Date: " + releaseDate + "\n\n";
                        jsonResponse += "Rating: " + rating + "\n\n";
                }
                    //Toast.makeText(getActivity(),"Response = "+jsonResponse,Toast.LENGTH_LONG).show();
                    parseResult(response);

                }catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(),"Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
                hidepDialog();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                //VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getActivity(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();
                // hide the progress dialog
                hidepDialog();
            }
        });

        // Adding request to request queue
        VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
    }


    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //txtResponse = (TextView) getActivity().findViewById(R.id.txtResponse);
        //makeJsonArrayRequest();

        // Calling the RecyclerView
        mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view_movie);
        mRecyclerView.setHasFixedSize(true);

        // The number of Columns
        mLayoutManager = new GridLayoutManager(getActivity(),2);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new MovieAdapter(getActivity(),movies);
        mRecyclerView.setAdapter(mAdapter);

        mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
            @Override
            public void onMovieClick(View view, int position) {
                Toast.makeText(getActivity(), "Kepencet " + position, Toast.LENGTH_SHORT).show();

                **//what to do here?**
            }

            @Override
            public void onMovieLongClick(View view, int position) {
                Toast.makeText(getActivity(),"Kepencet Lama "+position,Toast.LENGTH_LONG).show();
            }
        }));

        makeJsonObjectRequest();

        if (savedInstanceState!=null){
            movies=savedInstanceState.getParcelableArrayList(STATE_MOVIES);
            mAdapter.notifyDataSetChanged();
        }
    }



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


        return view;
    }

    private void parseResult(JSONObject response) {
        try {
            JSONArray arrayMovies = response.getJSONArray("results");


            if (movies == null) {
                movies = new ArrayList<Movies>();
            }



            for (int i = 0; i < arrayMovies.length(); i++) {

                JSONObject currentMovies = arrayMovies.getJSONObject(i);

                Movies item = new Movies();
                item.setTitle(currentMovies.optString("original_title"));
                item.setRating(currentMovies.optString("vote_average"));
                item.setReleaseDate(currentMovies.optString("release_date"));
                item.setId(currentMovies.optString("id"));
                item.setUrlThumbnail(urlJsonImg+currentMovies.optString("poster_path"));
                movies.add(item);
                mAdapter.notifyDataSetChanged();

                //Toast.makeText(getActivity(),"Movie : "+movies,Toast.LENGTH_LONG).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
        private GestureDetector mGestureDetector;
        private ClickListener mClickListener;


        public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
            this.mClickListener = clickListener;
            mGestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(),e.getY());
                    if (child!=null && clickListener!=null){
                        clickListener.onMovieLongClick(child,recyclerView.getChildAdapterPosition(child));
                    }
                    super.onLongPress(e);
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child!=null && mClickListener!=null && mGestureDetector.onTouchEvent(e)){
                mClickListener.onMovieClick(child,rv.getChildAdapterPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    }

    public static interface ClickListener{
        public void onMovieClick(View view, int position);
        public void onMovieLongClick(View view, int position);
    }

}

any help would be appreciated. Thanks!

like image 577
C.Wijaya Avatar asked Feb 10 '23 05:02

C.Wijaya


2 Answers

You need to add those other two values to a bundle in the intent. So something like this:

Intent intent = new Intent(getActivity(), YourNextActivity.class);
intent.putExtra("movie_id_key", movies.get(position).getId); //you can name the keys whatever you like
intent.putExtra("movie_rating_key", movies.get(position).getRating); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.)
intent.putExtra("movie_release_date_key", movies.get(position).getReleaseDate);
startActivity(intent)

And in your new activity just do this to retrieve:

 String id = getIntent().getExtras().getString("movie_id_key");
like image 142
Sree Avatar answered Feb 11 '23 19:02

Sree


Add them as extras in the intent with which you start the activity:

Intent intent = new Intent(currentActivity, targetActivity);
// Sree was right in his answer, it's putExtra, not putStringExtra. =(
intent.putExtra("title", title); 
// repeat for ID, Rating, ReleaseDate, urlPoster
startActivity(intent);

then pull them out in the onCreate of the other activity with

Intent startingIntent = getIntent();
String title = startingIntent.getStringExtra("title"); // or whatever.

In response to the comment below: I'm not 100% sure how you implemented it, but it looks like you have onclick handlers that pass a position and a view reference, right? Adapt it as you like, but basically...:

public void onClick(View v, int position){
    Movie m = movies.get(position);
    Intent intent = new Intent(v.getContext(), AnotherActivity.class);
    intent.putExtra("my_movie_foo_key", m.getFoo());
    intent.putExtra("my_movie_bar_key", m.getBar());
    // etc.
    v.getContext().startActivity(intent);
}

As long as you have a valid context reference (and they couldn't click on a view without a valid context), you can start an activity from wherever you like.

like image 31
MrPlow Avatar answered Feb 11 '23 17:02

MrPlow