0

I'll try to explain my problem. I've created a little project based on Zxing library for reading and storing barcodes. Now I've to create my first ListView, containing the elements from the working SQLite db. Here is an extract of my source code

DBAdapter

public boolean insertProduct(String barcode, int quantity)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_BARCODE, barcode);
    initialValues.put(KEY_QUANTITY, quantity);
    try {
        db.insert(DATABASE_TABLE, null, initialValues);
        return true;
    }
    catch(Exception ex){
        return false;
    }
}

public boolean deleteProduct(String barcode)
{
    return db.delete(DATABASE_TABLE, KEY_BARCODE + "=" + barcode, null) > 0;
}


public Cursor getAllProducts()
{
    return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_BARCODE, KEY_QUANTITY}, null, null, null, null, null);
}

Now I don't know how to populate the ListView in Activity class. Could someone help me?

1 Answer 1

1

Since your getAllProducts() will return a cursor, you could use a cursor adapter. Here is some sample code for the activity class:

Cursor cursor = db.query(DATABASE_TABLE,
    new String[] {KEY_ROWID, KEY_BARCODE, KEY_QUANTITY}, null, null, null, null, null);

CursorAdapter listAdapter = new SimpleCursorAdapter(this, 
    _id_of_your_item_layout, // You'll have to make your own item layout
    cursor, 
    new String[] {KEY_ROWID, KEY_BARCODE, KEY_QUANTITY}, 
    new int[]{id_of_textview_1, id_of_textview_2, id_of_textview_3}, 0);

Here is the breakdown:

CursorAdapter listAdapter = new SimpleCursorAdapter(Context context, 
    int layoutID,
    Cursor cursor, 
    String[] {FromColumns}, 
    int[] {toViews}, int flags);

It's worth noting that you don't have to use your own item layout. It all depends on how many fields you want in each list item and how you want them displayed. Android has a bunch of layouts baked in that you can use, again it depends. Here is a link for those layouts if you want to check them out.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.