我必须从 Service android 调用一种方法来打开与内部 android 数据库(sqlite)的连接。我正在使用以下代码:
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() 定义为:
SQLiteDatabase mDb=mDbHelper.getWritableDatabase();
为了调用我使用的服务:
myService serv = new myService();
serv.setDB(dbManager);
startService(new Intent(this,myService.class));
如果我删除行 dbManager.open(); 一切正常 但是,我的代码的其他部分中的方法 dbManager.open() 效果很好。但在这种情况下,我在 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)