在运行时创建SQLite的分贝 [英] Create SQlite Db on runtime
本文介绍了在运行时创建SQLite的分贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在运行时创建多个数据库。用户输入数据库名和系统必须创建它。
I am trying to create multiple databases at runtime. The user enter the database name and the system must create it.
这是我的code
First.Java
First.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();
}
}
}
}
DatabaseHandler.java
DatabaseHandler.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按钮的preSS我需要创建一个由该的EditText用户输入的文本数据库
On the press of OK button I need to create a database with the text entered by the user in the EditText
目前这项工作只有一次,如果用户输入一个不同的文本第二次,数据库未创建
currently this work only once, if the user enters a different text the second time, the database is not created
推荐答案
在这一行:
private static SQLiteDatabase myDb = null;
尝试删除static修饰符 - 场被用作一个实例对象
Try removing the static modifier - the field is used as an instance object.
这篇关于在运行时创建SQLite的分贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文