我创建了一个数据库并使用下面的代码我将值插入到数据库中。代码工作正常。
问题是因为代码在onCreate方法中。每次我调用活动时,都会一次又一次地插入数据。
我希望这只在我调用活动时第一次插入值。
有什么方法可以做到。谢谢。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_db_result);
Dbhandler dbhand = new Dbhandler(this);
kovil insertData1 = new kovil("Murugan Kovil", "Murugan", "9.6680077",
"80.0147083", "image_name", "year_build",
"address", "city", "email", "website",
"telephone1", "telephone2", "Description");
kovil insertData2 = new kovil("Murugan Kovil", "Murugan", "9.6661814",
"80.014883", "image_name2", "year_build2",
"address2", "city2", "email2", "website2",
"telephone12", "telephone22", "Description2");
kovil insertData3 = new kovil("Murugan Kovil", "Murugan", "9.6621890",
"80.0131851", "image_name3", "year_build3",
"address3", "city2", "email2", "website2",
"telephone12", "telephone22", "Description2");
ArrayList<kovil> arrayList = new ArrayList<kovil>();
arrayList.add(insertData1);
arrayList.add(insertData2);
arrayList.add(insertData3);
for (int i=0; i<arrayList.size(); i++) {
dbhand.Add_Temple(arrayList.get(i));
};
}
答案 0 :(得分:4)
数据库设置(例如使用默认数据填充表格)最好放在SQLite open helper onCreate()
中。它只在首次创建数据库时调用一次。
答案 1 :(得分:2)
只需在你的onCreate方法中使用一个查询(一个简单的“来自MyTable的SELECT Count(*)将会这样做)来告诉你记录数是否为0。
如果是,请继续插入。
答案 2 :(得分:2)
这是一种只能在第一次执行代码的方法:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs.getBoolean("FirstTime", false)) {
//code that is to be executed every time
}else{
// code to be executed only once the first time the app is run
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("FirstTime", true);
editor.commit();
}