问题
I am trying to create multiple databases at runtime. The user enter the database name and the system must create it.
here is my code
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
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();
}
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
回答1:
I suspect that it is making your database. You are just mistaken when you check to see if it has been created.
This line from your onClick method:
db.getmyDb();
will always return the first database, because it calls this:
public SQLiteDatabase getmyDb() {
if (myDb == null)
myDb = this.getWritableDatabase();
return myDb;
}
which, when called the first time, sets myDb to be the first database, and from then on, always returns that value.
You are going to need to set up an index of databases, and track your databases in an array.
回答2:
On this line:
private static SQLiteDatabase myDb = null;
Try removing the static modifier - the field is used as an instance object.
回答3:
public void createDynamicDatabase(Context context, String tableName, ArrayList<String> title) {
Log.i("INSIDE createLoginDatabase() Method","*************creatLoginDatabase*********");
try {
int i;
String queryString;
myDataBase = context.openOrCreateDatabase("Db", Context.MODE_WORLD_WRITEABLE, null); //Opens database in writable mode.
//System.out.println("Table Name : "+tableName.get(0));
queryString = title.get(0)+" VARCHAR(30),";
Log.d("**createDynamicDatabase", "in oncreate");
for(i = 1; i < title.size() - 1; i++)
{
queryString += title.get(i);
queryString +=" VARCHAR(30)";
queryString +=",";
}
queryString+= title.get(i) +" VARCHAR(30)";
queryString = "CREATE TABLE IF NOT EXISTS " + tableName + "("+queryString+");";
System.out.println("Create Table Stmt : "+ queryString);
myDataBase.execSQL(queryString);
} catch (SQLException ex) {
Log.i("CreateDB Exception ",ex.getMessage());
}
}
public void insert(Context context, ArrayList<String> array_vals, ArrayList<String> title, String TABLE_NAME) {
Log.d("Inside Insert","Insertion starts for table name: "+TABLE_NAME);
myDataBase = context.openOrCreateDatabase("Db",Context.MODE_WORLD_WRITEABLE, null); //Opens database in writable mode.
String titleString = null;
String markString = null;
int i;
titleString = title.get(0)+",";
markString = "?,";
Log.d("**createDynamicDatabase", "in oncreate");
for(i = 1; i < title.size() - 1; i++)
{
titleString += title.get(i);
titleString +=",";
markString += "?,";
}
titleString+= title.get(i);
markString += "?";
//System.out.println("Title String: "+titleString);
//System.out.println("Mark String: "+markString);
INSERT="insert into "+ TABLE_NAME + "("+titleString+")"+ "values" +"("+markString+")";
System.out.println("Insert statement: "+INSERT);
//System.out.println("Array size iiiiii::: "+array_vals.size());
//this.insertStmt = this.myDataBase.compileStatement(INSERT);
int s=0;
while(s<array_vals.size()) {
System.out.println("Size of array1"+array_vals.size());
// System.out.println("Size of array"+title.size());
int j=1;
this.insertStmt = this.myDataBase.compileStatement(INSERT);
for(int k =0;k< title.size();k++)
{
//System.out.println("Value of column "+title+" is "+array_vals.get(k+s));
//System.out.println("PRINT S:"+array_vals.get(k+s));
System.out.println("BindString: insertStmt.bindString("+j+","+ array_vals.get(k+s)+")");
insertStmt.bindString(j, array_vals.get(k+s));
j++;
}
s+=title.size();
}
insertStmt.executeInsert();
}
来源:https://stackoverflow.com/questions/17035834/create-sqlite-db-on-runtime