Android SQLiteOpenHelper: Why onCreate() method is not called? - java

I am trying to make my first Android app. I noticed that the SQLiteOpenHelper.onCreate() method is not called to create tables if the database not exists. However, the onCreate() method did not work even thought I tried to debug.
Please look at the code below and give me any suggestions. Any help will be appreciated.
public class NameToPinyinActivity extends Activity {
DatabaseOpenHelper helper = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nametopinyin);
Button searchButton = (Button) findViewById(R.id.search);
searchButton.setOnClickListener(new ButtonClickListener());
helper = new DatabaseOpenHelper(NameToPinyinActivity.this);
}
public class DatabaseOpenHelper extends SQLiteOpenHelper {
/** DB Name */
private static final String DB_NAME = "pinyin";
/** CREATE TABLE SQL */
private static final String CREATE_TABLE_SQL = "CREATE TABLE UNICODE_PINYIN"
+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "UNICODE TEXT NOT NULL, PINYIN TEXT NOT NULL)";
public DatabaseOpenHelper(Context context) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.beginTransaction();
try {
db.execSQL(CREATE_TABLE_SQL);
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
}

I have also had trouble with the SQLiteOpenHelper. What worked for me was storing a member variable
SQLiteDatabase db;
In the SQLiteOpenHelper subclass and calling
db = getWritableDatabase();
in the constructor.
The answer to this question also includes helpful information: SQLiteOpenHelper failing to call onCreate?
I hope this helps!

Until you call the method getWritableDatabase() or getReadableDatabase() of SQLiteOpenHelper class, database won't be created.
as simple as that database will be created in memory when you actually need that.:)

I had a similar problem where onCreate wasn't executed. Maybe this is of any use for someone even though it turned out being a different problem.
I was working on the database before and had already created one long time before. So now after making changes in onCreate() I was hoping to find the new tables created. But the SQLiteOpenHelper never called onCreate() again. Reason was, the database already existed. I was still working with the same device as before and consequently with the already existing (old) databse.
But there is hope. When the system sees a database with that name already exists, it also checks whether the version number is correct. In that case I simply forgot the database already existed. My solution was simply changing the version number. So onUpgrade() was called offering options for onCreate() changes.
So options were either uninstalling the complete app (and with it the database) or call onCreate again after upgrading the version number (and for example dropping) the old table and calling onCreate() again.
In any case, if onCreate() is not called, check twice if the database exists. Otherwise it's not called again.

I had a similar problem however it was not the OnCreate call that was the issue.
In the example code above, Kevin explained that the OnCreate is not called if the database already exists. However if, like me, you are using multiple tables from separate activities, then though you may have created the database already, the table associated with this activity may yet have not been created. Hence when you attempt to set the cursor data on a non-existent table, you will invoke an exception.
My solution was define a separate class called CreateTable which is called both from the OnCreate override and from the constructor after the
db = getWritableDatabase();

Call getWritableDatabase(); in the constructor
public DataBaseH(#Nullable Context context) {
super(context, dataBaseName, null, dataBaseVersion);
SQLiteDatabase db=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable="CREATE TABLE IF NOT EXISTS "+tableName+ " ( "+
id+ " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"+
name+ " TEXT,"+
familyName+ " TEXT,"+
age+ " INTEGER);";
db.execSQL(createTable);
Log.i(TAG,"db.exect");
}

I was having a similar problem with onCreate() not executing when the app was very first run, so my database never got created. This is NOT the same as when onCreate() is not executing because the database already existed, because the database did not yet exist. Specifically, my DataProvider onCreate() was not executing, so the OpenHelper never got called either.
I verified I had everything set up the way that everyone described in the previous answers, but nothing resolved my problem. Posting this answer in case anyone else forgets one small detail like I did.
What resolved the problem for me was adding a entry in AndroidManifest.xml for my Data Provider, nested inside the tags, along with all of my entries. The only attributes I needed were:
android:name=".DataManagement.DbDataProvider"
android:authorities="com.example.myApplicationName.DataManagement.DbDataProvider"
android:exported="false"
(Make sure to change the values for the above attributes to match your project)
I cleaned, built, ran, and onCreate() methods for the data provider and open helper classes executed properly, and the database was created on first application launch!

I had the same problem.. the resolution for me was to add .db as extension of the database name

In my case, it was not being called because the database already existed! So, if possible, make sure to delete your app and install it back and only then check if it is being called or not.

I had the same problem where it seemed that the onCreate was not executed. I thought so because my logs were not displayed. Turned out that there was something wrong with the blank spaces in my SQL_create String.
#Override
public void onCreate(SQLiteDatabase db) {
try {
Log.d(LOG_TAG, "A table is created with this SQL-String: " + SQL_CREATE + " angelegt.");
db.execSQL(SQL_CREATE);
}
catch (Exception ex) {
Log.e(LOG_TAG, "Error when creating table: " + ex.getMessage());
}
}
This is my corrected SQL-String:
enterpublic static final String SQL_CREATE =
"CREATE TABLE " + TABLE_VOCAB_LIST +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_GERMAN + " TEXT NOT NULL, " +
COLUMN_SPANISH + " INTEGER NOT NULL, "+
COLUMN_LEVEL + " INTEGER NOT NULL);)"; code here
I had forgotten one blank space and when I added it everything worked fine.

You can change AUTOINCREMENT to AUTO INCREMENT
Note
SQLiteOpenHelper Called onCreate when the database is created for the first time. If you create table in onCreate method you can't create new SQLiteDatabase. You can see example
#Override
public void onCreate(SQLiteDatabase db) {
String stringCreateTable = "CREATE TABLE "+"tblUser"+" ( " +
"id TEXT PRIMARY KEY, " +
"name TEXT )";
db.execSQL(stringCreateTable);
}

Related

How to insert values in database from Adapter class to fragment dialog class?

I created an adapter class in which
onClick method I'm calling a DialogFragment extended class like
if (!item.getNext().equals("0")) {
fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
AddonDialogFragment postalFragment = AddonDialogFragment.newInstance(Integer.valueOf(item.getNext()));
postalFragment.show(fragmentManager, "AddonDialogFragment");
}
I'm calling here a fragment dialog class. In Adapter class I made one interface. my interface code is also working fine but when i'm trying to insert data in sqlite database , my code is not working.
#Override
public void getItemFromAddon(String addonName, String addonId, String addonPrice) {
dbInsert(addonName, addonPrice, addonId, hashmapHead);
}
public void dbInsert(String addonName,String addonPrice,String addonId,String hashmapHead){
Log.e(TAG, "dbInsert: " );
databaseHelper = new CartDatabaseHelper(getContext());
databaseHelper.setAddons(addonName, addonPrice, addonId, hashmapHead);
Log.e(TAG, "getItemFromAddon: " + addonName + " " + addonId + " " + addonPrice + " " + hashmapHead);
}
In log i'm successfully getting dbInsert but after that code is not working.
Can any one please tell me what is the error or did i mistaken anywhere?
Thanks in advance
Maybe when you call databaseHelper = new CartDatabaseHelper(getContext()); the getContext() returns null. Can you post your code of CartDatabaseHelper?
In databaseHelper I was getting null value. When I debug my program i got that. Simply defined the object static and got what I was looking for.
static MyDatabaseHelper databaseHelper;
and in onCreate method
databaseHelper = new MyDatabaseHelper(getContext());

Clear sqlite database at a certain point of an application

I want to clear my SQLite db every time I hit a particular spot in my application.
I intended on just making a method that I could call called resetTables(), but this seems to be more challenging than I expected because I don't really know where to place it. Here is a snippet.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
public void reset(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
}
I'm getting a yellow line under reset and I can't call this method in my code. Any ideas?
Note this question is similar, but couldn't get it to help me.
This worked:
public void resetTables(){
mDb.delete(TABLE_NAME, null, null);
}
first create one method where you create your database and table.
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_NAME, null, null);
db.close();
}
and call above method using on your button click event.
i have done it by this way...
#Override
public void onOpen(SQLiteDatabase db) {
// TODO Auto-generated method stub
super.onOpen(db);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
}
and yes it definitely worked for me..:)

using method from other activity in Java ( android )

I have a conundrum, I do know how to call method from other activity.. crating object etc..
But I have dbHelper.java that deal with creating sql little tables etc and start like:
public class dbHelper extends SQLiteOpenHelper {
.
.
.
}
it works fine but i have method there that check when the DB version change and recreate DB tables etc..
like:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// pri zmene verzie DB dropne tabulku
Log.w("DATA", "Upgrading database from version " + oldVersion + " to " + newVersion);
db.execSQL("DROP TABLE IF EXISTS plan");
db.execSQL("DROP TABLE IF EXISTS contacts");
this.onCreate(db);
}
but I need to store also shared preference that I use to tell application that its new start... however its kind of strange i try :
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCE_FILENAME,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("FS", "1");
editor.commit();
But MODE_PRIVATE get underlined as error, even when I try call method from other activity creating object like this for example: dataManager db = new dataManager(this); where is method to store shared preference I get still underlined it as error...
Any idea what might be the issue ? I'm learning java but still no idea :-/
Vlad
MODE_PRIVATE is a constant which is declared in Context class. Just change MODE_PRIVATE to Context.MODE_PRIVATE
This works fine inside the Activity's method, cause' Activity is a subclass of Context

"No Such Table" Error found in SQLite Android

I am trying to learn about SQLite databases, but I really hate dealing with any back-end stuff, with a passion. I'm already hitting walls with a seemingly simple problem.
Here is the code that I think matters from the DatabaseHelper class
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Library";
public static final String TABLE_NAME = "books";
public static final String TITLE = "title";
public static final String AUTHOR = "author";
public static final String ISBN = "isbn";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT, isbn TEXT)");
}
public boolean insertBook(String title, String author, String isdn) {
try {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TITLE, title);
cv.put(AUTHOR, author);
cv.put(ISBN, isdn);
db.insert(TABLE_NAME, null, cv);
db.close();
return true;
} catch (Exception exp) {
exp.printStackTrace();
return false;
}
}
}
And this is the code in my main activity
dbHelper = new DatabaseHelper(this);
dbHelper.insertBook("Harry Potter", "JK", "1000");
dbHelper.insertBook("Hamlet", "Shakespeare", "500");
Eclipse is telling me that there is an error in the insertBook() method. It says that there is no such table books: .... I have no idea what I am doing wrong here. What makes it more frustrating is that only a couple of minutes before it was working perfectly, then (I think) I dropped the table and it just create it again for whatever reason, even though this code has not changed since I first created it (I think...).
There is an older version of the database on your device, which does have the (empty) database in place, but not the books table. If that's an option for you, just uninstall and reinstall the app.
Later, when you'd like to add a new table to the database during production on end-user devices, but keep existing data, the designated hook to add new tables, alter the schema or upgrade your data is the onUpgrade method of your SQLiteOpenHelper.
I have written a ORM framework for that. https://github.com/ahmetalpbalkan/orman
You can easily write Android applications using SQLite with that. It uses your Java classes (Book, in this case) as database tables (entities).
It even creates your table automatically and you just say book1.insert(), done.
You must uninstall the applcation and then reinstall it. It should work after that.
try this one
for example for insert:
public boolean insertBook(String title, String author, String isdn) {
try {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TITLE, title);
cv.put(AUTHOR, author);
cv.put(ISBN, isdn);
***try
{
db.insert(TABLE_NAME, null, cv);
}
catch ( SQLiteException e)
{
onCreate(db);
db.insert(TABLE_NAME, null, cv);
}***
db.close();
return true;
} catch (Exception exp) {
exp.printStackTrace();
return false;
}
}
Nothing about this made any sense, as the table existed from the very beginning of the DB, so we tried different things:
uninstalling app
claning cache / data
changing database version number
forcing to copy the database even if it already existed
If for some reason, you dropped the table, you might want to delete the database to force the application to recreate it correctly. Use adb shell and find the database in /data/data/[package_name]/databases/. You can just delete the file.
I had this problem, but cleaning the project did not fixed it.
It turned out I passed DATABASE_NAME instead of TABLE_NAME.
Make sure that onCreate method called. I am also facing similar type of problem when creating multiple table. If you create a separate class make sure you first clear all the storage data of your app and then again run it ..It will work fine for me.
Also had the issue where I already had the app built with an existing DB, but wanted to add another table.
Besides having the onUpgrade method, I also had to increment the private static final Integer DB_VERSION, which is used when instantiating the DatabaseHelper, like so:
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
}
Also from the official documentation, my onUpgrade method looks like this:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_1);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_2);
// create new tables
onCreate(db);
}
Then, after building the app, the new version of the database worked.
Note:
External Database You Access Time must add for the path in Sqliteopenhelper class
public final static String DATABASE_PATH = "/data/data/com.example.shortcuts/databases/";
com.example.shortcuts=Your Package name
db.execSQL(
"CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT, isbn TEXT)"
);
remove space after the table name, it should be like this.
db.execSQL(
"CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT, isbn TEXT)"
);

SQLite Android Problem

I am making a local high scores table using SQLite for my Android application (Java).
For some reason, the application crashes while trying to add a new high score to the table. Here is the relevant code:
private static String HIGHSCORES_TABLE_NAME = "SCORES_TABLE";
private SQLiteDatabase highScoresDB = null;
private Cursor cursor = null;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
try
{
highScoresDB = openOrCreateDatabase("ScoresDatabase", MODE_PRIVATE, null);
createTable();
lookupData();
}
catch (SQLiteException se)
{
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
finally
{
if (highScoresDB != null)
highScoresDB.execSQL("DELETE FROM " + HIGHSCORES_TABLE_NAME);
highScoresDB.close();
}
}
private void createTable() {
highScoresDB.execSQL("CREATE TABLE IF NOT EXISTS " + HIGHSCORES_TABLE_NAME + " (SCORE INT(3));");
}
private void insertData() {
highScoresDB.execSQL("INSERT INTO " + HIGHSCORES_TABLE_NAME + " Values ("+ highscore +");");
}
private void lookupData() {
cursor = highScoresDB.rawQuery("SELECT SCORE FROM " + HIGHSCORES_TABLE_NAME, null);
if (cursor.moveToLast()) {
highscore = cursor.getInt(cursor.getColumnIndex("SCORE"));
}
cursor.close();
}
public void restart() {
insertData();
}
When I look up the high score, I only want the most recent one so I use moveToLast().
I found that "cursor.moveToLast()" does not seem to work correctly. It does move the position in the cursor, but throws an exception when you attempt to read that record.
This works:
cursor.moveToPosition(cursor.getCount()-1)
What is the exception that causes it to crash, When are you inserting a new row ? Are you opening the database before inserting a row , as Close() is being called on in the finally block of the create method.
If this is the only information you are going to store in the database , consider using Shared Preferences.
This link has a demo of how to use it -
Shared preferences demo
Instead of doing statements like you are doing use some of the provided methods that are included in the SQLite Object class:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
This makes your code less error prone to SQL Typos or small errors.
Also please post your logcat.

Categories

Resources