Database creation using sqlite database

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBController extends SQLiteOpenHelper {

/**
* Instantiates a new DB controller.
*/
public DBController(Context context) {
super(context, "xyz.db", null, 1);
}

// Creates Table
/*
* (non-Javadoc)
*
* @see
* android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
* .SQLiteDatabase)
*/
@Override
public void onCreate(SQLiteDatabase database) {
String query;
query = "CREATE TABLE cart (id INTEGER PRIMARY KEY AUTOINCREMENT,productId TEXT,productName TEXT,price TEXT,qty TEXT)";
database.execSQL(query);

database.execSQL(query);
}

/*
* (non-Javadoc)
*
* @see
* android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
* .SQLiteDatabase, int, int)
*/
@Override
public void onUpgrade(SQLiteDatabase database, int version_old,
int current_version) {
String query;
query = "DROP TABLE IF EXISTS cart";
database.execSQL(query);

onCreate(database);
}

/**
* Inserts User into SQLite DB.
*
* @param queryValues
*            the query values
*/
public void insertProductInCart(HashMap<String, String> queryValues) {

String productId = queryValues.get("productId");

if (!isProductExist(productId)) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("productId", productId);
values.put("productName", queryValues.get("product_name"));
values.put("price", queryValues.get("price"));
values.put("qty", queryValues.get("qty"));
database.insert("cart", null, values);
database.close();
} else {
int qty = 0;
String selectQuery = "SELECT qty FROM cart where productId='"
+ productId + "'";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = null;
try {
cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
qty = Integer.parseInt(cursor.getString(0));
} while (cursor.moveToNext());
}
} finally {
if (cursor != null)
cursor.close();
}
qty = qty + 1;
String query = "update cart set qty='" + qty
+ "' where productId='" + productId + "'";
database.execSQL(query);

database.close();

}
}

public boolean isProductExist(String productId) {

boolean flag = false;
String selectQuery = "SELECT * FROM cart where productId='" + productId
+ "'";
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = null;
try {
cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
flag = true;
} while (cursor.moveToNext());
}
} finally {
if (cursor != null)
cursor.close();
}

database.close();

return flag;
}
}

Share this

Related Posts

Previous
Next Post »