deepthi
deepthi

Reputation: 8487

How do I connect to a URL when clicking on an Android ListView?

How do I connect to a URL when clicking on a ListView?

Upvotes: 0

Views: 5743

Answers (3)

Duc Tran
Duc Tran

Reputation: 6304

You need to set a function setOnItemClickListener() and inside it declare something like this:

Uri uri = Uri.parse( "http://www.google.com" );
startActivity( new Intent( Intent.ACTION_VIEW, uri ) );

Upvotes: 0

David Webb
David Webb

Reputation: 193764

I guess there are two questions here:

1. How do I respond to a click in a ListView?

If you're using a ListActivity override onListItemClick(). Use the position argument to see what was clicked.

For a plain ListView you'll need to call setOnItemClickListener() and pass in your own listener.

2. How do I view a URL?

The easiest way to launch a URL is to use the Built in Browser. You do this via an Intent:

Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://www.stackoverflow.com"));
startActivity(i);

Upvotes: 5

David Hedlund
David Hedlund

Reputation: 129812

You'd need to wrap some of this in try/catch blocks as at least new URL() throws an exception upon malformed URI.

listView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> adapter, View view, int which, long id) {
        String sUrl = "myUrl";
        URL url = new URL(sUrl);

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.forName("ISO-8859-1")));

        String res = "";

        String line;
        while ((line = rd.readLine()) != null) {
            res += line;
        }

        rd.close();
    }
});

EDIT If what you want to do is simply to view a website in the application, then Dave Webb's suggestion is the way to go.

Upvotes: 2

Related Questions