Ormlite database helper - onCreate() not called - android

I am using ormlite.android.4.31.jar
I have typical DatabaseHelper
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "realestate.db";
private static final int DATABASE_VERSION = 1;
private Dao<TabKraj, Integer> krajDao;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, TabKraj.class);
initData();
} catch (Exception e) {
Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
}
}
#Override
public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {
try {
TableUtils.dropTable(connectionSource, TabKraj.class, true);
onCreate(sqliteDatabase, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + oldVer + " to new " + newVer, e);
}
}
public Dao<TabKraj, Integer> getKrajDao() throws SQLException{
if (krajDao == null) {
krajDao = getDao(TabKraj.class);
}
return krajDao;
}
private void initData(){
Log.d(Constants.DEBUG_TAG, "data initiating");
TabKraj k1 = new TabKraj();
TabKraj k2 = new TabKraj();
k1.setNazov("Kosicky kraj");
k1.setId(1);
try {
getKrajDao().create(k1);
} catch (SQLException e) {
Log.e(Constants.DEBUG_TAG, "Data initialing ERROR");
}
}
}
app is uninstalled, data cleared ...
I am running app in debug mode from eclipse, constructor of DatabaseHleper is called but onCreate() is not called.
Where could the problem be?

As #k-mera said:
Database file will be created only if you did some operations in Database like "insert".

Although you say the data is cleared, I suspect that Android thinks it has not. To completely remove the data, I would remove the application and re-install it.
Since your onUpgrade calls onCreate you could also increase the DATABASE_VERSION value which will cause the data to be dropped and re-created.

Related

Creating database using orm

I am using ORMlite database for the first time in my application. i have taken reference from a tutorial, but instead of doing all the things exactly same i am not able to resolve an error. My code is below:-
DatabaseHelper:
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "qzeodemo.db";
private static final int DATABASE_VERSION = 1;
private Dao<ModifierDetails, Integer> itemsDao;
private Dao<ItemDetails, Integer> modifiersDao;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
}
#Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
try {
// Create tables. This onCreate() method will be invoked only once of the application life time i.e. the first time when the application starts.
TableUtils.createTable(connectionSource,ItemDetails.class);
TableUtils.createTable(connectionSource,ModifierDetails.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
}
}
#Override
public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVer, int newVer) {
try {
// In case of change in database of next version of application, please increase the value of DATABASE_VERSION variable, then this method will be invoked
//automatically. Developer needs to handle the upgrade logic here, i.e. create a new table or a new column to an existing table, take the backups of the
// existing database etc.
TableUtils.dropTable(connectionSource, ItemDetails.class, true);
TableUtils.dropTable(connectionSource, ModifierDetails.class, true);
onCreate(sqliteDatabase, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + oldVer + " to new "
+ newVer, e);
}
}
// Create the getDao methods of all database tables to access those from android code.
// Insert, delete, read, update everything will be happened through DAOs
public Dao<ItemDetails,Integer> getItemDao() throws SQLException {
if (itemsDao == null) {
itemsDao = getDao(ItemDetails.class);
}
return itemsDao;
}
public Dao<ModifierDetails, Integer> getMofifierDao() throws SQLException {
if (modifiersDao == null) {
modifiersDao = getDao(ModifierDetails.class);
}
return modifiersDao;
}
}
The line where i am using modifiersDao = getDao(ModifierDetails.class); is giving error
Error:(76, 30) error: invalid inferred types for D; inferred type does not conform to declared bound(s)
inferred: Dao
bound(s): Dao
where D,T are type-variables:
D extends Dao declared in method getDao(Class)
T extends Object declared in method getDao(Class)
Please help :(
Your declaration is wrong above:
private Dao< ItemDetails, Integer > modifiersDao;
but getMofifierDao() returns Dao< ModifierDetails, Integer>

Running DatabaseConfigUtility as Main class in Android Studio

I am trying to create a DatabaseConfigUtil which extends OrmLiteConfigUtil in Android Studio. I followed the steps specified here but since it mentions steps to follow in Eclipse, I got lost in the middle.
public class DatabaseConfigUtility extends OrmLiteConfigUtil {
public static void main(String[] args) {
try {
writeConfigFile("ormlite_config.txt");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I tried to Edit configuration for the class still it throws an error because I have defined the path to the config file in my DatabaseHelper class
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "notes.db";
private static final int DATABASE_VERSION = 1;
private Dao<Note, Integer> noteDao = null;
private RuntimeExceptionDao<Note, Integer> noteRunTimeDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, R.raw.ormlite_config);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
try {
// TableUtils.clearTable will create Table having attribute equals to Note class
TableUtils.createTable(connectionSource, Note.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i2) {
try {
// first drop the table and then create the table again.
TableUtils.dropTable(connectionSource, Note.class, true);
onCreate(sqLiteDatabase, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Dao<Note, Integer> getNoteDao() throws SQLException {
if (noteDao == null) {
noteDao = getDao(Note.class);
}
return noteDao;
}
public RuntimeExceptionDao<Note, Integer> getNoteRunTimeDao() {
if (noteRunTimeDao == null) {
noteRunTimeDao = getRuntimeExceptionDao(Note.class);
}
return noteRunTimeDao;
}
}
The gradle execution fails and throws this error which is because I have declared the path to config file and it does not exist.
Error:Gradle: Execution failed for task ':app:compileDebugJava'.
Compilation failed; see the compiler error output for details.
C:\Users\Pavitra\Documents\AndroidStudio\ORMLiteDemo\app\src\main\java\orm\entities\DatabaseHelper.java
Error:(24, 64) Gradle: error: cannot find symbol variable raw
In order to create ormlite_config.txt file, I have to run the DatabaseConfigUtil class.
How to run the DatabaseConfigUtil to generate the ormlite_config.txt file?
Any help or advice is much appreciated.
Thanks in advance.

Using OrmLite in AppWidget RemoteViewFactory

I need to load data from database in RemoteViewFactory class, I'm using OrmLite.
I've this Helper class:
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "gfkksa.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Issue.class);
TableUtils.createTable(connectionSource, IssuePriority.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database.");
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, Issue.class, true);
TableUtils.dropTable(connectionSource, IssuePriority.class, true);
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases.");
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
public HashMap<String, Dao> getDaoFactory() {
HashMap<String, Dao> hashFactory = new HashMap<String, Dao>();
try {
hashFactory.put("issue", getDao(Issue.class));
hashFactory.put("issuePriority", getDao(IssuePriority.class));
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hashFactory;
}
}
Everything works ok, in Activity class (extends OrmLiteBaseActivity<DatabaseHelper>), for example i'm getting list of data from DB like this:
ArrayList items = (ArrayList) getHelper().getDaoFactory().get("issue").queryForAll();
But if I do the same at class implementing RemoteViewsService.RemoteViewsFactory (Remote views factory for AppWidget's ListView) app crashes with this exception message:
03-18 16:13:29.244: E/AndroidRuntime(28500): java.lang.RuntimeException: Unable to bind to service cz.testbrana.widget.WidgetService#41e34110 with Intent { dat=intent: cmp=cz.testbrana.ebranasystem/cz.testbrana.widget.WidgetService (has extras) }: java.lang.IllegalStateException: A call has not been made to onCreate() yet so the helper is null
How can I use OrmLite in AppWidget's RemoteViewFactory?
I've found the anwser, everything works great when using methods getHelper() and onDestroy() from oficial documentation (http://ormlite.com/docs/android) instead of extending DBHelper.
private DatabaseHelper databaseHelper = null;
#Override
protected void onDestroy() {
super.onDestroy();
if (databaseHelper != null) {
OpenHelperManager.releaseHelper();
databaseHelper = null;
}
}
private DBHelper getHelper() {
if (databaseHelper == null) {
databaseHelper =
OpenHelperManager.getHelper(this, DatabaseHelper.class);
}
return databaseHelper;
}

Error from constructor when using ORMLite

I have a problem: Could not find constructor that has just a (context) argument for helper class ...
class ORMDBHelper extends OrmLiteSqliteOpenHelper {
private EventDAO mMyDao;
public ORMDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, MyClass.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, MyClass.class, true);
onCreate(db, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
public EventDAO getEventDAO() throws SQLException {
if (mMyDao == null) {
mMyDao = new MyDAO(getConnectionSource(), MyClass.class);
}
return mMyDao;
}
public void clearTable(Class dataClass) throws SQLException {
TableUtils.clearTable(getConnectionSource(), dataClass);
}
#Override
public void close() {
super.close();
mMyDao = null;
}
}
Line where is error:
mDbHelper = OpenHelperManager.getHelper(context, ORMDBHelper.class);
I found a few answers, but they are solution for obfuscation.
Could not find constructor that has just a (context) argument for helper class ...
Make sure that the ORMDBHelper class is public since otherwise the class and the constructor won't be visible.
Otherwise it might be referring to a different ORMDBHelper class or maybe the Context argument is of the wrong type somehow?

Where is my database file created

This is my file dataSqliteHelper and when I run the first time, the data file is created but I don't know where is it to get it and open it with a tool and view the file.
public class DataSQLiteHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_NAME = "ventasdb.db";
private static final int DATABASE_VERSION = 1;
private Context mContext;
private Dao<Customer, Integer> customerDao;
public DataSQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource conections) {
try {
TableUtils.createTable(connectionSource, Customer.class);
} catch (Exception e) {
Log.e(DataSQLiteHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, Customer.class, true);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Returns the Database Access Object (DAO) for our UserData class. It will
* create it or just give the cached value.
*/
public Dao<Customer, Integer> getCustomerDao() {
if (customerDao == null) {
try {
customerDao = getDao(Customer.class);
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return customerDao;
}
public boolean updateCustomer(Customer p) {
boolean ret = false;
if (customerDao != null) {
try {
customerDao = getDao(Customer.class);
UpdateBuilder<Customer, Integer> updateBuilder = customerDao
.updateBuilder();
updateBuilder.updateColumnValue("name", "PIRIPIPI"); // p.getName());
updateBuilder.updateColumnValue("cel", p.getCel());
updateBuilder.updateColumnValue("email", p.getEmail());
updateBuilder.updateColumnValue("address", p.getAddress());
updateBuilder.updateColumnValue("City", p.getCity());
// but only update the rows where the description is some value
updateBuilder.where().eq("customerID", 0);
// actually perform the update
customerDao.update(p);
customerDao.refresh(p);
} catch (Exception e) {
ret = false;
e.printStackTrace();
}
}
return ret;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
}
}
with this line I know that I give the file name
super(context, DATABASE_NAME, null, DATABASE_VERSION);
but where is it in the storage of the device?
By the way , can I change the path to store the file in the sd card ?
it will be stored at
/data/data/[package name]/databases
But unless your phone is rooted you cannot browse to it using file explorer or adb shell
It is saved here (as nandeesh says)
/data/data/[package name]/databases
You can only access it on a phone if it is rooted. Or you can install the app on an emulator, start up the DDMS tool and view the database file there.

Categories

Resources