mardi 31 mars 2015

getItem(position) Android issue.

I created a custom adapter for a ListView with a CheckBox in each row. Each time I check a Checkbox, I want to trigger an action on the selected item in my ListView, but the getItem(position) always return the last item in the ListView.



Set the adapter:



public void onPostExecuteSearchRequestedCars(JSONArray array){
List<JSONObject> list = new ArrayList<>(array.length());
try {
for(int i = 0 ; i < array.length() ; i++){
JSONObject temp = array.getJSONObject(i);
list.add(temp);
}
} catch (JSONException e) {
Log.e(e.getClass().getName(),"There is no JSONObject in the JSONArray", e);
}

// Create and set the custom listView.
adapter = new CustomSpecificCar(this, list, this);
lv = (ListView) findViewById(R.id.lvCars);
lv.setAdapter(adapter);
}




Custom Adapter:



public class CustomSpecificCar extends ArrayAdapter<JSONObject>{
ListSpecificCars caller;
private JSONObject currentJson;
private CheckBox cbSelectedCar;

public CustomSpecificCar(Context ctxt, List<JSONObject> list, ListSpecificCars caller){
super(ctxt, R.layout.custom_specific_car_row, list);
this.caller = caller;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
final View customView = inflater.inflate(R.layout.custom_specific_car_row, parent, false);

// Set the reference of the layout
currentJson = getItem(position);
cbSelectedCar = (CheckBox)customView.findViewById(R.id.cbSelectedCar);
TextView tvBrand = (TextView)customView.findViewById(R.id.tvBrand);
TextView tvModel = (TextView)customView.findViewById(R.id.tvModel);
TextView tvOwnerEditable = (TextView)customView.findViewById(R.id.tvOwnerEditable);
TextView tvPriceEditable = (TextView)customView.findViewById(R.id.tvEstimatedPriceEditable);


try {
tvBrand.setText(currentJson.getString("brand"));
tvModel.setText(currentJson.getString("model"));
tvOwnerEditable.setText(currentJson.getString("owner"));
} catch (JSONException e) {
Log.e(e.getClass().getName(), "JSONException", e);
}



cbSelectedCar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
caller.updateClickedUsername(currentJson, true); // Add to the List
try {
Log.d("Has been checked ", currentJson.getString("brand"));
} catch (JSONException e) {
e.printStackTrace();
}
}

else
caller.updateClickedUsername(currentJson, false); // Delete from the List
}
});


return customView;
}
}


I suspect the error is this one: I call getView() each time a JSONObject is added to the list and set the value of this object in the global variables. (private JSONObject currentJson).


Can you put me on the right way?





Aucun commentaire:

Enregistrer un commentaire