Blog Archive

Android SQLITE query selection example

In this example we are going to learn how to create a SQLite database adapter that will perform the basic operations such as creating the table, upgrading the database as well as providing access to the data based on given input parameters. SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks.  To query a given table and return a Cursor over the result set you can use the following method.
  • public Cursor query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

Parameters
  • table 
    • The table name to compile the query against.
  • columns 
    • A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
  • selection 
    • A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
  • selectionArgs 
    • You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
  • groupBy 
    • A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
  • having 
    • A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
  • orderBy 
    • How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
  • limit 
    • Limits the number of rows returned by the query, formatted as LIMIT clause. Passing null denotes no LIMIT clause.
Returns
  • A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized

package com.as400samplecode.Util;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class OrderDetailDbAdapter {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_STATUS = "statusCode";
    public static final String KEY_COMPANY = "company";
    public static final String KEY_ORDER = "orderNumber";
    public static final String KEY_SEQ = "sequence";
    public static final String KEY_ITEM = "item";
    public static final String KEY_DESCRIPTION = "description";
    public static final String KEY_QUANTITY = "quantity";
    public static final String KEY_PRICE = "price";

    private static final String TAG = "OrderDetailDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "OrderDatabase";
    private static final String SQLITE_TABLE = "OrderDetail";
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE =
        "CREATE TABLE " + SQLITE_TABLE + " (" +
        KEY_ROWID + " integer PRIMARY KEY autoincrement," +
        KEY_STATUS + "," +
        KEY_COMPANY + "," +
        KEY_ORDER + "," +
        KEY_SEQ + "," +
        KEY_ITEM + "," +
        KEY_DESCRIPTION + "," +
        KEY_QUANTITY + "," +
        KEY_PRICE + "," +
        " UNIQUE (" + KEY_COMPANY + "," + KEY_ORDER + "," + KEY_SEQ  + "," + KEY_ITEM +"));";


    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }


        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.w(TAG, DATABASE_CREATE);
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
            onCreate(db);
        }
    }

    public OrderDetailDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

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

    public void close() {
        if (mDbHelper != null) {
            mDbHelper.close();
        }
    }


    public long createOrderDetail() {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_STATUS, "A");
        initialValues.put(KEY_COMPANY, "1");
        initialValues.put(KEY_ORDER, "123");
        initialValues.put(KEY_SEQ, "1");
        initialValues.put(KEY_ITEM,"ABC");
        initialValues.put(KEY_DESCRIPTION, "Item ABC description");
        initialValues.put(KEY_QUANTITY, "100");
        initialValues.put(KEY_PRICE, "99.99");
        return mDb.insert(SQLITE_TABLE, null, initialValues);
    }

    public boolean deleteOrderDetail(long rowId) {

        return mDb.delete(SQLITE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public ArrayList<OrderDetail> getOrderDetails(String company, String orderNumber) throws SQLException {


        ArrayList<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();
        Cursor mCursor =


            mDb.query(true, SQLITE_TABLE, new String[] {
                    KEY_ROWID,
                    KEY_COMPANY,
                    KEY_ORDER,
                    KEY_SEQ,
                    KEY_ITEM,
                    KEY_DESCRIPTION,
                    KEY_QUANTITY,
                    KEY_PRICE,}, 
                    KEY_COMPANY + "=?" + " and "  +
                    KEY_ORDER + "=?", 
                    new String[] {company,orderNumber},
                    null, null, KEY_ITEM , null);


        if (mCursor.moveToFirst()) {
            do {
                OrderDetail orderDetail = new OrderDetail(); 
                orderDetail.setItem(mCursor.getString(mCursor.getColumnIndexOrThrow(KEY_ITEM)));
                orderDetail.setDescription(mCursor.getString(mCursor.getColumnIndexOrThrow(KEY_DESCRIPTION)));
                orderDetail.setQuantity(mCursor.getString(mCursor.getColumnIndexOrThrow(KEY_QUANTITY)));
                orderDetail.setPrice(mCursor.getString(mCursor.getColumnIndexOrThrow(KEY_PRICE)));
                orderDetailList.add(orderDetail);
            } while (mCursor.moveToNext());
        }
        if (mCursor != null && !mCursor.isClosed()) {
            mCursor.close();
        }
        return orderDetailList;


    }


    public boolean deleteAllOrderDetails() {

        int doneDelete = 0;
        doneDelete = mDb.delete(SQLITE_TABLE, null , null);
        Log.w(TAG, Integer.toString(doneDelete));
        return doneDelete > 0;

    }

}

5 comments :

  1. thanks for this example, saved me lots of time ,especially with the selection where part .

    ReplyDelete
  2. Thanks a lot! Very helpful

    ReplyDelete
  3. how to write search query ........

    ReplyDelete
  4. tnx :) it did help me to think...

    #GiftedHand11

    ReplyDelete