线程上的数据库操作

时间:2015-08-11 05:44:54

标签: java android multithreading

我正在开发android应用程序,它在用户启动应用程序时将一些数据存储在数据库中,它将数据从数据库提取到ArrayList,在整个应用程序生命周期中保持该ArrayList < / em>的。每当我需要更新数据时,我都会更新保存数据的数据库和ArrayList ,这种方法可以减少CPU的工作量。这里我必须通过非ui线程更新数据库,所以我需要一些建议,

1-这是一个好方法吗?

2-我有一个数据库助手类,它直接与数据库交互,我为每个表维护单独的类,与UI和数据库助手类进行通信,所以我应该在Helper类中实现什么线程或者在表中对应的类?

DbHandler

    @Override
        public void onCreate(SQLiteDatabase db) {
            FirstTable.createDatabaseTable(db);
            SecondTable.createDatabaseTable(db);
        }

 public void insertData(String tableName, ContentValues contentValues) {
        SQLiteDatabase db = getWritableDatabase();
        db.insert(tableName, null, contentValues);
        dbClose();
    }

    public Cursor readData(String tableName, String[] columns, String selection, String[]
            selectionArgs, String groupBy, String having, String orderBy, String limit) {
        SQLiteDatabase db = getWritableDatabase();
        Cursor cursor = db.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
        return cursor;
    }

    public void deleteData(String tableName, String id, NewsItem newsItem) {
        SQLiteDatabase db = getWritableDatabase();

        db.delete(tableName, id + " =?", new String[]{String.valueOf(newsItem.getmGuid())});
        dbClose();
    }


    public void updateData(String tableName, ContentValues contentValues, String where, String[] whereArgs) {
        SQLiteDatabase db = getWritableDatabase();
        db.update(tableName, contentValues, where, whereArgs);
        dbClose();
    }

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

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        FirstTable.deleteTable(db);
        SecondTable.deleteTable(db);
        onCreate(db);
    }

表格特定类

public static void createDatabaseTable(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

public static void deleteTable(SQLiteDatabase db) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}

public void createData(Data data) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_TITLE, data.getTitle());
    contentValues.put(COLUMN_LINK, data.getLink());

    DbHandler dbHandler = DbHandler.getInstance(mContext);
    dbHandler.insertData(TABLE_NAME, contentValues);
}

public ArrayList<NewsItem> readData() {
    ArrayList<Data> allData = new ArrayList<>();
    DbHandler dbHandler = DbHandler.getInstance(mContext);

    Cursor cursor = dbHandler.readData(TABLE_NAME, null, null, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            Data data = new Data();
            data.setTitle(cursor.getString(2));
            data.setLink(cursor.getString(3));
            allNewsList.add(newsItem);
        } while (cursor.moveToNext());
    }
    return allData;
}

public void deleteData(Data data) {
    DbHandler dbHandler = DbHandler.getInstance(mContext);
    dbHandler.deleteData(TABLE_NAME, ID,  data);
}

建议我好方法

1 个答案:

答案 0 :(得分:1)

是的,它的好主意是存储数据并在后台进程中维护。我想建议你做一个共同的类来处理Database&amp;表。

例如

公共类DatabaseHandler扩展了SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "demo_database";

// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
private static final String TABLE_PROINFO = "proinfo";
private static final String TABLE_RETAPROINFO = "retaproinfo";

private static final String TABLE_ATTENDANCE = "attendance";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_STUDID = "studid";
private static final String KEY_AVAILABILITY = "availability";




private final ArrayList<Bean_attendance> att_list = new ArrayList<Bean_attendance>();





public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

SQLiteDatabase db;
Cursor cursor;



// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_CATEGORY_NAME_TABLE = "CREATE TABLE " + TABLE_ATTENDANCE
            + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_STUDID + " TEXT,"
            + KEY_AVAILABILITY + " TEXT"  + ")";





    db.execSQL(CREATE_CATEGORY_NAME_TABLE);



}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed

    int upgradeTo = oldVersion + 1;
    while (upgradeTo <= newVersion) {
        switch (upgradeTo) {
        case 1:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 2:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);

            break;
        case 3:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 4:

            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 5:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 6:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 7:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 8:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 9:

            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 10:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 11:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        case 12:


            db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTENDANCE);


            break;
        }
        upgradeTo++;
    }


    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */



public void Add_Attandance(Bean_attendance contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_STUDID, contact.getStud_id());
    values.put(KEY_AVAILABILITY, contact.getAvailability());


    // Inserting Row
    db.insert(TABLE_ATTENDANCE, null, values);
    db.close(); // Closing database connection
}





public ArrayList<Bean_attendance> Get_Attandance() {
    try {
        att_list.clear();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_ATTENDANCE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Bean_attendance contact = new Bean_attendance();
                contact.setId(Integer.parseInt(cursor.getString(0)));
                contact.setStud_id(cursor.getString(1));
                contact.setAvailability(cursor.getString(2));

                // Adding contact to list
                att_list.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        cursor.close();
        db.close();
        return att_list;
    } catch (Exception e) {
        // TODO: handle exception
        Log.e("all_attandance", "" + e);
    }

    return att_list;
}







public int Update_MainAttandnce(String availble,int id) {
    String countQuery = "UPDATE " + TABLE_ATTENDANCE + " SET " + KEY_AVAILABILITY
            + " = " + "\"" + availble + "\""  + " where " + KEY_ID + "=" + "\"" + id
            + "\"";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int count = cursor.getCount();
    cursor.close();
    // return count
    return count;

}



public void Delete_Attandance_main(int id) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_ATTENDANCE, KEY_ID + "=" + id, null);
    db.close();

}

public void Attandanceremove() {
    SQLiteDatabase db = this.getWritableDatabase();
    // context.deleteDatabase(DATABASE_NAME);

    db.execSQL("delete from " + TABLE_ATTENDANCE);

    // db.delete(DATABASE_TABLE, null, null);
}

}