Reputation: 49
I'm working on a Android app but I'm stuck at a really little thing.
I've created a dynamic ListView, it's pulling data from my database. But now if I click on a specific line in the ListView it should show me a toast with the ID.
But I can't seem to get that working..
Can somebody give me a hand with that?
Cheers, Patrick
This is my code
package wvv.zondag.app;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class WedstrijdenJSONParser extends ListActivity{
/** Called when the activity is first created. */
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wedstrijdenlist);
setListAdapter(new ArrayAdapter(
this,android.R.layout.simple_list_item_1,
this.populate()));
}
private ArrayList<String> populate() {
ArrayList<String> items = new ArrayList<String>();
try {
URL url = new URL
("http://www.wvvzondag2.nl/android/fillwedstrijden.php");
HttpURLConnection urlConnection =
(HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// gets the server JSON data
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String next;
while ((next = bufferedReader.readLine()) != null){
JSONArray ja = new JSONArray(next);
for (int i = 0; i < ja.length(); i++) {
String var = "";
JSONObject jo = (JSONObject) ja.get(i);
var = jo.getString("Tijd");
var = var+" - "+jo.getString("Wedstrijd");
items.add(var);
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return items;
}
}
Sorry for the late reply, thanks for the piece of code, but now it's showing the exact same thing as the list view is showing, Tijd(Time) and Wedstrijd(Match) but I would like to see the ID when I click on a listview item
My field is called ProgrammaID how can I manage to get that one showing in the toast? Maybe I need to call it first in my JSONArray ?
Cheers, Patrick
Upvotes: 1
Views: 2513
Reputation: 8486
Add this to your code
@Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Toast.makeText(getApplicationContext(),
((TextView) v).getText(), Toast.LENGTH_SHORT).show();
/*v passed in as an argument is the view in your listitem which is clicked.If you want to get access to the adapter just use this.getListAdapter().*/
}
Upvotes: 5