1

I'm getting json of news articles from a website and displaying the article titles + summaries in a listview. Below each summary, I would like to add a 'read more' button which will open the browser and visit that specific article on the website.

However, how do I manage to make each 'read more' button link to the specific news article instead of every button to the same general website? Code below:

public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

// URL to get articles JSON
private static String url = "http://www.sample.com/json";

ArrayList<HashMap<String, String>> newsList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    newsList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    new GetArticles().execute();
}

/**
 * Async task class to get json by making HTTP call
 */
private class GetArticles extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray articles = jsonObj.getJSONArray("articles");

                // looping through All Contacts
                for (int i = 0; i < articles.length(); i++) {
                    JSONObject c = articles.getJSONObject(i);

                    String title = c.getString("title");
                    String description = c.getString("description");
                    String weblink = c.getString("weblink");

                    // tmp hash map for single contact
                    HashMap<String, String> article = new HashMap<>();

                    // adding each child node to HashMap key => value
                    article.put("title", weblink);
                    article.put("description", weblink);
                    article.put("weblink", weblink);

                    // adding contact to contact list
                    newsList.add(article);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, newsList,
                R.layout.list_item, new String[]{"title",
                "description"}, new int[]{R.id.title,
                R.id.description});

        lv.setAdapter(adapter);

    }

}


/** Called when the user clicks the read more button */
public void visitWebsite(View view) {
    Uri uri = Uri.parse("http://www.sample.com");
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}
}

And list_item.xml below:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/description"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="@color/colorAccent" />

    <Button
        android:id="@+id/weblink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="read more"
        android:onClick="visitWebsite" />
</LinearLayout>

And activity_main.xml below

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="nl.ttvavanti.avanti.MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>
Steffen
  • 35
  • 5

2 Answers2

0

You can put/get different URLs as TAG by .setTag() and getTag() methods like in this answer.

public void visitWebsite(View view) {
    Uri uri = Uri.parse(view.getTag().toString);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}
Community
  • 1
  • 1
Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
0

I suggest to try using an ArrayAdapter instead of a SimpleAdapter and in the array adapter use an OnclickListener over the Button

Like in this example https://www.sitepoint.com/custom-data-layouts-with-your-own-android-arrayadapter/

David
  • 75
  • 1
  • 9