android – How can I click on a ListView item and open an Activity referring to the item I clicked on?

Question:

I have a listView that has as content a list with countries name recorded in the database (SQLite). I needed to click on Item Brazil, for example, and open another ListView with the states of Brazil, I've already done it without a database, but with a database I'm not getting it because I need to pull it from the database and not the object, does anyone have any idea how to do it ?

Answer:

There are numerous ways to achieve this goal. I will suggest an approach that I find efficient.

The ideal would be to implement your own version of ** SimpleCursorAdapter**, register a callback responsible for performing the desired action and pass on to this callback some data referring to your registration, preferably an ID.

In your callback you execute the operation using the received reference, in this case opening a new activity. Receive the reference in the activity and make a new query to the DB with the reference.

1 – Tutorial to implement SimpleCursorAdapter

2 – Implement an interface in your adapter to pass the info to your callback

public interface MyListener {
    void setOnClickAdapter(final View view, final int myId );
}

3 – Register your listener in the bindView method of your adapter

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
   //....
   MyListener listener = (TaskListener)context;
   listener.setOnClickAdapter( myTextView, id );

4 – In your activity used as context, implement the adapter interface

@Override
public void setOnClickAdapter( final View view, final int id)
{
   view.setOnClickListener( new View.OnClickListener )
        @Override
        public void onClick(View view) {
            // Execute sua operação
        }
}
Scroll to Top