I am trying to create an android application using ORMLite package. I have a few activities and services and also use https://github.com/tomquist/Android-Error-Reporter to be able to receive errors from clients' pdas. ORMLite requires that all activities and services extend OrmLiteBaseActivity etc or add appropriate code to each activity to be able to get database helper and release it after the activity is finished. so this isn't very convenient to add this code to every activity or service. i also have some helper classes which can use database
I also have an application class that holds some global information and methods. So I decided to open ormlite helper in application class and use it through all activities/classes like this:
public class MyApplication extends Application {
private volatile DatabaseHelper databaseHelper = null;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onTerminate() {
if (databaseHelper != null) {
OpenHelperManager.releaseHelper();
databaseHelper = null;
}
super.onTerminate();
}
public DatabaseHelper getHelper() {
if (databaseHelper == null) {
databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
}
return databaseHelper;
}
}
and use it in other classes this way:
((MyApplication) getApplicationContext()).getHelper();
do you think it is a good idea to use it this way or there can be some memory leaks or other problems with this? My concern is that onTerminate never works on real devices... I am on the stage of "trying new stuff out" so would like to hear any comments about this to eliminate problems I can get in the future with a wrong approach and not having to rewrite the code.
The overall mechanism looks fine #Alex but as far as I know, onTerminate() is only used in emulated environments so doesn't have much use. You program gets killed by the Android OS when it terminates on a real device so there is no reason to be worried about memory leaks and the such.
What is most important with your code is that it guarantees a single databaseHelper instance. Each instance has it's own connection to the database and problems happen when there are more than one (1) connection opened to the database in a program. Sqlite handles multiple threads using the same connection at the same time but it doesn't handle multiple connections well and data inconsistencies may occur.
Related
I created a custom Application class for my app. This class onCreate sets a static variable of itself like this
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static ChattyApp getInstance() {
return mInstance;
}
Then I use App.getInstance() method to get application context to a nonactivity/fragment class like API Controller or something. Can it cause a memory leak?
I setup leak canary and it is showing memory leak on an instance variable of Application class. This variable keeps socket.io's socket ref so that I can use it anywhere in the app.
It is a good question that you have asked and people on SO have had extensive discussions on this. Have a look at this and this
Although this seems to be an okay way to store the Context in Application class as per the discussion in the first link, there can be better ways to deal with this.
Ideally for each logic unit you should have a separate class to deal with it rather than polluting your application class. You application class can however initialize or setup those other classes. This will create a separation of concern.
Another way is to use Dagger2, which is a dependency injection framework, to inject your socket ref to wherever you want.
Dagger 2 has a steep learning curve and but a very important tool to learn as an Android developer
I'm trying to put all the DatabaseRequests inside a module in Android to centralize all the acces to DDBB in the same place.
I'm wondering if I'm making any mistake doing that. The apps works in the right way but I'm concerned about best practices doing that.
I have an static class called DatabaseRequest where all the requests are inside, for instance:
public static void insertUser(Context context, User user) {
DataBaseHelper mDataBaseHelper = OpenHelperManager.getHelper(context, DataBaseHelper.class);
try {
Dao<User, Integer> dao = mDataBaseHelper.getUserDao();
dao.createOrUpdate(user);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (mDataBaseHelper != null) {
OpenHelperManager.releaseHelper();
}
}
}
The context param is the context of the activity that's making the request.
Is there any performance issue related with this code?
Thanks in advance ;)
No, as Gray (ORMlite creator) said in this post:
is it ok to create ORMLite database helper in Application class?
What is most important with your code is that it guarantees a single
databaseHelper instance. Each instance has it's own connection to the
database and problems happen when there are more than one (1)
connection opened to the database in a program. Sqlite handles
multiple threads using the same connection at the same time but it
doesn't handle multiple connections well and data inconsistencies may
occur.
And in your case you may have multiple connections at one time.
I can preset you my approach on how I'm using ORMlite, I have one singleton class public class DbHelper extends OrmLiteSqliteOpenHelper which takes care of creating database connection and holds all Dao fields. You will have database upgrade code there and some other stuff so consider making facade classes. In my case each facade holds one Dao object for one model class, where i keep logic for complex item retrieving (and for simple cases i just delegate it to Dao object.
Can anyone enlighten me about the safety of a class holding global values in Android?
Here's a short example of what I mean:
public class Globals {
public static int someVariable = 0;
public static User currentUser = null;
public static Handler onLogin = null;
}
Then somewhere in an Activity I do the following:
Globals.someVariable = 42;
Globals.currentUser = new User("John", "Doe");
I have to rely on Globals.currentUser at multiple places in my app as soon as the user is logged in, but I'm unsure if I should do it, and also if I could use a Handler like this.
I read everywhere that an Android app could be killed anytime, does this mean it is killed completely or maybe just a part of it, thus killing my Globals class only?
Or is there any other way to store globally available data in a safe way, without writing every member change to the database (in fact, my User class is a little more complex than in this example. ;-)
Thanks for your effort!
Edit: Ok, here's what I finally did:
public class MyApp extends Application {
private static MyApp _instance;
public MyApp() {
super();
_instance = this;
}
public static MyApp getContext() {
return _instance;
}
....
private User _user = null;
public User getUser() {
if (_user == null) _user = new User();
return _user;
}
}
Then modify the AndroidManifest.xml and add android:name=".MyApp" to your application node to tell the app to use your subclass.
So far everything works fine and I can easily access the current Context (f.ex. in SQLiteOpenHelper) by calling MyApp.getContext().
It would be better to use the Android Application class. It's meant to store global application state
http://developer.android.com/reference/android/app/Application.html
Just create a subclass and make sure to update your manifest file to use your version. Then you can store whatever you need to in it. Activities have a method getApplication() which you can cast to your class to access your implementation
The pattern is discouraged--you will run into problems when unit testing.
Can you explain how you unit-test a class that must supply different custom "Users" here? You are either forcing a mock/fake class into "User" which will probably have a cross-effect on other tests or you are putting an if(test) into your code which gets ugly quick.
Over time populating this class artificially for testing gets more complex and starts to have relationships and dependencies.
More simply it makes it difficult to unit test a class in isolation.
It's one of those patterns that a given programmer either doesn't see a problem with or never uses because he's been burnt--you'll see little middle ground.
Some backstory on my applications code organization:
Right now I'm kind of using a ad-hoc ORM for DB access, where each table is split up into a model (just a plain Java class not inheriting from any Android components) which covers normal CRUD activities.
I'm not using a content provider as all this data is private to the application.
I'm keeping a singleton of my databaseopenhelper, and the application context in my application's Application class
class MyApplication extends Application {
private static Context mContext;
#Override
public void onCreate() {
super.onCreate();
mContext = this;
dbHelper = new DatabaseHelper(this); // Subclass of SQLiteOpenHelper
}
public static Context getContext(){
return mContext;
}
All activities that touch the db open the database onResume, and close it onPause.
This seemed to be working fine until I started unit testing, when I ran into the first problem with using singletons - breaking encapsulation (specifically not being able use RenamingDelegatingContext to test with a specific test database).
So,
1) Something tells me if I can't unit test properly, my architecture is bunk - but I can't think of a better way to do this (short of passing context and dbhelpers explicitly - which is a pain)
2) If it is not an entirely crazy idea, what would be the best way to go about unit testing this setup?
I am creating an app which allows for many different Activities to be started from a TabActivity(up to ~25). Most of the activities require data from the sqlite database, so when onCreate is run, an AsyncTask creates an SQLiteOpenHelper object(which will open a readable/writable database), runs a query, data is retrieved, and everything is then closed.
i was just testing messing around to see if i could break something, so i added every Activityto the TabActivity's TabHost. I then started mashing each tab as quickly as possible.
i noticed that very quickly i began to see in the LogCat: Caused by: android.database.sqlite.SQLiteException: database is locked: BEGIN EXCLUSIVE; and the app proceeded to die.
Typically there will only be about 4-6 tabs(i can just limit the user anyway) for the TabHost. I haven't been able to break anything with a small amount of tabs to mash, but i am still worried that maybe i am accessing the database in a poor way.
How can i prevent my SQLiteDatabase objects to cause a lock?
If i create a ContentProvider will that eliminate the possibility of database locking?
Do you have any suggestions for changes I could make for accessing data from an SQLiteDatabase?
I ended up taking the approach of using the Application class and storing 1 SQLiteOpenHelper and trying my best to keep it synchronized. This seems to be working great - i put all my 25 activities in the TabHost and mashed away on them with no errors.
I am calling ((SQLiteDbApplication)getApplication()).setDbHelper(new DBHelper(this, Constants.DB_NAME, null, Constants.DB_VERSION_CODE)); method(shown below) in every onCreate() in my activities
Any further suggestions to this approach or to the changes i made using this Application class?
import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
public class SQLiteDbApplication extends Application {
private DBHelper dbHelper;
private SQLiteDatabase db;
public synchronized DBHelper getDbHelper() {
db = dbHelper.getDatabase();//returns the already opened database object
while(db.isDbLockedByCurrentThread() || db.isDbLockedByOtherThreads());
return dbHelper;
}
public synchronized void closeDb() {
if(null != dbHelper)
dbHelper.close();
if(null != db)
db.close();
}
#Override
protected void finalize() throws Throwable {
if(null != dbHelper)
dbHelper.close();
if(null != db)
db.close();
super.finalize();
}
public synchronized void setDbHelper(DBHelper dbHelper) {
if(null == this.dbHelper) {
this.dbHelper = dbHelper;
this.dbHelper.setDb(this.dbHelper.getWritableDatabase());//creates and sets the database object via getWritableDatabase()
}
}
}
If you are to worried about all the database connections try to limit yourself to one SqliteOpenHelper and be sure to wrap a synchronization layer around it.
You can extend the application class and then call getApplication and cast the object you get into your application. Now you can store a SqliteOpenHelper in this application class and build your own thread safe access method to the database connection.
If you are using AsyncTask in all of your onCreate methods and you are experiencing problems with a lot of tabs these problems can also occur with a slower device, a faster user or a database that is grown big over the time of usage.
Depending on the use case of you app you can go the save way and go through all the effort and pain of threading and locking, or you can just publish the app with a number of tabs that never produced the error and be sure to catch the database exception and send yourself a notification (for example through google analytics) to test if the threading problem does occur in real life usage of the app.
All activity callbacks happen on the main thread, so in the scenario you describe there is no multi-threading going on, no matter how many activities or tabs you have.
ContentProvider doesn't provide any locking. In fact, it can introduce multithreading where you wouldn't already have it because it allows other processes to make calls in to your own process, and when that happens the call is dispatched from a separate thread in your process (not on the main UI thread).
Of course if you create your own threads, then you will also have multi-threading going on.