Reputation: 157
I have a ListView that is updated from a ASyncTask, The adapter updates the list properly, however my setOnItemClickListener always has the same data in the intent.
This is the code for the loop that populates the ListView
if (JsonStr != null) {
//Get list of courses
JSONObject json = new JSONObject(JsonStr);
JSONObject Username = json.getJSONObject(InputUsername);
JSONObject Courses = Username.getJSONObject("Courses");
JSONObject CoursesItems = Courses.getJSONObject("items");
//Iterate around all courses
Iterator<String> i = CoursesItems.keys();
while (i.hasNext()) {
final String key = i.next();
JSONObject Course = (JSONObject) CoursesItems.get(key);
//Create a course entry
Map<String, String> ListEntry = new HashMap<>(2);
ListEntry.put("code", key);
if (Course.has("m_name")) {
String CourseName = (String) Course.get("m_name");
ListEntry.put("title", CourseName);
}
if (Course.has("original_source")) {
String Source = (String) Course.get("original_source");
ListEntry.put("source", Source);
}
JSONObject Units = null;
if (Course.has("Units")) {
Units = Course.getJSONObject("Units");
ListEntry.put("Units", Units.toString());
}
ListEntries.add(ListEntry);
final JSONObject finalUnits = Units;
runOnUiThread(new Runnable() {
public void run() {
SimpleAdapter adapter = new SimpleAdapter(
getApplicationContext(), //Activity
ListEntries, //List of pairs
R.layout.mymodules__list_item, //Target Parent Layout
new String[]{"title", "code", "source"}, //Key for pairs
new int[]{R.id.list_item_alert_textview,
R.id.list_item_date_textview,
R.id.list_item_source_textview}); //target items
ListView lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), CourseActivity.class);
intent.putExtra("Data", finalUnits.toString());
startActivity(intent);
}
});
}
});
}
}
Upvotes: 2
Views: 65
Reputation: 409
just replace by this code onitemclick
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?>parent, View view, int position, long id) {
String value = (new ArrayList<String>(ListEntry.values())).get(position);
Intent intent = new Intent(getApplicationContext(), CourseActivity.class);
intent.putExtra("Data", value);
startActivity(intent);
}
});
Upvotes: 0
Reputation: 1290
'finalUnits' is final value . move listener and data(List Units) to inside adapter. and set listener in bindview method.
{
Intent i = new Intent(context,CourseActivity.class);
i.putExtra("Data",list.get(position).toString());
startActivity(i);
}
Upvotes: 1