Hi.
How do I connect to a URL when clicking on a ListView?
Hi.
How do I connect to a URL when clicking on a ListView?
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.
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);