C Hill
C Hill

Reputation: 37

Passing a specific variable from ListView to the next activity (Android)

I have a ListView that displays, for each result, name, phone number, website and address in a manner that would look like:

Name

Address

Phone Number

Website

Currently my onClickListener looks something like this:

    private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(Results.this, ResultDetail.class);
            intent.putExtra("????????", ?????????);

        }

    };

I understand that I need to be passing the variables with putExtra, but am unsure of how to fetch the specific phone number or website value for the result I am working on.

Other questions that have been asked don't seem to focus on having multiple values per result, so if anyone has any help I would be grateful!

Edit: In case this is useful information, the listViews results are gathered using a cursor which an adapter uses to populate the list.

Upvotes: 0

Views: 32

Answers (1)

Sanj
Sanj

Reputation: 850

The method

public void onItemClick(AdapterView parent, View view, int position, long id)

The last parameter is the id column value of the record in the database. Use this id to retrive the record from the database.

You intent extras is just a map of name value pairs, like a Hashmap. After populating the intent to your requirement, call startActivity, to launch the ResultDetail activity.

Intent intent = new Intent(Results.this, ResultDetail.class);
intent.putExtra("phone", phoneNumber);
startActvity(intent);

In the ResultDetail activity, the following code will retrieve the value

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    // get event to edit
    Bundle extras = getIntent().getExtras();
    String phoneNumber = extras.getString("phone");
}   

Alternatively, rather than passing phone number, address, in the intent, you can pass the id instead. Then the ResultDetail activity, can retrieve the record using the id. Thus in the future, if you decide to add a new column to the table, e.g. mobilenumber, you will only have to change the code in ResultDetail.

Upvotes: 3

Related Questions