Android Open Source - Books Books Storage






From Project

Back to project page Books.

License

The source code is released under:

Apache License

If you think the Android project Books listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.contender.books;
//w  w w  . ja  va2  s .  com
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.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.provider.BaseColumns;
import android.util.Log;

/**
 * Database helper class, creates and maintains an SQLite DB and provides methods to 
 * manipulate its data.
 * <p>
 * Contains all the constants of the table and column names.
 * 
 * @author Paul Klinkenberg <pklinken@gmail.com>
  */
public class BooksStorage {

  private static final int DATABASE_VERSION = 10;

  private static final String DATABASE_NAME = "books.db";
  private static final String TAG = "BooksStorage";

  /**
   * Books table, where all current book loans reside.
   */
  public static final String BOOKS_TABLE_NAME = "books";
  /**
   * History table, where all deleted entries from books go.
   */
  public static final String HISTORY_TABLE_NAME = "history";

  // The data columns
  public static final String COLUMN_NAME__ID = BaseColumns._ID;
  public static final String COLUMN_NAME_BOOK = "books";
  public static final String COLUMN_NAME_CONTACT = "contacts";
  public static final String COLUMN_NAME_AUTHOR = "author";
  public static final String COLUMN_NAME_LOANDATE = "loandate";
  public static final String COLUMN_NAME_DUEDATE = "duedate";
  public static final String COLUMN_NAME_HASREMINDER = "hasreminder";
  public static final String COLUMN_NAME_RETURNDATE = "returndate";
  public static final String COLUMN_NAME_CALENDAREVENTID = "calendareventid";

  private BooksHelper mBooksHelper;
  
  /**
   * Nested helper class that creates/upgrades DB tables as needed
   * @see SQLiteOpenHelper
   */
  static class BooksHelper extends SQLiteOpenHelper {
    
    private static BooksHelper mInstance = null;

    public static BooksHelper getInstance(Context context) {
      if (mInstance == null) {
        mInstance = new BooksHelper(context.getApplicationContext());
      }
      return mInstance;
    }
    
    private BooksHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      try {
      db.execSQL("CREATE TABLE " + BOOKS_TABLE_NAME + " (" +
          COLUMN_NAME__ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
          COLUMN_NAME_BOOK + " TEXT NOT NULL," +
          COLUMN_NAME_CONTACT + " TEXT NOT NULL," +
          COLUMN_NAME_AUTHOR + " TEXT," +
          COLUMN_NAME_LOANDATE + " LONG NOT NULL," +
          COLUMN_NAME_DUEDATE + " LONG NOT NULL," +
          COLUMN_NAME_HASREMINDER + " BOOLEAN NOT NULL," +
          COLUMN_NAME_CALENDAREVENTID + " LONG" + ");");
      } catch (SQLException e) {
        Log.e(TAG, "Error: " + e.getLocalizedMessage());
      }
      
      try {
      db.execSQL("CREATE TABLE " + HISTORY_TABLE_NAME + " (" +
          COLUMN_NAME__ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
          COLUMN_NAME_BOOK + " TEXT NOT NULL," +
          COLUMN_NAME_CONTACT + " TEXT NOT NULL," +
          COLUMN_NAME_AUTHOR + " TEXT," +
          COLUMN_NAME_RETURNDATE + " LONG NOT NULL" + ");");
      } catch (SQLException e) {
        Log.e(TAG, "Error: " + e.getLocalizedMessage());
      }
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

      // Kills the table and existing data
      db.execSQL("DROP TABLE IF EXISTS books");
      db.execSQL("DROP TABLE IF EXISTS history");

      // Recreates the database with a new version
      onCreate(db);
    }
  }


  public BooksStorage(Context context) {

    mBooksHelper = BooksHelper.getInstance(context);
  }

  /**
   * Query the DB.
   * 
   * @param table The table to query
   * @param projection A list of which columns to return. Passing null will return all columns,<br>
   * which is discouraged to prevent reading data from storage that isn't going to be used.
   * @param selection A filter declaring which rows to return, formatted as an SQL WHERE<br>
   * clause (excluding the WHERE itself). Passing null will return all rows for the given URL. 
   * @param selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs,<br>
   * in order that they appear in the selection. The values will be bound as Strings.
   * @param sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself).<br>
   * Passing null will use the default sort order, which may be unordered.
   * @return a cursor over the result set or null if table was null or if an error occured.
   */
  // Returns a cursor to the DB pointing to the requested data
  // Will return null if the query is not valid
  public Cursor query(String table, String[] projection, String selection, String[] selectionArgs, String sortOrder )  {

    SQLiteQueryBuilder qr = new SQLiteQueryBuilder();
    if(table != null)
      qr.setTables(table);
    else
      return null;

    SQLiteDatabase db;
    try {
    db = mBooksHelper.getReadableDatabase();
    } catch (SQLiteException e) {
      Log.e(TAG, "Error: " + e.getLocalizedMessage());
      return null;
    }
    Cursor c = qr.query(db, projection, selection, selectionArgs, null, null, sortOrder);
    
    return c;
  }

  /**
   * Insert a new row into the DB
   * 
   * @param table The table in which to insert a new row.
   * @param initialValues Contains the key-value pairs to insert.
   * @return the row ID of the newly inserted row, or -1 if an error occurred
   */
  // Enter a new row in the DB, returns the row ID of the inserted row.
  public long insert(String table, ContentValues initialValues) {

    if(table != HISTORY_TABLE_NAME && table != BOOKS_TABLE_NAME)
      return -1;

    ContentValues values;
    if(initialValues != null) {
      values = new ContentValues(initialValues);
    } else {
      return -1;
    }

    // Check if any of the not null columns are missing data
    if(values.containsKey(COLUMN_NAME_BOOK) == false || values.containsKey(COLUMN_NAME_CONTACT) == false ||
        values.containsKey(COLUMN_NAME_LOANDATE) == false || values.containsKey(COLUMN_NAME_DUEDATE) == false || 
        values.containsKey(COLUMN_NAME_LOANDATE) == false) {
      if(table == HISTORY_TABLE_NAME) {
      } else {
        return -1;        
      }
    }
      
    SQLiteDatabase db;
    try {
      db = mBooksHelper.getWritableDatabase();
    } catch (SQLiteException e) {
      Log.e(TAG, "Error: " + e.getLocalizedMessage());
      return -1;
    }
    
    long result = db.insert(table, COLUMN_NAME_BOOK, values);
    
    return result;
  }
  
  /**
   * Delete a row from the DB.
   * 
   * @param table the table to delete from
   * @param where the optional WHERE clause to apply when deleting. Passing null will delete all rows. 
   * @param whereArgs You may include ?s in the where clause, which will be replaced by the values from whereArgs.
   * The values will be bound as Strings.
   * @return the number of rows affected if a whereClause is passed in, 0 otherwise, -1 on a DB error (SQLiteException) 
   */
  public int delete(String table, String where, String[] whereArgs) {
    
    int count;
    SQLiteDatabase db;
    
    try {
      db = mBooksHelper.getWritableDatabase();
    } catch (SQLiteException e) {
      Log.e(TAG, "Error: " + e.getLocalizedMessage());
      return -1;
    }
    
    if(table != HISTORY_TABLE_NAME && table != BOOKS_TABLE_NAME)
      return -1;
    
    count = db.delete(table, where, whereArgs);
    
    return count;
  }

/**
 * Updates a row in the DB
 * 
 * @param table the table to update in
 * @param values a map from column names to new column values. null is a valid value that will be translated to NULL.
 * @param where the optional WHERE clause to apply when updating. Passing null will update all rows.
 * @param whereArgs You may include ?s in the where clause, which will be replaced by the values from whereArgs.
 * The values will be bound as Strings.
 * @return the number of rows affected, -1 when an SQLiteException occurs, or the user tries to pass where
 * a null argument, or table is invalid.
 */
  public int update(String table, ContentValues values, String where, String[] whereArgs) {
    
    int count;
    SQLiteDatabase db;
    
    try {
      db = mBooksHelper.getWritableDatabase();
    } catch (SQLiteException e) {
      Log.e(TAG, "Error: " + e.getLocalizedMessage());
      return -1;
    }
    
    if(table != HISTORY_TABLE_NAME && table != BOOKS_TABLE_NAME)
      return -1;
    
    if(where == null) {
      Log.w("Books", "Please dont murder the DB.");
      return -1;
    }
        
    count = db.update(table, values, where, whereArgs);
    
    return count;
  }
}




Java Source Code List

com.contender.books.BookActivity.java
com.contender.books.BooksStorage.java
com.contender.books.DatePickerFragment.java
com.contender.books.EditOrDeleteDialogFragment.java
com.contender.books.HistoryActivity.java
com.contender.books.MainView.java
com.contender.books.ScanOrManualDialogFragment.java
com.contender.books.SettingsActivity.java
com.contender.books.SpecialCursorAdapter.java
com.google.zxing.integration.android.IntentIntegrator.java
com.google.zxing.integration.android.IntentResult.java