SQLITE插入android oncreate块

时间:2014-10-14 17:30:58

标签: android sqlite

我有这个插入语句,它在创建方法上工作正常,但我想要的是我不想每次都在创建时运行它。我只想让它只运行一次。任何人都可以给我一些提示或解决方案。

MainActivity

public class ListConfigActivity extends Activity {    
DBAdapter myDb;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_config);

    openDB();
        myDb.insertRow("Default", "10/13/2014" , 1204, "True", "True");
}

DBAdapter.java

public class DBAdapter {

private static final String TAG = "DBAdapter";

//DB fields
public static final String KEY_config = "_idconfiguracao";
public static final String KEY_Descricao = "descricao";
public static final String KEY_DataCriacao = "data_criacao";
public static final String KEY_Usuario = "usuario";
public static final String KEY_Ativo = "ativo";
public static final String KEY_Default = "defaultconfig";

//Setup fields numbers here
public static final int COL_idConfig = 0;
public static final int COL_Descricao = 1;
public static final int COL_DataCriacao = 2;
public static final int COL_Usuario = 3;
public static final int COL_Ativo = 4;
public static final int COL_DefaultConfig = 5;

public static final String[] ALL_KEYS = new String[]
{ KEY_config, KEY_Descricao, KEY_DataCriacao, KEY_Usuario, KEY_Ativo, KEY_Default };

//DB info: name and table
public static final String DATABASE_NAME = "jornada";
public static final String DATABASE_TABLE = "configuracao";
public static final int DATABASE_VERSION = 2;

public static final String DATABASE_CREATE_SQL = 
        "create table " + DATABASE_TABLE
        + "("   +   KEY_config          + " integer primary key autoincrement, "
                +   KEY_Descricao       + " string not null, "
                +   KEY_DataCriacao     + " text not null, "
                +   KEY_Usuario         + " integer not null, "
                +   KEY_Ativo           + " string not null, "
                +   KEY_Default         + " string not null"
        + ");" ;

// context of application who uses us.
private final Context context;

private DatabaseHelper myDbHelper;
private SQLiteDatabase db;

public DBAdapter (Context ctx)
{
    this.context = ctx;
    myDbHelper = new DatabaseHelper(context);
}

// open database connection
public DBAdapter open()
{
    db = myDbHelper.getWritableDatabase();
    return this;
}

// close database connection
public void close()
{
    myDbHelper.close();
}

// add new set of values to the database
public long insertRow(String descricao, String data_criacao, int usuario, String ativo,   String defaultconfig)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_Descricao, descricao);
    initialValues.put(KEY_DataCriacao, data_criacao);
    initialValues.put(KEY_Usuario, usuario);
    initialValues.put(KEY_Ativo, ativo);
    initialValues.put(KEY_Default, defaultconfig);
    Log.i("Insert record", initialValues.toString());
    return db.insert(DATABASE_TABLE, null, initialValues);
}

public boolean updateRow(long configID, String descricao, String data_criacao, int usuario, String ativo, String defaultconfig)
{
    String where = KEY_config + "=" + configID;

    ContentValues newValues = new ContentValues();
    newValues.put(KEY_Descricao, descricao);
    newValues.put(KEY_DataCriacao, data_criacao);
    newValues.put(KEY_Usuario, usuario);
    newValues.put(KEY_Ativo, ativo);
    newValues.put(KEY_Default, defaultconfig);

    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}

private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading application's database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data!");

        // Destroy old database:
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        // Recreate new database:
        onCreate(_db);
    }
}

}

2 个答案:

答案 0 :(得分:0)

我想知道你为什么要这样做,但这是一个使用preferences的想法:

   public class ListConfigActivity extends Activity {    
    DBAdapter myDb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_config);

    if(getIsDataInserted(getApplicationContext())){
           Toast.makeText(getApplicationContext(),"Row Already Inserted!", 1).show();
    }else{
        openDB();
        myDb.insertRow("Default", "10/13/2014" , 1204, "True", "True");
        setIsDataInserted(getApplicationContext(), true); //Data inserted !
        Toast.makeText(getApplicationContext(),"Row Inserted!", 1).show();
    }
  }

添加方法,设置一个布尔值,表示插入的行(true),另一个用于获取值(true或false)

public static void setIsDataInserted(Context context, boolean data){
    context.getSharedPreferences("PREFS_SYSTEM", MODE_PRIVATE).edit().putBoolean("insert_data", data);
}   

public static boolean getIsDataInserted(Context context){       
    return context.getSharedPreferences("PREFS_SYSTEM", MODE_PRIVATE).getBoolean("insert_data", false);
}

我认为您也会使用按钮执行此操作,或使用emerssso建议的方法

@Override
public void onCreate(SQLiteDatabase _db) {
    _db.execSQL(DATABASE_CREATE_SQL);
    _db.execSQL(DATABASE_INSERT_ROW); //Insert the row only when the database is created.
}

答案 1 :(得分:0)

如果您想要的是将该行恰好插入一次,我会考虑将其作为数据库创建方法的一部分:DBAdapter::onCreate()。只需添加另一个带有插入SQL语句的_db.execSQL即可插入行。这样,此行将仅添加到数据库一次。然后会读

@Override
public void onCreate(SQLiteDatabase _db) {
    _db.execSQL(DATABASE_CREATE_SQL);
    _db.execSQL(DATABASE_ADD_DEFAULT_ROW);
}

或者,假设我正确理解了您的代码,您可以使用与在Activity的onCreate中完全相同的调用:

@Override
public void onCreate(SQLiteDatabase _db) {
    _db.execSQL(DATABASE_CREATE_SQL);
    _db.insertRow("Default", "10/13/2014" , 1204, "True", "True");
}

编辑:@superfell在评论中正确指出您必须删除现有数据库才能再次调用此onCreate方法。您可以通过从测试设备/模拟器手动卸载应用程序来轻松实现此目的。