When the user selects an item from a ListView, how do you find the underlying object?

advertisements

I am learning Programming for Android. The activity has a ListView in which each item is just a TextView. This ListView is being populated by a custom adapter which iterates through an ArrayList of cRecord, and sets the appropriate text to each TextView. This class cRecord has many "fields" (members), e.g. person name, phone number... but only the person name is shown at the ListView. Now when the user clicks the ListView in order to select a person, how can we reach the source object of type cRecord corresponding to that person?


I tried to solve this by building a prototype of the requirement.

I assumed this one as your cRecord class:

public class cRecord{
    String name;
    String phoneNo;

    //GETTERS AND SETTERS IF ANY
    //METHOD IMPLEMENTATIONS IF ANY

}

You can have a getObject method in your activity which will return an object from cRecord's list which you are using to fill the ListAdapter:

public cRecord getObject(String name){
    forech(cRecord c   : listcRecord){
        if(c.name == name){
            return c;
        }
    }
    return null;
}

And finally, In the OnListItemClicked listener of your listview, you can get the clicked object like this:

ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.list_black_text,R.id.list_content, values));  //values is the list holding objects of cRecord and R.id.list_content is the textview which you are using in your list to show the name.

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.list_content);
            String text = textView.getText().toString(); //Getting the text of view being clicked.
            cRecord clickedObject = getObject(text); //Calling your getObject method here.
    Toast.makeText(this,"phoneNo of " + clickedObject.phoneNo, Toast.LENGTH_SHORT).show();
   }});

If this doesn't help, you can mention your own code so that the question would be a bit more clear.