android – Capture the data corresponding to the index in the database


I was able to feed my listview with data from SQLite, however, I now want to capture the data (in the database) that each row in the listview corresponds to.

For example:

Line 10 displays Code 1 and Name: Felipe
Line 13 displays Code 4 and Name: Giovana

For example, there are 2 lines in the list, the method I was able to use, returned a String with the complete line. As soon as I click on a line in the listview, I want it to return the code (Cod.4, for example) that is being shown in the String stored in the adapter. For example, I want to click on line 10 and have it inform me that the data it's displaying matches the bank's code 1 record.

As there are 2 columns being displayed, I want a way to capture them separately.

I'm feeding lisview like this:

    //coluna 1 do banco

    theList.add("Cód.: " + data.getString(0) + "      " + "Nome: " + data.getString(1));
    ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);


You must implement the onItemClickListener() method, using the position returned ( int position ) by the adapter, retrieve the String. Then use Regex to extract the number that refers to the code and do the search you want in the bank:

private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v, int position, long id) {
        // extrai com regex o codigo
        Pattern p = Pattern.compile("\s(\d+)\s");
        Matcher m = p.matcher(parent.getSelectedItem());
        boolean found = m.find();
        String cod = "";
        if (found){
            cod =; // testa se é este grupo mesmo ou 0
        }else{} // Algum tratamento de erro

        // Faça a busca no banco através de uma Asynctask<> por exemplo.



Okay, the cod variable has the registration code in the bank and you can use it to search the database.

PS. If you want to test some regex pattern, use this site , I recommend it.

Scroll to Top