Add onClick to RecyclerView to open URL of RecyclerView item

Viewed 521

I have a JSON that I'm parsing from and using it in a RecyclerView object. The JSON includes a URL to the related news story and I'm not really sure how to get the URL from the adapter and have it open the link when the item is pressed. Most of the stuff I searched up online doesn't seem to work for me so I'd really appreciate some help. Here's the relevant code and a sample of the JSON data.

JSON

    {
    "status": "ok",
    "totalResults": 65,
    "articles": [
        {
            "source": {
                "id": "the-wall-street-journal",
                "name": "The Wall Street Journal"
            },
            "author": null,
            "title": "Gyms Brace for Fewer Members As At-Home Fitness Rises During Pandemic",
            "description": "How might the coronavirus pandemic transform the fitness industry? To find out WSJ spoke with the CEO of Planet Fitness, an independent gym owner and an industry analyst to learn about what we can expect for the future of fitness.",
            "url": "https://www.wsj.com/video/gyms-brace-for-fewer-members-as-at-home-fitness-rises-during-pandemic/80E5B6D3-8297-43B6-8C3A-872038A5ADA6.html?mod=hp_lead_pos12",
            "urlToImage": "http://m.wsj.net/video/20200910/091020cultureshiftgyms1/091020cultureshiftgyms1_1280x720.jpg",
            "publishedAt": "2020-09-11T12:52:44.9999066Z",
            "content": "Inside the Tear of God: A Unique House on Crete That Filters the Sun\r\n9/7/2020For his home on Crete, Greeces largest island, George Kalykakis wanted something unique. He got a sculptural structure, n… [+117 chars]"
        },
        {
            "source": {
                "id": "cbc-news",
                "name": "CBC News"
            },
            "author": "CBC News",
            "title": "Coronavirus: What's happening in Canada and around the world on Friday | CBC News",
            "description": "A doctor who has been working with some of Calgary's most vulnerable citizens during the COVID-19 pandemic is worried homeless shelters won't have enough space to keep everyone safe once the cold weather hits.",
            "url": "http://www.cbc.ca/news/canada/world-canada-covid-19-sept-11-1.5720126",
            "urlToImage": "https://i.cbc.ca/1.5720172.1599823518!/fileImage/httpImage/image.jpg_gen/derivatives/16x9_620/covid-alta-homeless-20200903.jpg",
            "publishedAt": "2020-09-11T12:37:22.4755242Z",
            "content": "The latest:\r\n<ul><li>Calgary doctor worried lack of shelter space could hamper pandemic efforts over winter.</li><li>Quebec to ban karaoke after event linked to 80 cases of COVID-19.</li><li>UN warns… [+8319 chars]"
        }
    ]
}

NewsFragment.Java

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;

public class NewsFragment extends Fragment {

    View view;
    RecyclerView recyclerView;
    JSONArray news;
    String newsUrl;

    public NewsFragment(JSONArray data, String url) {
        news = data;
        newsUrl = url;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.view_page, container, false);
        recyclerView = view.findViewById(R.id.recyclerView2);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(false);
        RecyclerView.Adapter<CustomListAdapter.ListViewHolder> mAdapter = new CustomListAdapter(news, newsUrl);
        recyclerView.setAdapter(mAdapter);
        recyclerView.setOnClickListener((AdapterView.OnItemClickListener) (parent, view, position, id) -> {

            String url;// THIS IS WHERE I NEED TO GET THE URL FROM THE CLICKED ITEM
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        });
        return view;
    }

}

CustomListAdapter.java

import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONException;

import java.text.NumberFormat;

public class CustomListAdapter extends RecyclerView.Adapter<CustomListAdapter.ListViewHolder> {

    private JSONArray mDataset;
    private String murl;

    static class ListViewHolder extends RecyclerView.ViewHolder {

        // each data item that we need to populate
        TextView textView;
        TextView textView2;
        ImageView imageView;
        ListViewHolder(LinearLayout v) {
            super(v);
            textView = v.findViewById(R.id.name);
            textView2 = v.findViewById(R.id.cases);
            imageView = v.findViewById(R.id.image);
        }

    }

    // Provide a suitable constructor (depends on the kind of dataset)
    CustomListAdapter(JSONArray myDataset, String url) {
        mDataset = myDataset;
        murl = url;
    }

    // Create new views (invoked by the layout manager)
    @NonNull
    @Override
    public CustomListAdapter.ListViewHolder onCreateViewHolder(ViewGroup parent,
                                                               int viewType) {
        // create a new view
        LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_view, parent, false);

        // TextView v = (TextView) linearLayout.findViewById(R.id.info_text);

        return new ListViewHolder(linearLayout);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ListViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element

        String textViewString = "";
        String textView2String = "";
        String url = "";

        try {
            textViewString = mDataset.getJSONObject(position).getString("title");
            textView2String = mDataset.getJSONObject(position).getString("description");
            url = mDataset.getJSONObject(position).getString("url");
            holder.textView.setText(textViewString);
            holder.textView2.setText(textView2String);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.length();
    }

}
0 Answers
Related