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?
Related
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.
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;
}
I am trying to develop an Android app. I use a local database "AndroidProject.db" which is put into the assets folder. When I try to copy the database to its correct location I encounter a NullPointer Exception. I marked the line where the Exception is happening.
Source Code:
public class DBHelper extends SQLiteOpenHelper {
public static final int VERSION = 1;
public SQLiteDatabase myDatabase;
private static final String TAG = "DBHelper";
public Context myContext;
public static final String DB_NAME = "AndroidProject.db";
public DBHelper(Context context){
super(context,DB_NAME,null,VERSION);
}
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
public void openDatabase() {
importDatabase();
Log.i(TAG, "open database");
}
public void closeDatabase() {
myDatabase.close();
Log.i(TAG, "close database");
}
public void importDatabase() {
File f = null;
try {
// Exception occurs here
f = myContext.getDatabasePath(DB_NAME);
} catch (NullPointerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (!f.exists()) {
try {
f.getParentFile().mkdirs();
InputStream is = myContext.getAssets().open("AndroidProject.db");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("File Error", e.getMessage());
}
}
if (myDatabase == null || !myDatabase.isOpen()) {
myDatabase = SQLiteDatabase.openDatabase(f.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
}
}
public SQLiteDatabase getDatabase() {
return myDatabase;
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
The error is happening here: f = myContext.getDatabasePath(DB_NAME);
Logcat:
Caused by: java.lang.NullPointerException
at fu.android.example.travelvnproject_v01.Database.DBHelper.importDatabase(DBHelper.java:59)
at fu.android.example.travelvnproject_v01.Database.DBHelper.openDatabase(DBHelper.java:42)
at fu.android.example.travelvnproject_v01.Database.DBProvider.query(DBProvider.java:38)
at fu.android.example.travelvnproject_v01.LocalActivity.onCreate(LocalActivity.java:41)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
The error is happening because myContext is null. Try this:
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
myContext = context;
}
EDIT:
I tested with this source code with my suggested changes and it's working fine, I only made a few other changes for convenience and I removed the unnecessary try/catch block:
public class DBHelper extends SQLiteOpenHelper {
public static final int VERSION = 1;
public SQLiteDatabase myDatabase;
private static final String TAG = "DBHelper";
public Context myContext;
public static final String DB_NAME = "AndroidProject.db";
public DBHelper(Context context){
this(context, DB_NAME, null, VERSION); // Changed this to call the other constructor for convinience
}
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
myContext = context;
}
public void openDatabase() {
importDatabase();
Log.i(TAG, "open database");
}
public void closeDatabase() {
myDatabase.close();
Log.i(TAG, "close database");
}
public void importDatabase() {
File f = myContext.getDatabasePath(DB_NAME);
if (!f.exists()) {
try {
f.getParentFile().mkdirs();
InputStream is = myContext.getAssets().open("AndroidProject.db");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("File Error", e.getMessage());
}
}
if (myDatabase == null || !myDatabase.isOpen()) {
myDatabase = SQLiteDatabase.openDatabase(f.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
}
}
public SQLiteDatabase getDatabase() {
return myDatabase;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
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.
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.