Reputation: 1611
I have an android ListView, inside each row there's a button. This is the code of my custom ArrayAdapter:
public class CheckInSArrayAdapter extends ArrayAdapter<JSONObject> {
CheckInFunctions checkFuns;
String check_id, watcher_id, user_id;
FragmentManager fm;
LayoutInflater inflater;
public CheckInSArrayAdapter(Context context, int textViewResourceId,
List<JSONObject> objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getViewOptimize(position, convertView, parent);
}
public View getViewOptimize(int position, View convertView, ViewGroup parent) {
..... //various findViewById()
user_id = jObj.get("user_id").toString();
check_id = jObj.getString("check_id");
viewHolder.likeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!v.isActivated()){
if (checkFuns.like(check_id, watcher_id))
v.setActivated(true);
} else {
if (checkFuns.unlike(check_id, watcher_id))
v.setActivated(false);
}
}
});
return convertView;
}
private class ViewHolder {
.... //various variables
protected Button likeBtn;
}
}
So here is the problem: when i click on the button the value inside the "check_id" variable is always the value of the first(from top to bottom) object in the listview (i assume it is the last instanced). How can i have the value of the object of the item where i am clickin the button?
Upvotes: 0
Views: 2961
Reputation: 486
You can do something like this.
public class CheckInSArrayAdapter extends ArrayAdapter<JSONObject> {
CheckInFunctions checkFuns;
//String check_id, watcher_id, user_id; NOTE THIS
FragmentManager fm;
LayoutInflater inflater;
...
public View getViewOptimize(int position, View convertView, ViewGroup parent) {
..... //various findViewById()
final String user_id = jObj.get("user_id").toString(); //NOTE THIS
final String check_id = jObj.getString("check_id"); //AND THIS
viewHolder.likeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!v.isActivated()){
if (checkFuns.like(check_id, watcher_id))
v.setActivated(true);
} else {
if (checkFuns.unlike(check_id, watcher_id))
v.setActivated(false);
}
}
});
return convertView;
}
...
}
All variables declared final are accessible from within the inner class.
Upvotes: 3