Android 使用现有数据库在sqlite中创建表
我在一个名为Player1的应用程序中创建了一个名为first.db的数据库。我想使用相同的数据库从不同的应用程序Player2创建另一个表。我还提供了从Player1到player2的相同sharedUserId。但当我尝试在AppPlayer2中创建表时,它并没有转到表的onCreate方法Android 使用现有数据库在sqlite中创建表,android,Android,我在一个名为Player1的应用程序中创建了一个名为first.db的数据库。我想使用相同的数据库从不同的应用程序Player2创建另一个表。我还提供了从Player1到player2的相同sharedUserId。但当我尝试在AppPlayer2中创建表时,它并没有转到表的onCreate方法 public static final String KEY_ID="_id"; public static final String KEY_ClIENTID="_clientid"; pub
public static final String KEY_ID="_id";
public static final String KEY_ClIENTID="_clientid";
public static final String KEY_LOCATION="_location";
public static final String KEY_MASTERDIRECTOR="_masterdirector";
public static final String KEY_IPADDRESS="_ipaddress";
public static final String KEY_SUBNETMASK="_subnetmask";
public static final String DATABASE_TABLE ="preptool";
private static final String DB_NAME = "first.db";
private static final int DB_VERSION = 1;
private DbHelper ourhelper;
private Context context;
private SQLiteDatabase ourdatabase;
public dataBase(Context sharedContext){
context = sharedContext;
}
public class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context c) {
super(c, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
System.out.println("in");
try{
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_ClIENTID + " TEXT NOT NULL, " +
KEY_LOCATION + " TEXT NOT NULL, " +
KEY_MASTERDIRECTOR + " TEXT NOT NULL, " +
KEY_IPADDRESS + " TEXT NOT NULL, " +
KEY_SUBNETMASK + " TEXT NOT NULL);");
}catch(Exception e){
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE );
onCreate(db);
}
}
public dataBase open()throws SQLException{
ourhelper = new DbHelper(context); System.out.println(context);
ourdatabase = ourhelper.getWritableDatabase();
return this;
}
public void close(){
ourhelper.close();
}
下面的代码是我在Player2应用程序中编写的,用于从Player1应用程序访问数据库:
Context sharedContext = null;
try {
sharedContext = this.createPackageContext("com.xxx.android.player1",Context.CONTEXT_INCLUDE_CODE);
if (sharedContext == null) {
return;
}
} catch (NameNotFoundException e1) {
}
db = new dataBase(sharedContext);
db.open();
我自己想:实际上,onCreate方法只有在创建新数据库时才被调用。所以,若您想在预先存在的数据库中创建表,您需要在某个地方创建表,而不是依赖onCreate方法来为您创建表。我刚刚添加了一个新方法,名为:public void createTable{ourdatabase.execsqlcreatetable if note exist preptool(如果不存在)id integer主键自动递增(如果不存在),(如果不存在)clientid text,(如果不存在)位置text(,(