|
| 1 | +package org.wordpress.android.editor |
| 2 | + |
| 3 | +import android.content.ContentValues |
| 4 | +import android.database.sqlite.SQLiteDatabase |
| 5 | +import android.os.Parcel |
| 6 | +import android.os.Parcelable |
| 7 | +import org.wordpress.android.util.SqlUtils |
| 8 | + |
| 9 | +object SavedParcelTable { |
| 10 | + private const val SAVED_PARCEL_TABLE = "tbl_saved_parcel" |
| 11 | + private const val PARCEL_ID = "parcel_id" |
| 12 | + private const val PARCEL_DATA = "parcel_data" |
| 13 | + fun createTable(db: SQLiteDatabase) { |
| 14 | + db.execSQL( |
| 15 | + "CREATE TABLE " + SAVED_PARCEL_TABLE + " (" |
| 16 | + + PARCEL_ID + " TEXT," |
| 17 | + + PARCEL_DATA + " BLOB," |
| 18 | + + " PRIMARY KEY (" + PARCEL_ID + ")" |
| 19 | + + ")" |
| 20 | + ) |
| 21 | + } |
| 22 | + |
| 23 | + fun dropTable(db: SQLiteDatabase) { |
| 24 | + db.execSQL("DROP TABLE IF EXISTS $SAVED_PARCEL_TABLE") |
| 25 | + } |
| 26 | + |
| 27 | + fun reset(db: SQLiteDatabase) { |
| 28 | + dropTable(db) |
| 29 | + createTable(db) |
| 30 | + } |
| 31 | + |
| 32 | + fun addParcel(writableDb: SQLiteDatabase?, parcelId: String, parcel: Parcelable) { |
| 33 | + val parcelable = ParcelableObject(parcel) |
| 34 | + val values = ContentValues() |
| 35 | + values.put(PARCEL_ID, parcelId) |
| 36 | + values.put(PARCEL_DATA, parcelable.toBytes()) |
| 37 | + writableDb?.insertWithOnConflict(SAVED_PARCEL_TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE) |
| 38 | + parcelable.recycle() |
| 39 | + } |
| 40 | + |
| 41 | + fun <T> getParcel(readableDb: SQLiteDatabase?, parcelId: String, creator: Parcelable.Creator<T>): T? { |
| 42 | + val db = readableDb ?: return null |
| 43 | + val c = db.rawQuery("SELECT * FROM $SAVED_PARCEL_TABLE WHERE $PARCEL_ID ='$parcelId'", null) |
| 44 | + return try { |
| 45 | + if (c.moveToFirst()) { |
| 46 | + val parcelableObject = ParcelableObject(c.getBlob(c.getColumnIndexOrThrow(PARCEL_DATA))) |
| 47 | + val parcelable = creator.createFromParcel(parcelableObject.getParcel()) |
| 48 | + parcelableObject.recycle() |
| 49 | + parcelable |
| 50 | + } else { |
| 51 | + null |
| 52 | + } |
| 53 | + } finally { |
| 54 | + SqlUtils.closeCursor(c) |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + private class ParcelableObject { |
| 59 | + private val parcel = Parcel.obtain() |
| 60 | + |
| 61 | + constructor(parcelable: Parcelable) { |
| 62 | + parcelable.writeToParcel(parcel, 0) |
| 63 | + } |
| 64 | + |
| 65 | + constructor(data: ByteArray) { |
| 66 | + parcel.unmarshall(data, 0, data.size) |
| 67 | + parcel.setDataPosition(0) |
| 68 | + } |
| 69 | + |
| 70 | + fun toBytes(): ByteArray { |
| 71 | + return parcel.marshall() |
| 72 | + } |
| 73 | + |
| 74 | + fun getParcel(): Parcel { |
| 75 | + parcel.setDataPosition(0) |
| 76 | + return parcel |
| 77 | + } |
| 78 | + |
| 79 | + fun recycle() { |
| 80 | + parcel.recycle() |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments