检查表是否为空,如果不是空的更新字段sqllite android?

时间:2016-01-06 08:54:54

标签: android sqlite

我正在学习sqllite for android,但我无法理解。 我像这样创建数据库处理程序:

public class DatabaseHandler extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "BookMyFitManager";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_LANGUAGE = "language";
    // Contacts Table Columns names
    private static final String LANGUAGE_ID = "languageid";
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_LANGUAGE + "("
                + LANGUAGE_ID + " INTEGER PRIMARY KEY"+ ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LANGUAGE);

        // Create tables again
        onCreate(db);
    }
    void addLanguage(String language) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(LANGUAGE_ID, language);
        // Inserting Row
        db.insert(TABLE_LANGUAGE, null, values);
        db.close();
    }
    public int updateLanguage(String language) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(LANGUAGE_ID, language);

        // updating row
        return db.update(TABLE_LANGUAGE, values, LANGUAGE_ID + " = ?",
                new String[] { String.valueOf(language) });
    }
    public boolean checkForTables(){

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " +TABLE_LANGUAGE, null);

        if(cursor != null){

            cursor.moveToFirst();

            int count = cursor.getInt(0);

            if(count > 0){
                return true;
            }

            cursor.close();
        }
        return false;
    }
}

我把它放在活动上:

DatabaseHandler db = new DatabaseHandler(this);
db.checkForTables();

但没有奏效。 基本是我创建一个切换按钮,当它打开时它发送1作为参数,当它关闭时它发送2作为参数。之后,我想将参数作为language_id发送到数据库(上面的代码addlanguage或updatelanguage上的字符串语言)。

如何检查表是否为空?如果表不空,如何更新? (来自活动)。

如何在另一项活动中调用LANGUAGE_ID?使用下面的代码?

db.openDataBase();
final String lang_id = db.getLanguageid();
db.close();

1 个答案:

答案 0 :(得分:0)

在checkForTables()里面必须是
    SQLiteDatabase db = this.getReadableDatabase();