0

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

Dmi7ry
  • 1,777
  • 1
  • 13
  • 25
Srikanth Pai
  • 926
  • 3
  • 17
  • 30

3 Answers3

0

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.

HalR
  • 11,411
  • 5
  • 48
  • 80
  • I can see the databases are not created... The code to check if db exists might be wrong and thanks for the suggestions to correct it – Srikanth Pai Jun 11 '13 at 04:09
  • @HalR would you suggest me something about Sqlite. that is i want to store my chat app's messages, like all other chat apps, how can i achieve that. i tried this code but there is syntex error. my doubt is **1.** how can i create database and tables at runtime and **2** how to insert data at runtime. – Devendra Singh Nov 19 '15 at 18:39
  • @DevendraSingh This other question may help you. http://stackoverflow.com/questions/8379677/android-db-loading-chat-for-chat-application – HalR Nov 19 '15 at 20:30
0
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();
        }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sagar Maiyad
  • 12,655
  • 9
  • 63
  • 99
  • it is creating db but `syntex error` in inserting data at this line `this.insertStmt = this.myDataBase.compileStatement(INSERT);` – Devendra Singh Nov 19 '15 at 18:37
0

On this line:

private static SQLiteDatabase myDb = null;

Try removing the static modifier - the field is used as an instance object.

Nathan Adams
  • 1,255
  • 1
  • 11
  • 17