SQLiteDatabase Helper class : SQLiteDatabase « Database « Android






SQLiteDatabase Helper class

    
//package com.fit.aSeaBus.utils;

import java.io.Serializable;

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

@SuppressWarnings("serial")
abstract class DaoUtils implements Serializable {

  protected final String DB_NAME = "SeaBusDB";
  protected String TBL_NAME;
  protected SQLiteDatabase sql;
  protected String[] attrs;

  public SQLiteDatabase createDB(Context ctx) {
    SQLiteDatabase sql = null;
    try {
      sql = ctx.openOrCreateDatabase(DB_NAME,
          SQLiteDatabase.CREATE_IF_NECESSARY, null);
    } catch (Exception e) {
      sql.close();
      sql = ctx.openOrCreateDatabase(DB_NAME,
          SQLiteDatabase.CREATE_IF_NECESSARY, null);
    }
    return sql;
  }

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

  public void delete(String whereClause) throws Exception {
    sql.delete(TBL_NAME, whereClause, null);
  }

  public long insert(String[] attr) {
    ContentValues initialValues = new ContentValues();
    for (int i = 0; i < attr.length; i += 2) {
      initialValues.put(attr[i], attr[i + 1]);
    }
    long i = -1;
    try {
      i = sql.insert(TBL_NAME, null, initialValues);
    } catch (Exception e) {
      Log.e("Hata", e.toString());
      e.printStackTrace();
    }
    return i;
  }

  public Cursor getAllRows(String table, String[] var) {
    try {
      return sql.query(table, var, null, null, null, null, null);
    } catch (Exception e) {
      System.out.println(e.toString());
      Log.e("Exception on query", e.toString());
      return null;
    }
  }

  public Cursor execSQL(String[] st, String[] var) {
    try {
      String query = TBL_NAME + " WHERE ";
      boolean k = false;
      for (int i = 0; i < var.length; i++) {
        if (k)
          query += " AND ";
        else
          k = true;
        query += st[i] + " = '" + var[i] + "'";
      }
      return sql.query(query, null, null, null, null, null, null);
    } catch (Exception e) {
      System.out.println(e.toString());
      Log.e("Exception on query", e.toString());
      return null;
    }
  }
}

   
    
    
    
  








Related examples in the same category

1.Use SQLiteDatabase
2.SQLiteDatabase and ReentrantLock
3.SQLiteDatabase wrapper
4.Using Database
5.SQLite based diary app
6.Create table, insert record, delete records, query table, remove table
7.Insert Data into database
8.Searchable Dictionary
9.Sqlite Annotations Helper
10.Convert From Java Week To Sqlite Week