Android Studio: execSQL(String sql) do not throw SQLException - android

On the documentation it say's
execSQL(String sql) Throws: SQLException - if the SQL string is invalid
but it do not in android studio, any one having this problem ?
public class test extends SQLiteOpenHelper {
public test(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("some sql code");
}
catch(SQLException e){
//do something
}
}
//some other overrides
}
This will give me error an error because execSQL() is not throwing an exception.when checking its declaration I get
public void execSQL(String sql) {
executeSql(sql, null);
}
So my question is in the documentation and even on eclipse I am sure it returns a SQLException but here on Android Studio its not.

execSQL() can throw android.database.SQLException. If you inadvertently imported java.sql.SQLException as first suggested by Android Studio, you'll get an error
Exception 'java.sql.SQLException' is never thrown in the corresponding try block
To fix it, import android.database.SQLException instead.

Related

upgrading database in android studio not working

I am trying to updgrade the sqlite version number from 1 to 2 but onupgrade method is not getting called.
do i have to delete application in the device and then install the application to test it ?
Only method which get called is DatabaseHelper and onCreate
No other method get called.
In DatabaseHelper.java file
private static final int DBVersion = 1; // I had change this value to 2.but it is not working.
public DatabaseHelper(Context context, CursorFactory cf) {
super(context, DBName, cf, DBVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE_Table);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
//This is not called.If it called i will add the changed here
}
another class for dataprovider.java
#Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext(), null);
return true;
}
using :-
#Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext(), null);
SqliteDatabase db = dbHelper.getWritableDatabase(); //<<<<<<<<<<<
return true;
}
attempts to open the database and thus onCreate/onUpgrade would be called.
- onCreate only if the database does not exist.
- onUpgrade only if the database exists AND the specified version number is greater than the database version stored in the database.
That is when instantiating the Database Helper (subclass of SQLiteOpenHelper) no attempt is made to open the database.
The attempt to open the database is only made when the SQLiteDatabase's getWritableDatabase (or getReadableDatabase) are called. Both attempt to open the database. Noting that getWritableDatabase or getReadableDatabase may well be called implicitly.
Note the above does not include directly using the SQliteDatabase's OPEN methods.
Alternative Fix
I personally tend to force the open when constructing the database helper by using :-
public DatabaseHelper(Context context, CursorFactory cf) {
super(context, DBName, cf, DBVersion);
this.getWritableDatabase();
}
I tend to save the returned SQLiteDatabase into a class variable and then use that rather than using this.getWritableDatabase() in the underlying methods.

OrmLite java.lang.IllegalStateException: you must call initialize() before you can use the dao

I am using ORMLite to persist my object in my SqliteDatabase in my app.
I am getting this exception while trying to get a DAO in order to persist an object.
The documentation says I have to call the initialize() method before I can use the DAO, and the OrmLite documentation (insufficient) says:
BaseDaoImpl (class)
initialize(): Initialize the various DAO configurations after the various setters have been called.
The problem is, I get the DAOs by calling getDao(class), and there is no initialize() that I can call neither on DAOs nor in my class that extends OrmLiteSqliteOpenHelper.
This is my custom OpenHelper class code:
public class LocalDBHelper extends OrmLiteSqliteOpenHelper {
private LocalDBHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static LocalDBHelper getInstance(Context context) {
if (instance == null) instance = new LocalDBHelper(context);
return instance;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Barrio.class);
TableUtils.createTable(connectionSource, Fenomeno.class);
TableUtils.createTable(connectionSource, Info.class);
TableUtils.createTable(connectionSource, TelefonoUtil.class);
TableUtils.createTable(connectionSource, Alarma.class);
TableUtils.createTable(connectionSource, ReplicaAlerta.class);
} catch (SQLException e) {
e.printStackTrace();
Log.d(TAG, e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, Barrio.class, true);
TableUtils.dropTable(connectionSource, Fenomeno.class, true);
TableUtils.dropTable(connectionSource, Info.class, true);
TableUtils.dropTable(connectionSource, TelefonoUtil.class, true);
TableUtils.dropTable(connectionSource, Alarma.class, true);
TableUtils.dropTable(connectionSource, ReplicaAlerta.class, true);
} catch (SQLException e) {
e.printStackTrace();
Log.d(TAG, e.getMessage());
}
}
And this is the full stack of Android Monitor:
java.lang.IllegalStateException: you must call initialize() before you can use the dao
at com.j256.ormlite.dao.BaseDaoImpl.checkForInitialized(BaseDaoImpl.java:1061)
at com.j256.ormlite.dao.BaseDaoImpl.create(BaseDaoImpl.java:316)
at com.org.siam.app.controller.BarrioController.actualizarTodos(BarrioController.java:75)
at com.org.siam.app.remote.BarriosWebService.onResponse(BarriosWebService.java:43)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
EDIT: added an Application subclass called SiacApplication, onCreate() method code here (also registered on manifest):
#Override
public void onCreate() {
super.onCreate();
LocalDBHelper.getInstance(this);
}
EDIT 2: added DAO getter (the DAO is a local field):
public Dao<Barrio, Long> getBarrioDao() throws SQLException {
if (barrioDao == null) barrioDao = getDao(Barrio.class);
return barrioDao;
}
Faced the same problem in Android. It seems that it's required to send ConnectionSource while creating DAO.
In my case only creating wrapper classes for DAO helped because there is no getDao() method variation with such parameter.
So i created wrapper
class BarrioDao {
public BarrioDao(ConnectionSource connectionSource) throws SQLException{
super(connectionSource, Barrio.class);
}
}
getter for dao in LocalDBHelper looked like:
public BarrioDao getBarrioDao() throws SQLException {
if (barrioDao == null) barrioDao = new BarrioDao(getConnectionSource());
return barrioDao;
}
for everyone got this error,
WHY I GET THIS ERROR:
When beginning creating your DAO any runtime exception does interrupt your DAO initialization and it makes you got this error.
HOW TO SOLVE IT :
1 - Check every throw ORMlite and SQLite exception from your DaoHelper class.
2 - Try to correct every error you got and stop every exception that can be thrown.
3 - Run your application without any runtime exception when beginning creating your DAO.
Ran into this same problem and realized that it was caused by changing the name of one of my database fields and running the code without regenerating the ormlite_config.txt.
When the ORMLite system was trying to load my class config and initialize the DAOs, it saw the config in ormlite_config.txt said there was a fieldname called oldname and then looked at the java class definition and didn't see an instance variable for oldname so it threw an exception which corrupted the rest of the process.
So, if you run into this error, make sure you regenerate your ormlite_config.txt file and try running again.

Strange behavior with SQLItes onConfigure method

I am trying to implement a foreign key in my database table, for that I need to call onConfigure where I set the PRAGMA. However implementation of this method gives me strange behavior. When I use the #Override annotation the eclipse intellisense asks me to remove it , and when I remove it I get a different set of warnings This method is not overriding anything with the current build target, but will in API level 16 (current target is 11)
Following is my code snippet for the particular problem code:
public static class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE0);
db.execSQL(unique);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void onConfigure(SQLiteDatabase db){
System.out.println("Hello from on Configure");
db.execSQL("PRAGMA foreign_keys=ON");
}
}
This is my Manifest SDK Declaration:
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
To stop android lint from raising an error, annotate the onConfigure
override in DatabaseOpenHelper to be JellyBean or higher. Older
android versions will continue to use the old mechanism already checked
for in the onOpen override.
You need to add the #TargetAPI in your class as below:
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db); }
Check out the Reference

Android databases are too big to be created on onCreate

On my app I make use of two datatabases.
This is the class that handles the database management and all the query that are made to it.
public class Database {
private DbHelper DBHelper;
private final Context Context;
private SQLiteDatabase MyDBone, MyDBtwo;
static Context ctx;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context, String dbName, int dbVersion) {
super(context, dbName, null, dbVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
// This is where the two databases are created
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVesion) {
// database upgrades are handled here
}
}
}
// database constructor
public Database(Context c) {
Context = c;
ctx = c;
}
// database open
public Database open() throws SQLException {
DBHelper = new DbHelper(Context, BD_NAME, BD_VERSION);
// I have here some if code to decide witch one of the bellow is used
if{
MyDBone = DBHelper.getWritableDatabase();
} else{
MyDBtwo = DBHelper.getWritableDatabase();
}
return this;
}
// database close
public void close() {
DBHelper.close();
}
public Cursor getData(........) {
// My querys are made here
}
}
My problem is that the databases are too big. In the onCreate method I'm getting the error: The code of method onCreate(SQLiteDatabase) is exceeding the 65535bytes limit. On the other side, my app is getting very big on size.
I would like to know what's the best way to address this issue since I can't change my databases.
Since my app must be run offline I can't make query's on a webserver.
I beleive that the best aproach would be to, on the first run of the app, download the databases from somewhere on the internet (drive, dropbox or other side) but since my programming skils are a little green I must pospone this to a must do in the future.
Is it possible, maintaining my Database class, prepack the apk with the databases and install them on the sdcard? On the other side this will increase the apk size (the total of the databases is 15 mb).
Please advise on the best way to address this issue.
Regards,
favolas

Android SQLite - why is my db re-created each time?

I'm trying to get a better understanding of the SQLiteOpenHelper class and how and when onCreate and onUpgrade are called.
My problem is that each time I quit and start my application (technically it's actually each time I create a new instance of MyDB), onCreate is called, and all of the data from the previous usage is effectively wiped... WTF???
I got around this problem initially by creating a singleton MyDBFactory where I created a single instance of MyDB. This allowed the data to be persistent while the application is running at least.
What I would like is for my database schema and data to be persistent!
I basically have:
public class MyDB extends SQLiteOpenHelper{
private static int VERSION = 1;
...
public ContactControlDB(Context context) {
super(context, null, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
db.execSQL(INSERT_DATA);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
and:
public class MyDBFactory{
private static MyDB db;
public static MyDB getInstance(Context context) {
if(db == null) {
db = new MyDB (context);
}
return db;
}
}
What I'd like to know is why onCreate is called every time I have 'new MyDB(context)', and where my database goes each time my app exits.
If you have some appropriate links, or some knowledge that would clue me up a bit, I'd greatly appreciate it!
the line:
super(context, null, null, VERSION);
the second parameter is null specifying that the database should be created in memory, you should give it a name.
Android reference

Categories

Resources