2
我想讓我的代碼清潔&簡單,所以我想創建數據庫,但我想通過主要活動從另一個類調用它...我試圖做到這一點,但它沒有工作...所以,它應該如何工作?如何通過主要活動課程調用數據庫(從另一個課程)?
注:我是一個在android開發新手。所以,對不起,這種類型的問題...
這是主要活動:
package com.DataStorage.Excercise;
import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
public class DataStorageActivity extends Activity {
private Context context;
public SQLiteDatabase db_1=null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AccessingDB acc= new AccessingDB(context);
acc.onCreate(db_1);
}
}
有數據庫代碼的其他類..:
package com.DataStorage.Excercise;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class AccessingDB extends SQLiteOpenHelper {
public AccessingDB(Context context) {
super(context, "Test_1", null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(CreateTable());
db.execSQL(Insert_1());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
/*
public String CreateDB_1(){
String s1= "create database Test_1;";
return s1;
}
*/
private String CreateTable(){
String s2="create table Customer(id_1 INTEGER,fn TEXT,ln TEXt);";
return s2;
}
private String Insert_1(){
String s3="insert into Customer values(1,'aaa','bbb');";
return s3;
}
}
非常感謝..
檢查此鏈接[如何從Android中的助手類初始化sqlitedatabase](http://stackoverflow.com/questions/7444327/how-to-initialize-sqlitedatabase-once-from-a-helper-class-在功能的Android/7444373#7444373)。它關於主Activity的初始化數據庫類。謝謝。 – user370305
這是一個壞主意,因爲數據庫打開需要上下文,請參閱此鏈接http://stackoverflow.com/questions/7444327/how-to-initialize-sqlitedatabase-once-from-a-helper-class-in -android/7444355#7444355 –
好的,那我該如何讓activity類擴展sqlite?它只能有一個擴展... – Q8Y