Aakash
Aakash

Reputation: 3171

SQLite Database creation for Android App

I am creating my SQLite database for my App at runtime if it does not exist and insert rows if it does. Since it is supposed to be created at runtime and I have implemented it by creating a subclass of SQLiteOpenHelper and overriding the onCreate() method -

"Do I need to put anything in the /assets folder of my project?"

I am not using any Content Provider "Do I need to add any tags in the AndroidManifest.xml?"

Here is what I have done. The strings have been defined properly and I do not get any runtime exceptions.

Implementation of the SQLiteOpenHelper subclass.

public class MyDB extends SQLiteOpenHelper {

                   public MyDB(Context context) {
                    super(context, DATABASE_NAME, null,  DATABASE_VERSION );
                   }

                @Override
                public void onCreate(SQLiteDatabase db) {
                db.execSQL(USERAUTH_TABLE_CREATE);
                db.execSQL(USERPREF_TABLE_CREATE); 
                }

                @Override
                public void onUpgrade(SQLiteDatabase db, int oldVersion, int 
                newVersion) {
                    Log.w("Example", "Upgrading database, this will drop tables and
                    recreate.");
                    db.execSQL("DROP TABLE IF EXISTS " +  USERAUTH_TABLE_NAME);
                    db.execSQL("DROP TABLE IF EXISTS " +  USERPREF_TABLE_NAME);
                    onCreate(db);
               }

}

Here is where I create an instance of the MyDB subclass of the SQLiteOpenHelper.

MyDB tdb = new MyDB(Activity.this); 
SQLiteDatabase db = tdb.getReadableDatabase();

Everything runs and when I go to the sqlite shell and write the following query

select * from table_name - it just tells me no such record exist. I set breakpoints and it seems after the getReadableDatabase() is called the @Override OnCreate() method is never executed which is where I execute the Create table SQLs. I have tried getWritableDatabase() as well.

I dont understand why the tables are not being created. If anyone can help that would be awesome.

Thanks.

Query Text String#1

private static final String USERAUTH_TABLE_CREATE = "CREATE TABLE " + USERAUTH_TABLE_NAME + " (" + "number INTEGER NOT NULL," + "dip TEXT NOT NULL," + "email TEXT NOT NULL," + "password TEXT NOT NULL," + "flag INTEGER" + ");" ;

Query Text String #2

private static final String USERPREF_TABLE_CREATE = 
 "CREATE TABLE " + USERPREF_TABLE_NAME + " (" +
 "tpd TEXT NOT NULL ," +
 "cat TEXT NOT NULL" + ");";

Upvotes: 2

Views: 6419

Answers (5)

Pir Fahim Shah
Pir Fahim Shah

Reputation: 10623

This simple application will create a data base and 1 table w and at the end it will

retrieve the value which u have enetered and vl show in textBox.

       SQLiteDatabase myDB= null;
        String TableName="Profile";
        String ShowData="";

        /* This function create new database if not exists. */
        try {
            myDB = openOrCreateDatabase("DataBase.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);

        /* Create a Table in the Database. */
        myDB.execSQL("CREATE TABLE IF NOT EXISTS "+ TableName + " (id INT(4),firstname VARCHAR,lastname VARCHAR);");

        /* Insert data to a Table*/
        //myDB.execSQL("INSERT INTO "+ TableName    +"(id, firstname, lastname) "+ " VALUES (1, 'Pir', 'Fahim');");
         Toast.makeText(this," DATA BASE HAVE BEEN CREATED ", Toast.LENGTH_SHORT).show();

         /*Fetch data from database table */
        Cursor c = myDB.rawQuery("SELECT* FROM " + TableName , null);

        int id = c.getColumnIndex("id");
        int fristName = c.getColumnIndex("firstname");
        int lastName = c.getColumnIndex("lastname");

        // Check result.
        c.moveToFirst();
        if (c != null) {
        // Loop through all Results
        do {
        int personId = c.getInt(id);
        String FirstName = c.getString(fristName);
        String LastName = c.getString(lastName);
        ShowData =ShowData +personId+" .) "  +FirstName+" "+LastName+"\n";

        txt.append("********************"+"\n"+personId+"\n"+FirstName+"\n"+LastName+"\n");
  // Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
        }

        while(c.moveToNext());
        }           
        // Toast.makeText(this," RESULT 2 IS = "+ ShowData, Toast.LENGTH_LONG).show();
        }
        catch(Exception e) 
        {
        Toast.makeText(this, "Error = "+e.getMessage(), Toast.LENGTH_LONG).show();
        } 
        finally 
        {
        if (myDB != null)
        myDB.close();
        }

Upvotes: 0

Aakash
Aakash

Reputation: 3171

Issue resolved. Code was working all the way once again. sqlite shell was not showing me the tables and the database. When I kept my app running on the emulator and navigated to data > data > your-package-name > databases > your-database-file using DDMS the system shows me the SQLite DB was created fine. I have checked the tables are there as well.

Thank you all guys!!

Upvotes: 0

Robert Nekic
Robert Nekic

Reputation: 3107

This might be a silly question, but have you defined the DATABASE_NAME and DATABASE_VERSION variables?

Upvotes: 0

McStretch
McStretch

Reputation: 20645

If onCreate() is not being called, then the database has already been created for your app. The quickest way to solve it is to delete your project on the emulator (Settings --> Applications --> Your application), and then restart your application. Alternatively you could use ADB to just drop your database -- it's up to you. Restarting the app after dropping the database will call onCreate() because the database does not exist, and then your table creation sql will be run. onCreate() is only called if your database DOES NOT exist (so pretty much the first time you call the database in your code.

Upvotes: 3

success_anil
success_anil

Reputation: 3658

"Do I need to put anything in the /assets folder of my project?"

No

"Do I need to add any tags in the AndroidManifest.xml?"

No

Your syntax is ok ... could you paste the query you are making for creating tables ?

Upvotes: 1

Related Questions