Avian Driyanto
Avian Driyanto

Reputation: 93

How to to code setOnItemClickListener on Custom ListView with SimpleCursorAdapter?

I'm new in android program. I'm trying to build a list of contact phone. the contact phone is already finish, but when i'm trying to get the phoneNumber from the list to EditText using intent it always error. activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/lvContacts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

$adapter_contact_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="3dp" >

    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="@string/txtName"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/txtPhone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtName"
        android:text="@string/txtPhone"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

SampleActivity.java

public class SampleActivity extends FragmentActivity {


    private SimpleCursorAdapter adapter;
    public static final int CONTACT_LOADER_ID = 78;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupCursorAdapter();
        final ListView lvContacts = (ListView) findViewById(R.id.lvContacts);
        lvContacts.setAdapter(adapter);
        getSupportLoaderManager().initLoader(CONTACT_LOADER_ID, new Bundle(),
                contactsLoader);
        lvContacts.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                String phoneName = (String)lvContacts.getItemAtPosition(position);
                //Cursor cursor = (Cursor)lvContacts.getItemAtPosition(position);
                // Get the state's capital from this row in the database.
                //String phoneName = cursor.getString(cursor
                //      .getColumnIndexOrThrow("txtName"));
                Toast.makeText(SampleActivity.this, phoneName,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupCursorAdapter() {
        // Column data from cursor to bind views from
        String[] uiBindFrom = {
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone._ID };
        // View IDs which will have the respective column data inserted
        int[] uiBindTo = { R.id.txtName, R.id.txtPhone };
        // Create the simple cursor adapter to use for our list
        // specifying the template to inflate (item_contact),
        // Fields to bind from and to and mark the adapter as observing for
        // changes
        adapter = new SimpleCursorAdapter(this, R.layout.adapter_contact_item,
                null, uiBindFrom, uiBindTo,
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    }

    private LoaderManager.LoaderCallbacks<Cursor> contactsLoader = new LoaderManager.LoaderCallbacks<Cursor>() {
        // Create and return the actual cursor loader for the contacts data
        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            // Define the columns to retrieve
            String[] projectionFields = new String[] {
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                    ContactsContract.CommonDataKinds.Phone._ID };
            // Construct the loader
            CursorLoader cursorLoader = new CursorLoader(SampleActivity.this,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, // URI
                    projectionFields, // projection fields
                    null, // the selection criteria
                    null, // the selection args
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                            + " ASC" // the sort order
            );
            // Return the loader for use
            return cursorLoader;
        }
        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
            // The swapCursor() method assigns the new Cursor to the adapter
            adapter.swapCursor(cursor);
        }

        // This method is triggered when the loader is being reset
        // and the loader data is no longer available.
        @Override
        public void onLoaderReset(Loader<Cursor> loader) {
            // Clear the Cursor we were using with another call to the
            // swapCursor()
            adapter.swapCursor(null);
        }
    };
}

Can someone help with the code above, so i can get the value of the phoneNumber when i click the listview.

Upvotes: 0

Views: 3777

Answers (2)

max59
max59

Reputation: 606

Try this:

String phoneName = (String) parent.getItemAtPosition(position);

Upvotes: 1

duggu
duggu

Reputation: 38439

Try below code:-

    lvContacts.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            Cursor cursor = (Cursor) adapter.getItem(position);
        }
    });

it will give you adapter.getItem(position) cursor. Now you can your value from particular cursor.

For more info see below link :-

http://developer.android.com/reference/android/widget/CursorAdapter.html#getItem%28int

Upvotes: 1

Related Questions