SQLiteDatabase and ReentrantLock : SQLiteDatabase « Database « Android






SQLiteDatabase and ReentrantLock

    
//package com.softright.db;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

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

public class Database {
  private final ReentrantLock lock = new ReentrantLock();

  private static final int LONG = 3327612;
  private static final int INT = 104431;
  private static final int STRING = 1195259493;
  private static final int INTEGER = -2056817302;
  private static final int LONG_CLZ = 398795216;

  private SQLiteDatabase sqlLite;
  
  private static final Map<String, Database> databases = new HashMap<String, Database>();

  public static Database getInstance(String name,Context context) {
    Database rlt = databases.get(name);
    if (rlt == null)
      return new Database(name,context);
    else
      return rlt;
  }
  
  

  private Database(String name,Context context) {
    sqlLite = context.openOrCreateDatabase(name + ".db", Context.MODE_WORLD_WRITEABLE, null);
    databases.put(name, this);
  }

  public void begin() {

    sqlLite.beginTransaction();
    lock.lock();
  }

  public void commit() {
    sqlLite.setTransactionSuccessful();
    sqlLite.endTransaction();
  }

  public void rollback() {
    sqlLite.endTransaction();
    
  }

  public void close() {
    lock.unlock();
  }

  @SuppressWarnings("unchecked")
  public void checkTable(Class clz) {
    Field[] fields = clz.getFields();
    StringBuffer sql = new StringBuffer();
    sql.append("create table IF NOT EXISTS ");

    sql.append(getTableName(clz));
    sql.append("(");
    for (int i = 0; i < fields.length; i++) {
      Field field = fields[i];
      if (this.isFieldValid(field.getType().getName())) {
        sql.append(field.getName());
        sql.append(",");
      }

    }
    sql.setCharAt(sql.length() - 1, ')');
    Log.d("DB", sql.toString());
    sqlLite.execSQL(sql.toString());
  }

  public boolean exist(Object obj, String where) {
    StringBuffer sql = new StringBuffer();
    sql.append("select count(0) from ");
    sql.append(getTableName(obj.getClass()));
    sql.append(" where ");
    sql.append(where);
    
    Cursor cursor = sqlLite.rawQuery(sql.toString(), null);
    if (cursor.moveToFirst())
      return cursor.getInt(0) > 0;
    else
      return false;

  }

  @SuppressWarnings("unchecked")
  public int count(Class clz, String where) {
    StringBuffer sql = new StringBuffer();
    sql.append("select count(0) from ");
    sql.append(getTableName(clz));
    if (where != null) {
      sql.append(" where ");
      sql.append(where);
    }
    Cursor cursor = sqlLite.rawQuery(sql.toString(), null);
    if (cursor.moveToFirst())
      return cursor.getInt(0);
    else
      return 0;

  }

  public int insert(Object object) {

    ContentValues values = new ContentValues();
    Field[] fields = object.getClass().getFields();
    String where = "";
    for (int i = 0; i < fields.length; i++) {
      Field field = fields[i];
      try {
        if (field.get(object) != null) {

          boolean pk = field.getName().equalsIgnoreCase("localId");
          switch (field.getType().getName().hashCode()) {
          case STRING:// string
            values.put(field.getName(), field.get(object).toString());
            if (pk)
              where = field.getName() + "='" + field.get(object).toString() + "'";
            break;
          case LONG:// long
          case LONG_CLZ:
            values.put(field.getName(), field.getLong(object));
            if (pk)
              where = field.getName() + "=" + field.getLong(object);
            break;
          case INT:// integer
          case INTEGER:
            values.put(field.getName(), field.getInt(object));
            if (pk)
              where = field.getName() + "=" + field.getInt(object);
          }
          if (pk && this.exist(object, where)) {
            return this.save(object);

          }
        }
      } catch (IllegalArgumentException e) {

        e.printStackTrace();
      } catch (IllegalAccessException e) {

        e.printStackTrace();
      }
    }
    return (int) sqlLite.insert(getTableName(object.getClass()), "", values);
    
  }

  public int save(Object object) {

    ContentValues values = new ContentValues();
    Field[] fields = object.getClass().getFields();
    String where = "";

    for (int i = 0; i < fields.length; i++) {
      Field field = fields[i];
      try {

        if (field.getName().equalsIgnoreCase("localId")) {
          where = field.getName() + "=";
          switch (field.getType().getName().hashCode()) {
          case STRING:// string
            where += "'" + field.get(object).toString() + "'";
            break;
          case LONG:// long
          case LONG_CLZ:
          case INT:// integer
          case INTEGER:
            where += field.get(object).toString();
            break;

          }

        } else {
          Object value = field.get(object);
          if (value != null) {

            switch (field.getType().getName().hashCode()) {
            case STRING:// string
              values.put(field.getName(), value.toString());
              break;
            case LONG:// long
            case LONG_CLZ:
              values.put(field.getName(), (Long) value);
              break;
            case INT:// integer
            case INTEGER:
              values.put(field.getName(), (Integer) value);
            }
          }
        }

      } catch (IllegalArgumentException e) {

        e.printStackTrace();
      } catch (IllegalAccessException e) {

        e.printStackTrace();
      }
    }
    Log.d("DB","db update:"+object.getClass().getName()+" "+where);
    if(object.getClass().getName().equals("com.softright.db.ContactBase"))
    {
    }
    return (int) sqlLite.update(getTableName(object.getClass()), values, where, null);
  }

  @SuppressWarnings("unchecked")
  private Object readCursor(Class clz, Cursor cursor, Map map) throws Exception {

    Object result = clz.newInstance();
    Field[] fields = clz.getFields();
    Object key = null;
    for (int i = 0; i < fields.length; i++) {
      Field field = fields[i];
      try {
        int columIndex = cursor.getColumnIndex(field.getName());
        if (columIndex < 0)
          continue;
        Object value = null;
        switch (field.getType().getName().hashCode()) {
        case STRING:// string
          value = cursor.getString(columIndex);
          field.set(result, cursor.getString(columIndex));
          break;
        case LONG:// long
        case LONG_CLZ:
          value = cursor.getLong(columIndex);
          field.set(result, cursor.getLong(columIndex));
          break;
        case INT:// integer
        case INTEGER:
          value = cursor.getInt(columIndex);
          field.set(result, cursor.getInt(columIndex));
          break;
        }

        if (field.getName().equalsIgnoreCase("localId") && map != null) {
          key = value;
        }

      } catch (Exception e) {
        Log.d("database", "database readcursor failed!");
        e.printStackTrace();
      }
    }
    if (map != null)
      map.put(key, result);
    return result;
  }

  private boolean isFieldValid(String name) {
    switch (name.hashCode()) {
    case STRING:
    case INT:
    case LONG:
    case INTEGER:
    case LONG_CLZ:
      return true;
    default:
      return false;
    }
  }

  @SuppressWarnings("unchecked")
  private String getTableName(Class clz)
  {
    return clz.getSimpleName();
  }
  
  @SuppressWarnings("unchecked")
  public List<?> search(Class clz, String where, String[] args, int start, int maxResult, Map map) {

    StringBuffer query = new StringBuffer();
    query.append("select ");
    Field[] fields = clz.getFields();
    for (int i = 0; i < fields.length; i++) {
      Field field = fields[i];
      try {

        if (isFieldValid(field.getType().getName())) {
          query.append(field.getName());
          query.append(",");
        }

      } catch (Exception e) {
        Log.d("NET", "net7");
        e.printStackTrace();
      }
    }
    query.setCharAt(query.length() - 1, ' ');
    query.append(" from ");
    query.append(getTableName(clz));

    if (where != null) {
      query.append(" where ");
      query.append(where);
    }
    Log.d("DB", "Search:"+query.toString());
    Cursor cursor = sqlLite.rawQuery(query.toString(), args);
    List<Object> rlt = new ArrayList<Object>();
    int index = 0;
    if (cursor.moveToFirst()) {
      if (start > 0) {
        if (!cursor.move(start))
          return rlt;
      }
      do {

        try {

          rlt.add(this.readCursor(clz, cursor, map));
          index++;

        } catch (Exception e) {
          Log.d("NET", "net6");
          e.printStackTrace();
        }
        if ((index) >= maxResult) {

          break;
        }
      } while (cursor.moveToNext());
    }
    
    return rlt;
  }

  @SuppressWarnings("unused")
  public Object locate(Object pk, Class<?> clz) {
    Field[] fields = clz.getFields();
    String where = "";
    String[] id = null;
    for (int i = 0; i < fields.length; i++) {
      Field field = fields[i];
      try {

        if (field.getName().equalsIgnoreCase("localId")) {
          switch (field.getType().getName().hashCode()) {
          case STRING:
            where = field.getName() + "=?";
            id = new String[] { pk.toString() };
            break;
          default:
            where = field.getName() + "=" + pk.toString();
            break;
          }

          break;
        }

      } catch (IllegalArgumentException e) {

        e.printStackTrace();
      }
    }
    List<?> rlt = this.search(clz, where, null, 0, 1, null);
    if (rlt.size() > 0)
      return rlt.get(0);
    else
      return null;
  }

  public Object locate(Class<?> clz, String where) {

    List<?> rlt = this.search(clz, where, null, 0, 1, null);
    if (rlt.size() > 0)
      return rlt.get(0);
    else
      return null;
  }

  public int delete(Object object) {
    Field[] fields = object.getClass().getFields();
    String where = "";
    String[] id = new String[1];
    for (int i = 0; i < fields.length; i++) {
      Field field = fields[i];
      try {

        if (field.getName().equalsIgnoreCase("localId")) {
          where = field.getName() + "=?";
          id[0] = field.get(object).toString();
          break;
        }

      } catch (IllegalArgumentException e) {

        e.printStackTrace();
      } catch (IllegalAccessException e) {

        e.printStackTrace();
      }
    }
    return (int) sqlLite.delete(getTableName(object.getClass()), where, id);
  }
}

   
    
    
    
  








Related examples in the same category

1.Use SQLiteDatabase
2.SQLiteDatabase wrapper
3.SQLiteDatabase Helper class
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