这是我第一次开发Android应用程序。我正在尝试编写一个能够将csv文件导入android sqlite本地数据库的应用程序。 这是我目前的设计:
我想问一下我是否应该尝试使用onUpgrade函数来替换我的步骤1,2。我在更新DATABASE_VERSION方面做了一些研究。如果我更新DATABASE_VERSION的值,将调用onUpgrade并且可以完成相同的功能。使用onUpgrade和我的编码有什么区别?哪一个更好?
P.S。请注意,此按钮每天会按一次。
这是我的编码:
主要活动
button_import_csv.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
DatabaseHelper helper = new DatabaseHelper(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_1);
String CREATE_TB;
CREATE_TB = "CREATE TABLE adv_sales_order ("
+ "order_date text not null, "
+ "cust_code text not null, "
+ "customer_ref_no text, "
+ "line_no integer not null, "
+ "item_code text not null, "
+ "tran_code text not null, "
+ "order_qty real not null, "
+ "constraint pk_adv_sales_order "
+ "primary key (order_date, "
+ "cust_code, "
+ "item_code, "
+ "tran_code))";
db.execSQL(CREATE_TB);
try{
FileReader file = new FileReader("/sdcard/downloadedfolder/A1/adv_sales_order.csv");
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues=new ContentValues();
String line = "";
String tableName ="adv_sales_order";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split("\t");
contentValues.put("order_date", str[0]);
contentValues.put("cust_code", str[1]);
contentValues.put("customer_ref_no", str[2]);
contentValues.put("line_no", str[3]);
contentValues.put("item_code", str[4]);
contentValues.put("tran_code", str[5]);
contentValues.put("order_qty", str[6]);
db.insert(tableName, null, contentValues);
}
db.setTransactionSuccessful();
db.endTransaction();
}catch (IOException e){
}
helper.close();
}
});
DatabaseHelper
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TB;
CREATE_TB = "CREATE TABLE adv_sales_order ("
+ "order_date text not null, "
+ "cust_code text not null, "
+ "customer_ref_no text, "
+ "line_no integer not null, "
+ "item_code text not null, "
+ "tran_code text not null, "
+ "order_qty real not null, "
+ "constraint pk_adv_sales_order "
+ "primary key (order_date, "
+ "cust_code, "
+ "item_code, "
+ "tran_code))";
db.execSQL(CREATE_TB);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_1);
onCreate(db);
}
public void insert_adv_sales_order (ContentValues values) {
SQLiteDatabase db = getWritableDatabase();
db.insert("adv_sales_order", null, values);
db.close();
}