Adsense Ad

Saturday, 30 December 2017

Database Handler Class For Android SQLite DB

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

/** * Created by HasanJawaid on 10/20/2017. */

public class DatabaseHandler extends SQLiteOpenHelper {
    SQLiteDatabase sqLiteDatabase=getWritableDatabase();
    private static final String dbname="sampledb";
    private static final int dbver=1;
    public DatabaseHandler(Context context) {
        super(context, dbname, null, dbver);
    }

    @Override    
public void onCreate(SQLiteDatabase db) {
    String CreateTableQry="Create Table if not exists UBAG(" +
            "id integer primary key autoincrement not null, " +
            "uname text , " +
            "pword text , " +
            "fname text , " +
            "lname text , " +
            "age integer, " +
            "email text , " +
            "gender text  )";

            db.execSQL(CreateTableQry);
            Log.e("","UBAG Table Created...");

        CreateTableQry = "Create Table if not exists USHIS(" +
                "id integer, " +
                "ldate Date, " +
                "timein integer, " +
                "timeout integer ) ";

            db.execSQL(CreateTableQry);
            Log.e("","USHIS Table Created...");

    }

    @Override    
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("Drop table if exists UBAG");
        db.execSQL("Drop table if exists USHIS");
        onCreate(db);
    }

    public long insert(ContentValues values,String TableName){
        return (long) sqLiteDatabase.insert(TableName,null,values);
    }

    public long update(ContentValues values,String TableName,String criteria){
        return sqLiteDatabase.update(TableName,values,criteria,null);
    }

    public long delete(String TableName,String criteria){
        return sqLiteDatabase.delete(TableName,criteria,null);
    }

    public Cursor getData(String query){
        Cursor cursor=null;
        try {
            cursor = sqLiteDatabase.rawQuery(query, null);
        }catch (Exception e){
            Log.e("GD","DB Helper Found Error " + query);
        }
        cursor.moveToFirst();
        return cursor;
    }
}

No comments: