I need to get in a toast the position and the string of a item in a ListView when is clicked. Until now it only gives me the position, but not the string. I need help getting the string of the same position
This is my code
public void mandaOnClick(View v){
try {
View parentRow = (View) v.getParent();
lista = (ListView) parentRow.getParent();
final int position = lista.getPositionForView(parentRow);
//this is not working
final String item = (String) lista.getItemAtPosition(position);
//this is not working
String string = (String) lista.get(position);
Toast.makeText(getBaseContext(),"Your " + position + string + item, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),"Nothing", Toast.LENGTH_SHORT).show();
}
}
This is how i set my adapter in my list
public class JsonTask extends AsyncTask<URL, Void, List<Animal>> {
@Override
protected List<Animal> doInBackground(URL... urls) {
List<Animal> contactos = null;
HttpURLConnection con = null;
try {
// Establecer la conexión
con = (HttpURLConnection) urls[0].openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(10000);
// Obtener el estado del recurso
int statusCode = con.getResponseCode();
if (statusCode != 200) {
contactos = new ArrayList<>();
contactos.add(new Animal(null, null, null, null));
} else {
// Parsear el flujo con formato JSON
InputStream in = new BufferedInputStream(con.getInputStream());
// JsonAnimalParser parser = new JsonAnimalParser();
GsonAnimalParser parser = new GsonAnimalParser();
contactos = parser.leerFlujoJson(in);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
con.disconnect();
}
return contactos;
}
@Override
protected void onPostExecute(final List<Animal> contactos) {
/*
Asignar los objetos de Json parseados al adaptador
*/
if (contactos != null) {
adaptador = new AdaptadorDeAnimales(getBaseContext(), contactos);
lista.setAdapter(adaptador);
} else {
Toast.makeText(
getBaseContext(),
"Error",
Toast.LENGTH_SHORT)
.show();
}
}
}
}
You're doing it wrong by trying to call onClick method from your ListView's layout declaration. You should attach a onItemClickListener to your ListView in your Activity/Fragment class.
First, implement the OnItemClickListener interface in your Activity/Fragment class. Then set the listener:
lista.setOnItemClickListener(this);
And in the onItemClick method:
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
String str = (String) adaptador.getItem(position);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.