在Android中使用SyncAdapter中的DbHandler

时间:2017-12-10 23:29:00

标签: android sqlite synchronization android-syncadapter

我正在Android Studio中构建应用程序,并在MainActivity内部我实例化一个DbHandler(继承自SQLiteOpenHelper)类,负责处理SQLite数据库。当然,在它的onCreate方法中,它创建了模式和内容:

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    String CREATE_WORD_TABLE = "CREATE TABLE " + WordDbContract.WordTable.TABLE_NAME + "("
                + WordDbContract.WordTable.COLUMN_WORD_ID + " INTEGER, " + WordDbContract.WordTable.COLUMN_WORD_TITLE + " TEXT, "
                + WordDbContract.WordTable.COLUMN_WORD_TRANSLATION + " TEXT);";


       sqLiteDatabase.execSQL(CREATE_WORD_TABLE);
}

我也在使用我使用官方安卓指南开发的SyncAdapter,它确实被触发了。现在在这个SyncAdapter的onPerformSync方法中,我想与我的SQLite数据库进行一些交易(插入,更新等)

鉴于适配器和主活动是两个独立的进程,当我尝试在DbHandler内实例化onPerformSync时,会导致创建两个单独的SQLite数据库。

我的另一个想法是将MainActivity中的DbHandler声明为public static,因此SyncAdapter可以使用它;但是这会导致未知的运行时错误。

我想知道实现这一目标的最佳做法是什么;在SyncAdapter的同步方法中操作数据库?

1 个答案:

答案 0 :(得分:-1)

公共类DBHandler扩展了SQLiteOpenHelper {

public DBHandler(Context context) {
    super(context, "user_db", null, 1);

}

@Override
public void onCreate(SQLiteDatabase db) {

    String createQuery = "CREATE TABLE "+UserProfile.Users.TABLE_NAME +"( "+UserProfile.Users.COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT ,"+UserProfile.Users.COL_USERNAME+" TEXT UNIQUE," +
            UserProfile.Users.COL_PASSWORD +" TEXT, "+UserProfile.Users.COL_GENDER +" TEXT, "+UserProfile.Users.COL_DOB +" TEXT"+")";

    Log.d("createQuery",createQuery);

    try {
        db.execSQL(createQuery);
    }
    catch (Exception e){
        e.printStackTrace();
        Log.e("Exception",e.getMessage());
    }

}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    String createQuery = "CREATE TABLE "+UserProfile.Users.TABLE_NAME +"( "+UserProfile.Users.COL_ID +" INTEGER PRIMARY KEY AUTO INCREMENT ,"+UserProfile.Users.COL_USERNAME+" TEXT," +
            UserProfile.Users.COL_PASSWORD +" TEXT, "+UserProfile.Users.COL_GENDER +" TEXT, "+UserProfile.Users.COL_DOB+" TEXT"+")";

    Log.d("createQuery",createQuery);

    try {
        db.execSQL(createQuery);
    }
    catch (Exception e){
        e.printStackTrace();
        Log.e("Exception",e.getMessage());
    }


}

public boolean addInfo(UserProfile.Users users){

    SQLiteDatabase db = this.getWritableDatabase();

    String insertQuery = "INSERT INTO "+UserProfile.Users.TABLE_NAME+"("+UserProfile.Users.COL_USERNAME+","+UserProfile.Users.COL_PASSWORD+","+UserProfile.Users.COL_GENDER+","+
            UserProfile.Users.COL_DOB+") VALUES('"+users.getUsername()+"','"+users.getPassword()+"','"+users.getGender()+"','"+users.getDob()+"')";

    Log.d("insertQuery",insertQuery);

    try {
        db.execSQL(insertQuery);
        return true;
    }
    catch (Exception e){
         e.printStackTrace();
         Log.d("Exception",e.getMessage());
    }

    db.close();
    return false;
}

public boolean updateInfor(UserProfile.Users users){

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    String username = users.getUsername();
    String password = users.getPassword();
    String dob = users.getDob();
    String gender = users.getGender();
    int id = users.getId();
    values.put(UserProfile.Users.COL_DOB,dob);
    values.put(UserProfile.Users.COL_GENDER,gender);
    values.put(UserProfile.Users.COL_PASSWORD,password);
    values.put(UserProfile.Users.COL_USERNAME,username);

    int result = db.update(UserProfile.Users.TABLE_NAME,values,UserProfile.Users.COL_ID+" = ?",new String[]{String.valueOf(id)});

    if(result >0)
        return true;

    return false;
}


public ArrayList<UserProfile.Users> readAllInfor(){

    ArrayList<UserProfile.Users> userList = new ArrayList<>();

    SQLiteDatabase db = this.getWritableDatabase();

    String readAllQuery = "SELECT * FROM "+UserProfile.Users.TABLE_NAME;

    Cursor cursor = db.rawQuery(readAllQuery,null);

    if(cursor.moveToFirst()){
        do{
            UserProfile.Users users = UserProfile.getProfile().getUser();

            users.setId(Integer.parseInt(cursor.getString(0)));
            users.setUsername(cursor.getString(1));
            users.setPassword(cursor.getString(2));
            users.setGender(cursor.getString(3));
            users.setDob(cursor.getString(4));

            userList.add(users);

        }while (cursor.moveToNext());
    }

    return userList;

}

public UserProfile.Users readAllInfor(String userName){

    SQLiteDatabase db = this.getWritableDatabase();

    String readSingleQuery = "SELECT * FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_USERNAME + " =  '"+ userName+"'";

    Cursor cursor = db.rawQuery(readSingleQuery,null);

    if(cursor.moveToFirst()){

        UserProfile.Users users = UserProfile.getProfile().getUser();

        users.setId(Integer.parseInt(cursor.getString(0)));
        users.setUsername(cursor.getString(1));
        users.setPassword(cursor.getString(2));
        users.setGender(cursor.getString(3));
        users.setDob(cursor.getString(4));

        return users;
    }

   return null;
}

public UserProfile.Users readAllInfor(int id){

    SQLiteDatabase db = this.getWritableDatabase();

    String readSingleQuery = "SELECT * FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_ID + " =  '"+ id+"'";

    Cursor cursor = db.rawQuery(readSingleQuery,null);

    if(cursor.moveToFirst()){

        UserProfile.Users users = UserProfile.getProfile().getUser();

        users.setId(Integer.parseInt(cursor.getString(0)));
        users.setUsername(cursor.getString(1));
        users.setPassword(cursor.getString(2));
        users.setGender(cursor.getString(3));
        users.setDob(cursor.getString(4));

        return users;
    }

    return null;
}



public void deleteInfo(String username){

    SQLiteDatabase db = this.getWritableDatabase();

    String deleteQuery = "DELETE FROM "+ UserProfile.Users.TABLE_NAME+" WHERE "+ UserProfile.Users.COL_USERNAME +" = '"+ username +"' ";
    Log.d("deleteQuery ",deleteQuery);
    db.execSQL(deleteQuery);
    db.close();
}

}