Back to project page MythTrack.
The source code is released under:
MIT License
If you think the Android project MythTrack listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
/** * MythTrackDatabase manages the database containing the saved hero information. * MythTrackSQLiteHelper simplifies interacting with the SQLite database. *//from ww w . ja va2 s .co m * @author Nolan Jurgens */ package nolanjurgens.mythtrack.provider; // IMPORTS ///////////////////////////////////////////////////////////////////////////////////////// import android.app.backup.BackupManager; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteCantOpenDatabaseException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabaseCorruptException; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.util.Log; //////////////////////////////////////////////////////////////////////////////////////////////////// // CLASS - MythTrackDatabase // //////////////////////////////////////////////////////////////////////////////////////////////////// public class MythTrackDatabase extends ContentProvider { // CONSTANTS ///////////////////////////////////////////////////////////////////////////////////// /** A tag used to mark console output.*/ private static final String TAG = "MythTrackDatabase"; // URI matcher constants. private static final int URI_HERO_TABLE = 1; private static final int URI_HERO_RECORD = 2; private static final int URI_ITEM_TABLE = 3; private static final int URI_ITEM_RECORD = 4; private static final int URI_INVENTORY_TABLE = 5; private static final int URI_INVENTORY_RECORD = 6; private static final int URI_TITLE_TABLE = 7; private static final int URI_TITLE_RECORD = 8; // FIELDS //////////////////////////////////////////////////////////////////////////////////////// /** The parent context.*/ private Context context; /** A SQLite database helper object.*/ private MythTrackDatabaseHelper databaseHelper; /** The SQLite database. */ private SQLiteDatabase sqLiteDatabase; /** Parses URIs and maps them to integer values.*/ private UriMatcher uriMatcher; // METHODS /////////////////////////////////////////////////////////////////////////////////////// /** * Request a database backup using the Google Backup API. */ private void backupDatabase() { BackupManager backupManager = new BackupManager(context); backupManager.dataChanged(); } /** * Adds entries to the URI matcher. */ private void buildURIMatcher() { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(MythTrackContract.AUTHORITY, MythTrackContract.Heroes.TABLE, URI_HERO_TABLE); uriMatcher.addURI(MythTrackContract.AUTHORITY, MythTrackContract.Heroes.TABLE + "/#", URI_HERO_RECORD); uriMatcher.addURI(MythTrackContract.AUTHORITY, MythTrackContract.Items.TABLE, URI_ITEM_TABLE); uriMatcher.addURI(MythTrackContract.AUTHORITY, MythTrackContract.Items.TABLE + "/#", URI_ITEM_RECORD); uriMatcher.addURI(MythTrackContract.AUTHORITY, MythTrackContract.Inventories.TABLE, URI_INVENTORY_TABLE); uriMatcher.addURI(MythTrackContract.AUTHORITY, MythTrackContract.Inventories.TABLE + "/#", URI_INVENTORY_RECORD); uriMatcher.addURI(MythTrackContract.AUTHORITY, MythTrackContract.Titles.TABLE, URI_TITLE_TABLE); uriMatcher.addURI(MythTrackContract.AUTHORITY, MythTrackContract.Titles.TABLE + "/#", URI_TITLE_RECORD); } /** * Open a writable connection the SQLite database. */ public void connect() { try { sqLiteDatabase = databaseHelper.getWritableDatabase(); } catch(SQLiteCantOpenDatabaseException exception) { Log.e(TAG, "Caught SQLiteCantOpenDatabaseException: " + exception.getMessage()); } catch(SQLiteDatabaseCorruptException exception) { Log.e(TAG, "Caught SQLiteDatabaseCorruptException: " + exception.getMessage()); } catch(SQLiteException exception) { Log.e(TAG, "Caught SQLiteException: " + exception.getMessage()); } } /** * Open a writable connection the SQLite database. */ public void connectReadOnly() { try { sqLiteDatabase = databaseHelper.getReadableDatabase(); } catch(SQLiteCantOpenDatabaseException exception) { Log.e(TAG, "Caught SQLiteCantOpenDatabaseException: " + exception.getMessage()); } catch(SQLiteDatabaseCorruptException exception) { Log.e(TAG, "Caught SQLiteDatabaseCorruptException: " + exception.getMessage()); } catch(SQLiteException exception) { Log.e(TAG, "Caught SQLiteException: " + exception.getMessage()); } } /** * Delete records from the database. * @param uri The URI of the table to delete from / record to delete. * @param selection Filter to match specific records to delete. * @param selectionArgs Additional arguments for the selection filter * @return The number of records deleted. */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int rowsDeleted; // Connect to the SQLite database. connect(); switch(uriMatcher.match(uri)) { // Delete multiple heroes. case URI_HERO_TABLE: { rowsDeleted = sqLiteDatabase.delete(MythTrackContract.Heroes.TABLE, selection, selectionArgs); break; } // Delete a single hero. case URI_HERO_RECORD: { String heroID = uri.getLastPathSegment(); String where = MythTrackContract.Heroes._ID + " = " + heroID; rowsDeleted = sqLiteDatabase.delete(MythTrackContract.Heroes.TABLE, where, null); break; } // Deleting items not needed/implemented. // Delete multiple inventory items. case URI_INVENTORY_TABLE: { rowsDeleted = sqLiteDatabase.delete(MythTrackContract.Inventories.TABLE, selection, selectionArgs); break; } // Delete a single inventory item. case URI_INVENTORY_RECORD: { String inventoryItemID = uri.getLastPathSegment(); String where = MythTrackContract.Inventories._ID + " = " + inventoryItemID; rowsDeleted = sqLiteDatabase.delete(MythTrackContract.Inventories.TABLE, where, null); break; } default: { throw new IllegalArgumentException("Unsupported URI for deletion: " + uri); } // Deleting titles not needed/implemented. } // Signal that rows have been deleted. if(rowsDeleted > 0) { context.getContentResolver().notifyChange(uri, null); backupDatabase(); } return rowsDeleted; } /** * Return the MIME type of the data at the given URI. * @param uri URI of the data. * @return MIME type string. */ @Override public String getType(Uri uri) { switch(uriMatcher.match(uri)) { case URI_HERO_TABLE: { return MythTrackContract.Heroes.CONTENT_TYPE; } case URI_HERO_RECORD: { return MythTrackContract.Heroes.CONTENT_RECORD_TYPE; } case URI_ITEM_TABLE: { return MythTrackContract.Items.CONTENT_TYPE; } case URI_ITEM_RECORD: { return MythTrackContract.Items.CONTENT_RECORD_TYPE; } case URI_INVENTORY_TABLE: { return MythTrackContract.Inventories.CONTENT_TYPE; } case URI_INVENTORY_RECORD: { return MythTrackContract.Inventories.CONTENT_RECORD_TYPE; } case URI_TITLE_TABLE: { return MythTrackContract.Titles.CONTENT_TYPE; } case URI_TITLE_RECORD: { return MythTrackContract.Titles.CONTENT_RECORD_TYPE; } default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } /** * Insert a new record into the database. * @param uri The URI to the table where the record is being inserted. * @param newRecord Container with the columns/values to initialize the new record with. * @return The URI of the new record. */ @Override public Uri insert(Uri uri, ContentValues newRecord) { long id; // Connect to the SQLite database. connect(); int uriMatch = uriMatcher.match(uri); // If the URI is for a valid table, insert the record into that table. switch(uriMatch) { case URI_HERO_TABLE: { id = sqLiteDatabase.insert(MythTrackContract.Heroes.TABLE, null, newRecord); break; } case URI_ITEM_TABLE: { id = sqLiteDatabase.insert(MythTrackContract.Items.TABLE, null, newRecord); break; } case URI_INVENTORY_TABLE: { id = sqLiteDatabase.insert(MythTrackContract.Inventories.TABLE, null, newRecord); break; } case URI_TITLE_TABLE: { id = sqLiteDatabase.insert(MythTrackContract.Titles.TABLE, null, newRecord); break; } default: { // The URI was not for a valid table. throw new IllegalArgumentException("Unsupported URI for insertion: " + uri); } } // A successful insert will give a positive ID value. if(id > 0) { // Signal that the content has been updated. context.getContentResolver().notifyChange(uri, null); backupDatabase(); // Return the URI to the new record. return ContentUris.withAppendedId(uri, id); } else { // Didn't get a new ID. Signal that the insert failed. throw new SQLiteException("Could not insert record into URI: " + uri); } } /** * Called when the content provider is started. * @return True when the provider loaded successfully. */ @Override public boolean onCreate() { // Save context handle. this.context = getContext(); // Initialize the database helper. databaseHelper = new MythTrackDatabaseHelper(context); // Initialize the URI matcher. buildURIMatcher(); return true; } /** * Query the database and put the results in a cursor. * @param uri The URI of the table/record to query. * @param projection Which columns are being retrieved. * @param sortOrder How to sort the results. * @return The generated cursor. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Connect to the SQLite database. connectReadOnly(); SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); switch(uriMatcher.match(uri)) { // Get the requested heroes. case URI_HERO_TABLE: { builder.setTables(MythTrackContract.Heroes.TABLE); break; } // Get a single requested hero. case URI_HERO_RECORD: { builder.setTables(MythTrackContract.Heroes.TABLE); // Get just the specified record. builder.appendWhere(MythTrackContract.Heroes._ID + " = " + uri.getLastPathSegment()); break; } // Get the requested items. case URI_ITEM_TABLE: { builder.setTables(MythTrackContract.Items.TABLE); break; } // Get a single requested item. case URI_ITEM_RECORD: { builder.setTables(MythTrackContract.Items.TABLE); // Get just the specified record. builder.appendWhere(MythTrackContract.Items._ID + " = " + uri.getLastPathSegment()); break; } // Get the requested inventory items and their info out of the items table. case URI_INVENTORY_TABLE: { // Joint table with inventory items and their matching info out of the items table. builder.setTables(MythTrackContract.Inventories.TABLE + " JOIN " + MythTrackContract.Items.TABLE + " ON " + MythTrackContract.Inventories.TABLE + "." + MythTrackContract.Inventories.COLUMN_ITEM_ID + " = " + MythTrackContract.Items.TABLE + "." + MythTrackContract.Items._ID); break; } // Get a single requested inventory item and its info from the items table. case URI_INVENTORY_RECORD: { // Joint table with inventory items and their matching info out of the items table. builder.setTables(MythTrackContract.Inventories.TABLE + " JOIN " + MythTrackContract.Items.TABLE + " ON " + MythTrackContract.Inventories.TABLE + "." + MythTrackContract.Inventories.COLUMN_ITEM_ID + " = " + MythTrackContract.Items.TABLE + "." + MythTrackContract.Items._ID); // Get just the specified record. builder.appendWhere(MythTrackContract.Inventories.TABLE + "." + MythTrackContract.Inventories._ID + " = " + uri.getLastPathSegment()); break; } // Get the requested titles. case URI_TITLE_TABLE: { builder.setTables(MythTrackContract.Titles.TABLE); break; } // Get a single requested title. case URI_TITLE_RECORD: { builder.setTables(MythTrackContract.Titles.TABLE); // Get just the specified record. builder.appendWhere(MythTrackContract.Titles._ID + " = " + uri.getLastPathSegment()); break; } default: { throw new IllegalArgumentException("Unsupported URI: " + uri); } } // Build the cursor. Cursor cursor = builder.query(sqLiteDatabase, projection, selection, selectionArgs, null, null, sortOrder); // Register the URI to watch for changes. cursor.setNotificationUri(context.getContentResolver(), uri); return cursor; } /** * Update all records matching the selection with the given update values. * @param uri The URI of the table or record to update. * @param updatedValues A set of column/value pairs to update with. * @param selection Filter to match specific records to update. * @param selectionArgs Additional arguments for the selection filter * @return The number of records updated. */ @Override public int update(Uri uri, ContentValues updatedValues, String selection, String[] selectionArgs) { int rowsUpdated; // Connect to the SQLite database. connect(); switch(uriMatcher.match(uri)) { // If the URI is for a single hero, update the hero. case URI_HERO_RECORD: { String heroID = uri.getLastPathSegment(); String where = MythTrackContract.Heroes._ID + " = " + heroID; rowsUpdated = sqLiteDatabase.update(MythTrackContract.Heroes.TABLE, updatedValues, where, null); break; } // If the URI is for a single item, update the item. case URI_ITEM_RECORD: { String itemID = uri.getLastPathSegment(); String where = MythTrackContract.Items._ID + " = " + itemID; rowsUpdated = sqLiteDatabase.update(MythTrackContract.Items.TABLE, updatedValues, where, null); break; } // Updating Inventory Items not needed / implemented yet. // If the URI is for a single title, update the title. case URI_TITLE_RECORD: { String titleID = uri.getLastPathSegment(); String where = MythTrackContract.Titles._ID + " = " + titleID; rowsUpdated = sqLiteDatabase.update(MythTrackContract.Titles.TABLE, updatedValues, where, null); break; } default: { throw new IllegalArgumentException("Unsupported URI for update: " + uri); } } // Signal that rows have been updated. if(rowsUpdated > 0) { context.getContentResolver().notifyChange(uri, null); backupDatabase(); } return rowsUpdated; } ////////////////////////////////////////////////////////////////////////////////////////////////// // SUBCLASS - MythTrackDatabaseHelper // ////////////////////////////////////////////////////////////////////////////////////////////////// public class MythTrackDatabaseHelper extends SQLiteOpenHelper { // CONSTANTS /////////////////////////////////////////////////////////////////////////////////// /** The version number. Increase on each schema change.*/ public static final int DATABASE_VERSION = 8; /** The filename of the SQLite database.*/ public static final String DATABASE_NAME = "MythTrack.sqlite3"; // METHODS ///////////////////////////////////////////////////////////////////////////////////// /** * Constructor * @param context The parent activity/context. */ public MythTrackDatabaseHelper(Context context) { super(context, DATABASE_NAME, null,DATABASE_VERSION); } /** * Create the tables in the database. * @param database The database where the tables are being created. */ public void createTables(SQLiteDatabase database) { // Create Heroes table. database.execSQL("CREATE TABLE " + MythTrackContract.Heroes.TABLE + " (" + MythTrackContract.Heroes._ID + " INTEGER PRIMARY KEY," + MythTrackContract.Heroes.COLUMN_NAME + " TEXT NOT NULL," + MythTrackContract.Heroes.COLUMN_CLASS_ID + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_ATTRIBUTE + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_MOVEMENT + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_BASE_VITALITY + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_COURAGE + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_THREAT + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_VITALITY + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_GOLD + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_SERENDIPITY + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_PRIMARY + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_SECONDARY + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_ARMOR + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_HELM + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_ACCESSORY + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_TITLE + " INTEGER NOT NULL," + MythTrackContract.Heroes.COLUMN_STATUS_EFFECTS + " INTEGER NOT NULL" + ");"); // Create Items table. database.execSQL("CREATE TABLE " + MythTrackContract.Items.TABLE + " (" + MythTrackContract.Items._ID + " INTEGER PRIMARY KEY," + MythTrackContract.Items.COLUMN_NAME + " TEXT NOT NULL," + MythTrackContract.Items.COLUMN_SOURCE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_TYPE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_RARITY + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_CASTING + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_RANGE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_BUY + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_SELL + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_HIT_DICE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_FATE_DICE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_OFFENSE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_DEFENSE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_MOVEMENT_POINTS + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_CAUTIOUS_MOVEMENT + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_NON_COMBAT_ACTION + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_COURAGE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_MIN_THREAT + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_MAX_THREAT + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_VITALITY + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_FAITH + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_AMMO + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_VERSES + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_RAGE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_ESSENCE + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_DURABILITY + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_PARTS + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_POTION + " INTEGER NOT NULL," + MythTrackContract.Items.COLUMN_IMMUNITIES + " INTEGER NOT NULL" + ");"); // Create Inventories table. database.execSQL("CREATE TABLE " + MythTrackContract.Inventories.TABLE + " (" + MythTrackContract.Inventories._ID + " INTEGER PRIMARY KEY," + MythTrackContract.Inventories.COLUMN_HERO_ID + " INTEGER NOT NULL," + MythTrackContract.Inventories.COLUMN_ITEM_ID + " INTEGER NOT NULL" + ");"); // Create Titles table. database.execSQL("CREATE TABLE " + MythTrackContract.Titles.TABLE + " (" + MythTrackContract.Titles._ID + " INTEGER PRIMARY KEY," + MythTrackContract.Titles.COLUMN_NAME + " TEXT NOT NULL," + MythTrackContract.Titles.COLUMN_DESCRIPTION + " TEXT NOT NULL," + MythTrackContract.Titles.COLUMN_MOVEMENT_POINTS + " INTEGER NOT NULL," + MythTrackContract.Titles.COLUMN_NON_COMBAT_ACTION + " INTEGER NOT NULL," + MythTrackContract.Titles.COLUMN_VITALITY + " INTEGER NOT NULL," + MythTrackContract.Titles.COLUMN_IMMUNITIES + " INTEGER NOT NULL" + ");"); } /** * Delete all tables from the database. * @param database The SQLite database where the tables are being erased from. */ public void dropAllTables(SQLiteDatabase database) { database.execSQL("DROP TABLE IF EXISTS " + MythTrackContract.Heroes.TABLE); database.execSQL("DROP TABLE IF EXISTS " + MythTrackContract.Items.TABLE); database.execSQL("DROP TABLE IF EXISTS " + MythTrackContract.Inventories.TABLE); database.execSQL("DROP TABLE IF EXISTS " + MythTrackContract.Titles.TABLE); } /** * Create the tables for the database. * @param database The SQLite database being created. */ public void onCreate(SQLiteDatabase database) { createTables(database); } /** * Called when the database version increases. * @param database The SQLite database being upgraded. * @param oldVersion The old version stored in the database. * @param newVersion The new version defined in the DATABASE_VERSION constant. */ public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { // If the database is older than version 5, just drop it and recreate it. if(oldVersion < 5) { // Drop the old tables. dropAllTables(database); // Recreate the new tables. createTables(database); } switch(oldVersion) { // 5 -> 6: Adds the non-combat action modifier column to the item table. case 5: { database.execSQL("ALTER TABLE " + MythTrackContract.Items.TABLE + " ADD COLUMN " + MythTrackContract.Items.COLUMN_NON_COMBAT_ACTION + " INTEGER NOT NULL DEFAULT 0"); } // 6 -> 7: Adds verses, essence, durability, and parts columns to the item table. case 6: { database.execSQL("ALTER TABLE " + MythTrackContract.Items.TABLE + " ADD COLUMN " + MythTrackContract.Items.COLUMN_VERSES + " INTEGER NOT NULL DEFAULT 0"); database.execSQL("ALTER TABLE " + MythTrackContract.Items.TABLE + " ADD COLUMN " + MythTrackContract.Items.COLUMN_ESSENCE + " INTEGER NOT NULL DEFAULT 0"); database.execSQL("ALTER TABLE " + MythTrackContract.Items.TABLE + " ADD COLUMN " + MythTrackContract.Items.COLUMN_DURABILITY + " INTEGER NOT NULL DEFAULT 0"); database.execSQL("ALTER TABLE " + MythTrackContract.Items.TABLE + " ADD COLUMN " + MythTrackContract.Items.COLUMN_PARTS + " INTEGER NOT NULL DEFAULT 0"); } // 7 -> 8: Adds the titles table. case 7: { database.execSQL("CREATE TABLE " + MythTrackContract.Titles.TABLE + " (" + MythTrackContract.Titles._ID + " INTEGER PRIMARY KEY," + MythTrackContract.Titles.COLUMN_NAME + " TEXT NOT NULL," + MythTrackContract.Titles.COLUMN_DESCRIPTION + " TEXT NOT NULL," + MythTrackContract.Titles.COLUMN_MOVEMENT_POINTS + " INTEGER NOT NULL," + MythTrackContract.Titles.COLUMN_NON_COMBAT_ACTION + " INTEGER NOT NULL," + MythTrackContract.Titles.COLUMN_VITALITY + " INTEGER NOT NULL," + MythTrackContract.Titles.COLUMN_IMMUNITIES + " INTEGER NOT NULL" + ");"); } } } } }