I have to call, from a Service android, a method for opening connection with internal android database (sqlite). I’m using the following code:
public class myService extends Service{
public void setDB(DB_DatabaseManager db){
dbManager = db;
}
public DB_DatabaseManager dbManager;
private Timer timer;
public IBinder onBind(Intent intent){
return null;
}
public void onCreate(){
super.onCreate();
Log.i("my attempt","service activated");
TimerTask task = new TimerTask(){
public void run(){
Log.i("my attempt","ANDROID SERVICE RUNNING!");
dbManager.open(); // <--this statement generates error!
// --- in this section I start the communication with database
}
};
timer = new Timer();
timer.schedule(task, 0, 20000);
}
public void onDestroy(){
super.onDestroy();
timer.cancel();
timer = null;
Log.i("my attampt", "service stopped");
}
open() is defined as:
SQLiteDatabase mDb=mDbHelper.getWritableDatabase();
For calling the service I use:
myService serv = new myService();
serv.setDB(dbManager);
startService(new Intent(this,myService.class));
all work fine if I delete the row dbManager.open();
however the method dbManager.open() in other parts of my coode, works good. But in this situation i obtain the following error in logcat:
09-14 23:44:32.287: E/AndroidRuntime(1115): FATAL EXCEPTION: Timer-0
09-14 23:44:32.287: E/AndroidRuntime(1115): java.lang.NullPointerException
09-14 23:44:32.287: E/AndroidRuntime(1115): at host.framework.myService$1.run(myService.java:49)
09-14 23:44:32.287: E/AndroidRuntime(1115): at java.util.Timer$TimerImpl.run(Timer.java:284)
Do not try to do this…
Similar to the
Activityclass,Serviceis a “special case” class and you should never try to create an instance usingnew.A
Serviceis created using eitherbindService(...)orstartService(...)and it is the responsibility of the OS to create/instantiate it.In your case it seems you need your
Serviceto be able to access a database “helper” class and there are a number of ways you could do this.One way is to extend the
Applicationclass and have it create an instance of the db helper and hold astaticreference to it. In this way in theService, you can simply use…Alternatively use the
singletonmodel for your db helper which would allow you to do something like the following in theService…