简体   繁体   中英

How do I click on the listview item and get the phone number?

Can't get the information of the list item after I press on the list item

I've looked at many overflow questions so far, and I don't know if I have my listview set up right, but I don't want to mess up how I was able to get the contacts

public class ViewContacts extends AppCompatActivity {

    private ListView lv;
    private Cursor cursor1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_contacts);

        cursor1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        startManagingCursor(cursor1);
        String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};

        int[] to = {android.R.id.text1, android.R.id.text2};
        final SimpleCursorAdapter listAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor1, from, to);

        ListView lv = findViewById(R.id.list);
        lv.setAdapter(listAdapter);
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AlertDialog.Builder option = new AlertDialog.Builder(ViewContacts.this);

                option.setMessage(the phone number);
                option.show();
                }
        });

    }
}

press on list item, then have a pop up that displays the phone number

If you want the phone number of the contact item that you tapped on, you need to use position to move your cursor to the corresponding row , then get the item from the desired column.

Simplified example below that you put inside your onItemClick :

cursor1.moveToPosition(position);
String phoneNumber = cursor1.getString(cursor1.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));

You can replace ContactsContract.CommonDataKinds.Phone.NUMBER with any valid column name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM