3

In my application activity was running fine but database is not getting created also there is no error in logcat. Main activity class:

package com.example.testdb;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Database d=new Database(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Database class:

package com.example.testdb;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

public class Database extends SQLiteOpenHelper{

    String Tablename = "Table1";
    private String Column1 = "RegionID";
    private String Column2 = "RegionName";
    private String Column3 = "Currency";
    SQLiteDatabase db;

    public Database(Context context) {
        super(context, "Test", null, 2);
        this.getWritableDatabase();
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        try {
            final String r_Table = "CREATE TABLE " + Tablename + " (" + Column1+ " INTEGER PRIMARY KEY , " + Column2 + " TEXT, " + Column3 + " Text) ";
            db.execSQL(r_Table);
            ContentValues cv = new ContentValues();
            cv.put(Column1, 1);
            cv.put(Column2, "India");
            cv.put(Column3, "Rupee");
            db.insert(r_Table, null, cv);
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }

        Cursor c = db.rawQuery("Select * from Table1", null);

        if (c != null ) {
            if  (c.moveToFirst()) {
                //Toast.makeText(new MainActivity().getApplicationContext(), c.getCount(), Toast.LENGTH_LONG).show();
                System.out.println("Rows are:"+c.getCount());
            }
        }
        c.close();  
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
    }
}

Logcat:

05-18 12:45:22.042: I/ActivityThread(3270): Switching default density from 160 to 130
05-18 12:47:18.162: I/ActivityThread(3415): Switching default density from 160 to 130

I am using Virtual box for emulator and in DDMS I can't even see the database got created.

Can anyone please help me in this.

Thanks in advance Siva

8
  • Are you sure you have the sufficient rights to see the DB in DDMS? Try to use ADB shell to check if the DB exists or not in your application folder. Commented May 18, 2013 at 13:02
  • try to run after remove this.getWritableDatabase(); this line from your database constructor. Commented May 18, 2013 at 13:04
  • Thanks Gunaseelan.. but where to add the getwritabledatabase? one more thing while debug I noticed control not going to "Oncreate" of database class Commented May 18, 2013 at 13:06
  • Thanks Yoann. How to use ADB shell can you please eloborate Commented May 18, 2013 at 13:07
  • I have tested the code and the database gets created. So the code is correct. Commented May 18, 2013 at 13:08

3 Answers 3

2

According to documentation SqliteOpenHelper uses lazy model of creating databases. This means, that in the absence of database, onCreate will be called not in constructor, but when the database is actually needed, I.e. at the first call to getReadableDatabase or getWritableDatabase. So, you situation is normal.

Think of SqliteOpenHelper as provider of connection to database, containing additional logic for handling situations like "if database not exist" and "if database is outdated". Thus, in your case, don't worry about when database file is actually created.

Database usage in your Activity (if it is the only one, using db) could be something like:

private SqliteOpenHelper connection;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.OnCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    connection = new Database(this); //no actual db creation here
    //if you want to test db table creation without any further work uncomment following line
    //SQLiteDatabase db = connection.getReadableDatabase();
}

public void onBtnAddRecordClick(View view) {
    SqliteDatabase db = connection.getWritableDatabase(); //if something not right with
                                                  //the db this will be corrected here
    ContentValues values;
    //... fill in the record to insert
    db.insert(MY_TABLE_NAME, null, values);
}

Important note: If you are going to access you db from multiple Activities, consider making your Database extending SqliteDatabaseHelper a singleton or wrap it into a ContentProvider, because it is generally frowned upon to use multiple connections to a database without a clear purpose.

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for your reply Alexei. I am still confused. It means if database exists then oncreate willnot be called. Is that right? In this case if how can we carry on database operations, Can you please share your thoughts
You are right, onCreate is called only once. The flow of operation is following: when you want to,say, query database you call getReadableDatabase. This function first checks the existence of database. If db is absent, empty database is created and onCreate handler called. Then version of database is checked against your current version. If database is outdated onUpgrade handler is called and version number updated. When, finally database exists and is up to date getReadableDatabase returns database object of guaranteed validity. Now you are free to do your queries.
I mean, that all database operations are performed with database objects returned by getReadable/writableDatabase. The SqliteOpenHelper descendants contains only logic of setting up/upgrading permanent database tables. It is Open Helper and frees you from calling "if not table exists" stuff.
Thanks for your reply alexei. These are some of the points I am summing up.1. Since oncreate is called only once our "Readable or writable" database should be written in constructor. 2. If database is removed or deleted then again oncreate is called
Alexei.. Is it compulsory to write "if not table exists" for table create statements?.. Can you please eloborate of this also can you give me some idea on where to close the database.
|
0

I guess db.insert(r_Table, null, cv); is wrong. First argument r_Table should be Tablename.

1 Comment

Thanks morodomi.. good catch changed the name but still result is same
0

Change the line

final String r_Table = "CREATE TABLE " + Tablename + " (" + Column1+ " INTEGER PRIMARY KEY , " + Column2 + " TEXT, " + Column3 + " Text) ";

to

final String r_Table = "CREATE TABLE " + Tablename + " (" + Column1+ " INTEGER PRIMARY KEY , " + Column2 + " TEXT, " + Column3 + " Text);";

1 Comment

Thanks for your reply Anirudha. I have changed accordingly still there is problem I am not getting why control is not going to oncreate. If you have any idea can you please share.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.