nexgen sam
nexgen sam

Reputation: 35

Get data of a selected row in listview

I have created an application in which the listview gets populated from the database.Now i want to see in a toast the details of the value of a row which is clicked. How can I get the data of the clicked row??

Below is my .java page..

public class ListviewActivity extends ListActivity{

ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listlayout);
    mListView=(ListView)findViewById(R.id.list);

     DbAdapter dbHelper = new DbAdapter(this);
        dbHelper.open();

        // Get a Cursor for the list items
        Cursor listCursor = dbHelper.fetchListItems();
        startManagingCursor(listCursor);

        // set the custom list adapter
        setListAdapter(new MyListAdapter(this, listCursor));

        mListView = getListView();
        mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position,long id){
                String val=(String)(mListView.getItemAtPosition(position));

                Toast.makeText(ListviewActivity.this,position, Toast.LENGTH_SHORT).show();

            }
        });


}

When i click on a row the application gets forcibly closed with the following errors:

E/AndroidRuntime(13011): FATAL EXCEPTION: main
E/AndroidRuntime(13011): java.lang.ClassCastException: android.database.sqlite.SQLiteCursor
E/AndroidRuntime(13011):    at com.android.pickuplistview.ListviewActivity$1.onItemClick(ListviewActivity.java:38)
E/AndroidRuntime(13011):    at android.widget.AdapterView.performItemClick(AdapterView.java:284)
E/AndroidRuntime(13011):    at android.widget.ListView.performItemClick(ListView.java:3382)
E/AndroidRuntime(13011):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:1696)
E/AndroidRuntime(13011):    at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime(13011):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(13011):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(13011):    at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime(13011):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(13011):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(13011):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime(13011):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime(13011):    at dalvik.system.NativeStart.main(Native Method)

My DB Adapter page is given here:

public class DbAdapter {
 private static final String DB_NAME = "ListData";
    private static final String TABLE_ITEMS = "itemslist";
    public static final String COL_ID = "_id";
    public static final String COL_ITEMS = "items";
    public static final String COL_NAME = "name";
    public static final String COL_ADDRESS = "address";
    public static final String COL_STATUS="status";

    private static final int DB_VERSION = 1;

    private final Context mCtx;
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String CREATE_DB_TABLE_DATES = 

        "CREATE TABLE "+TABLE_ITEMS+" ("+ 
            COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, "+ 
            COL_ITEMS + " TEXT NOT NULL, " + 
            COL_NAME + " TEXT, " + 
            COL_ADDRESS + " TEXT, " +
            COL_STATUS + " TEXT " +
            ");";

    private static final String CREATE_TEST_DATA1 = 
        "INSERT INTO "+TABLE_ITEMS+
            " ("+
                COL_ITEMS+","+
                COL_NAME+","+
                COL_ADDRESS+","+
                COL_STATUS+
                ") VALUES (" +
                "'Gems',"+
                "'KAJU',"+
                "'Behala',"+
                "'DELIVERED'"+
                ");";

    private static final String CREATE_TEST_DATA2 = 
        "INSERT INTO "+TABLE_ITEMS+
        " ("+
        COL_ITEMS+","+
        COL_NAME+","+
        COL_ADDRESS+","+
        COL_STATUS+
        ") VALUES (" +
        "'Eclairs',"+
        "'BIJU',"+
        "'Joka',"+
        "'PENDING'"+
            ");";

    private static final String CREATE_TEST_DATA3 = 
        "INSERT INTO "+TABLE_ITEMS+
        " ("+
        COL_ITEMS+","+
        COL_NAME+","+
        COL_ADDRESS+","+
        COL_STATUS+
        ") VALUES (" +
        "'Donut',"+
        "'RAJU',"+
        "'Kasba',"+
        "'DELIVERED'"+
            ");";

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_DB_TABLE_DATES);
            db.execSQL(CREATE_TEST_DATA1);
            db.execSQL(CREATE_TEST_DATA2);
            db.execSQL(CREATE_TEST_DATA3);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            // if the new version is higher than the old version, 
            // delete existing tables:
            if (newVersion > oldVersion) {
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
                onCreate(db);
            } else {
                // otherwise, create the database
                onCreate(db);
            }

        }

    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public DbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public DbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public Cursor fetchListItems() {

        Cursor cursor = 
            mDb.query(TABLE_ITEMS, new String[] 
                      {COL_ID, COL_ITEMS, COL_NAME, COL_ADDRESS, COL_STATUS}, 
                      null, null, null, null, null, null);

        if (cursor != null) {
            cursor.moveToFirst();
        }
        return cursor;
    }

}

Upvotes: 0

Views: 11044

Answers (2)

Cruceo
Cruceo

Reputation: 6824

It looks like you're trying to cast a Cursor to a String:

String val=(String)(mListView.getItemAtPosition(position));

At least that's what this error makes it out to be:

java.lang.ClassCastException: android.database.sqlite.SQLiteCursor

Try getting a String representation of the data from the Cursor, not casting the Cursor to a String directly.

EDIT:

A Cursor contains pointers to information stored in a database. Without knowing how your DB is structured, it'd be impossible for me to really do that for you. However, you can try this format:

String val = mListView.getItemAtPosition(position).getString(columnIndexInteger);

Where columnIndexInteger is the integer value of the column. If you don't know it, but have a String name for it, you can get it with: getColumnIndex(). If that's the case, adjust this:

Cursor c = (Cursor)mListView.getItemAtPosition(position);
String val = c.getString(c.getColumnIndex(DbAdapter.COL_NAME));

The above line should set val to the database record associated with COL_NAME

Upvotes: 2

Rishabh Bhardwaj
Rishabh Bhardwaj

Reputation: 831

This exception occured because you are passing integer value to the toast massage.Toast need char sequence.So replate your line

    Toast.makeText(ListviewActivity.this,position, Toast.LENGTH_SHORT).show();

with

  Toast.makeText(ListviewActivity.this,position+"", Toast.LENGTH_SHORT).show();

on click of listView.

Upvotes: 0

Related Questions