Capture the index data in the database

Asked

Viewed 68 times

5

I was able to feed my listview with Sqlite data, however, I now want to capture the data (in the database) that each line of listview matches.

For example:

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

For example, there are 2 lines of the list, the method I was able to use, returned me 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 saved String in the Adapter. For example, I want to click on line 10 and have it inform me that the data it is displaying corresponds to the database’s code 1 record.

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

I’m feeding the lisview like this:

while(data.moveToNext()){
    //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);
    listView.setAdapter(listAdapter);
}
  • Felipe, it’s bad to understand what you want to do. Can [Dit] the question and try to be a little more specific? In fact, try to give a descriptive title to your publication.

  • Yeah, I’ll do that.

  • To be honest, now I understand what you want to do. I think you just need to change the title and show how you’re doing to capture the data when you click, what value you return and what value you need.

  • Instead of an Arrayadapter use a Cursoradapter.

  • Guys, I saw in another place that I am feeding my listview with String instead of objects, I will change here

1 answer

1

You must implement the method onItemClickListener(), using the returned position (int position) by Adapter, retrieve the String. Then use Regex to extract the number referring 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 = m.group(1); // 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.

    }
};

listView.setOnItemClickListener(mMessageClickedHandler);

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

PS. If you want to test some pattern regex, use this website, i recommend.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.