Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to Create Sqlite database with Tables [duplicate]

I need to create a database with 3 tables and I am doing this like below:

public class DatabaseUtils extends SQLiteOpenHelper {
      private final Context myContext;  
      private SQLiteDatabase DataBase; 

      // Database creation sql statement
      private static final String CREATE_TABLE_CS = "create table "+ TABLE_CS + "(" + COLUMN_CS + " TEXT NOT NULL, " + COLUMN_CE_CID + " INTEGER NOT NULL, "+ COLUMN_CE_PID +" INTEGER NOT NULL);";
      private static final String CREATE_TABLE_SS = "create table "+ TABLE_SS + "(" + COLUMN_SS + " TEXT NOT NULL, " + COLUMN_SUB_CID + " INTEGER NOT NULL, "+ COLUMN_SUB_PID +" INTEGER NOT NULL);";
      private static final String CREATE_TABLE_AS = "create table "+ TABLE_AS + "(" + COLUMN_AS + " TEXT NOT NULL, " + COLUMN_CID + " INTEGER NOT NULL, "+ COLUMN_AID +" INTEGER NOT NULL);";

      public DatabaseUtils(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        DATABASE_PATH =  Environment.getDataDirectory().getAbsolutePath() + "/" +"data/"+ context.getResources().getString(R.string.app_package);
        this.myContext = context;
      }

      @Override
      public void onCreate(SQLiteDatabase database) {
        database.execSQL(CREATE_TABLE_CS);
        database.execSQL(CREATE_TABLE_SS);
        database.execSQL(CREATE_TABLE_AS);
      }
      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(DatabaseUtils.class.getName(),"Upgrading database from version " + oldVersion + " to "+ newVersion + ", which will destroy all old data");
        //db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
        onCreate(db);
      }
}

and in my Activity I am calling DatabaseUtils class in onCreate as below:

DatabaseUtils db = new DatabaseUtils(this);

but Database is not creating with the 3 tables. What am I doing wrong? BTW, I have all the string values correctly. Please help me how to create database.

like image 828
user2326860 Avatar asked Jan 27 '26 19:01

user2326860


1 Answers

I found the solution. DatabaseUtils' onCreate() is never called if i implement like below:

 DatabaseUtils db = new DatabaseUtils(this);

in myActivity's onCreate() method. I need to call getWritableDatabase() in myActivity as below:

DatabaseUtils db = new DatabaseUtils(this);
db.getWritableDatabase();

Then DatabaseUtils' onCreate() will be called and tables are created.

like image 167
user2326860 Avatar answered Jan 30 '26 09:01

user2326860



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!