我正在尝试在运行时创建多个数据库。用户输入数据库名称,系统必须创建它。
这是我的代码
一、Java
public class First extends Activity implements OnClickListener {
Button btnOk;
EditText inputName;
DatabaseHandler db = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db);
try {
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
initVar();
}
catch (Exception e) {
CommonUtils.postException(e, e.getMessage().toString());
}
}
private void initVar() {
try {
btnOk = (Button) findViewById(R.id.btnOk);
inputName = (EditText) findViewById(R.id.dbName);
btnOk.setOnClickListener(this);
}
catch (Exception e) {
CommonUtils.postException(e, e.getMessage().toString());
}
}
public void onClick(View v) {
if (v == btnOk ){
DBConstants.DATABASE_NAME=inputName.getText().toString().trim();
Toast.makeText(getApplicationContext(), DBConstants.DATABASE_NAME, Toast.LENGTH_LONG).show();
db = new DatabaseHandler(getApplicationContext());
db.getmyDb();
if(DatabaseHandler.doesDatabaseExist(getApplication(), inputName.getText().toString().trim())== true ){
Toast.makeText(getApplicationContext(), "DB created", Toast.LENGTH_LONG).show();
db.close();
}else{
Toast.makeText(getApplicationContext(), "DB Not created", Toast.LENGTH_LONG).show();
db.close();
}
}
}
}
数据库处理程序.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static SQLiteDatabase myDb = null;
public DatabaseHandler(Context context) {
super(context, DBConstants.DATABASE_NAME, null, DATABASE_VERSION);
}
public SQLiteDatabase getmyDb() {
if (myDb == null)
myDb = this.getWritableDatabase();
return myDb;
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public static boolean doesDatabaseExist(ContextWrapper context, String dbName) {
File dbFile=context.getDatabasePath(dbName);
return dbFile.exists();
}
在按下 OK 按钮时,我需要使用用户在 EditText 中输入的文本创建一个数据库
目前这项工作只工作一次,如果用户第二次输入不同的文本,则不会创建数据库