简体   繁体   中英

Android get selected item position from Class structure in AutoComplete

I'm trying to find Class structure position as an ArrayList from AutoComplete, for example I have this class structure:

public class Clients {

    @DatabaseField(generatedId = true)
    public int id;

    @DatabaseField
    public int client_code;

    public int getClient_code() {
        return client_code;
    }
}

And I define ArrayList from this class as:

private ArrayList<Clients> customersList = new ArrayList<Clients>();

Now I have some data into this arrayList and I want to get selected position to find which client_code is selected.

at_sender_package.setOnItemClickListener(new AdapterView.OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
        int selectedposition=position;
        Log.e("SELECTED ITEM: ", customersList.get(selectedposition).getClient_code()+"");
    }
});

Unfortunately I get this error:

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) at java.util.ArrayList.get(ArrayList.java:304)

my array list dont empty and i have 3 item into that and i dont have any problem to get selected text, i want to only get selected position not selected text

for example :

Log.e("POS: ", parent.getItemAtPosition(position) + "");

Result is: POS: Item 1)

Here your list is empty and you are trying to get data from it.

The proactive way to escape this error is to apply one check of list's length before using its elements.

like :

if(customersList.size() > 0) {
//do your stuff

}

You can read more about this error here :

http://voidexception.weebly.com/array-index-out-of-bounds-exception.html

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

means your arraylist, customersList is empty and you want to get item at position 0 which is invalid.Therefore first check customersList length as

if (customersList.size() > 0) {
    Log.e("SELECTED ITEM: ", customersList.get(selectedposition).getClient_code() + "");
} else {
    Log.e("SELECTED ITEM: ", "customersList is empty");
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM