【发布时间】:2011-05-21 09:53:43
【问题描述】:
第一次启动应用程序后,我需要向 SQLite 数据库添加初始值。我该怎么做?
【问题讨论】:
第一次启动应用程序后,我需要向 SQLite 数据库添加初始值。我该怎么做?
【问题讨论】:
在 DBAdapter.java 类文件中你可以这样做。
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_1);
db.execSQL(CREATE_TABLE_2);
db.execSQL(CREATE_TABLE_3);
db.execSQL("insert into " + DATABASE_TABLE3 + "(" + KEY_ROWID + ","
+ KEY_DEF + ") values(1,'')");
}
喜欢这种类型。
【讨论】:
您可以创建自己的 SQLite 数据库,放入 assets 文件夹并访问它,如此链接的答案所示: adding your own SQLite database to an android application
【讨论】:
这样的一次性或首次加载要求很常见。
1) 设置一个名为 FIRSTLOAD 的标志变量并将其设置为 True。请务必将此变量保存到设备中的隔离存储中,以便在每次启动应用程序时回读。 2) 创建一个方法来检查 FIRSTLOAD 的值,并且仅在 FIRSTLOAD 为真时执行。将“将 [s] 初始值添加到 SQLite 数据库”的代码放在这里。然后将 FIRSTLOAD 变量设置为 false。这样它只会执行一次代码!
Boolean FIRSTLOAD= new Boolean("true");
void SetInitialValues()
{
if(!FIRSTLOAD)
return;
// insert your code to run only when application is started first time here
FIRSTLOAD = False;
}
【讨论】:
您应该为此使用 SQLiteOpenHelper
private static class OpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "rss.sqlite";
private static final int DATABASE_VERSION = 1;
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE RSS (TITLE TEXT, LINK TEXT, DESCR TEXT, PUBDATE DATE, GUID TEXT, READ TEXT, TYPE TEXT)");
db.execSQL("CREATE TABLE PAGE (LINK TEXT, CONTENT TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
并在代码中使用
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
【讨论】:
如果您使用 org.droidparts 库 OR-Mapper 来访问您的数据库,您可以这样做。
在你的实现中
public class CategoryEntityMgr extends EntityManager<Category> {
public CategoryEntityMgr(Context ctx) {
super(Category.class, ctx);
}
// NEW --> this one must be used in onCreateTables or you will receive a database locked exception
private CategoryEntityMgr(Context ctx, SQLiteDatabase db) {
super(Category.class, ctx, db);
}
}
在您的 AbstractDbOpenHelper 实现中:
protected void onCreateTables(SQLiteDatabase db) {
// create your tables as usual
createTables(db, Booking.class, Category.class);
// Use a new instance of your entity manager
// but use the 2nd constructor to provide the db connection
CategoryEntityMgr mgr = new CategoryEntityMgr(ctx, db);
// add the new table row / entity you an to have
Category c = new Category();
c.name = "the value for this column";
mgr.createOrUpdate(c);
}
【讨论】:
每次在应用程序中首次打开数据库时,您都应该检查数据库中的对象数量。 不要忘记用户可以释放所有数据。
//Open DataBase
MyDb.Open();
//Get All List
MyCursor = MyDb.getAllNames(); //You should have a function to get all the table data
//First Time we open Database, add default Values
if ( MyCursor.getCount() < 1 )
{
AddDefaultValuesToDataBase();
}
从这里您可以继续再次获取值。
希望对你有帮助, BR, 阿德里安。
【讨论】: