无法在Android中实例化服务

时间:2014-04-10 09:38:31

标签: android sqlite service

我正在编写服务代码,每小时后删除Sqlite数据库中的表。这是我的服务类

  public class MyService extends Service{

 private Task retryTask;
    Timer myTimer;

    private boolean timerRunning = false;

    private long RETRY_TIME = 60000 * 60;
    private long START_TIME = 5000;

    DataHelperDon databaseHelperDon = new DataHelperDon(this);

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        myTimer = new Timer();
        myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
        timerRunning = true;

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!timerRunning) {
            myTimer = new Timer();
            myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
            timerRunning = true;
        }

        return super.onStartCommand(intent, flags, startId);

    } 
         public class Task extends TimerTask {

        @Override
        public void run() {

            // DO WHAT YOU NEED TO DO HERE
            databaseHelperDon.deleteDon();
            System.out.println("running service ==");
        }

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        if (myTimer != null) {
            myTimer.cancel();

        }

        timerRunning = false;
    }

在DataHelperDon中,我正在编写要删除的方法。

 public class DataHelperDon {


Context context;
MyDatabaseHelperDon don_helper;
SQLiteDatabase db;
Don myDon;

public DataHelperDon(Context context){
    this.context = context;
    don_helper= new MyDatabaseHelperDon(context, MyDatabaseHelperDon.DATABASE_NAME,null, MyDatabaseHelperDon.DATABASE_VERSION);
    db = don_helper.getWritableDatabase();
}


  public void deleteDon(){
        db=don_helper.getWritableDatabase();
        int i=0;
        Cursor cursor=db.query(MyDatabaseHelperDon.TABLE_NAME, null, null, null, null, null,null);
        while(cursor.moveToNext()) {

                db.delete(MyDatabaseHelperDon.TABLE_NAME, null, null);

         }
           db.close();
}
   }

当我运行此操作时,我收到以下错误

  04-10 14:49:28.267: E/AndroidRuntime(1432): FATAL EXCEPTION: main
  04-10 14:49:28.267: E/AndroidRuntime(1432): java.lang.RuntimeException: Unable to    instantiate service com.mb.mysmart.MyService: java.lang.NullPointerException
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at android.app.ActivityThread.handleCreateService(ActivityThread.java:2943)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at android.app.ActivityThread.access$3300(ActivityThread.java:125)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2087)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at android.os.Handler.dispatchMessage(Handler.java:99)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at android.os.Looper.loop(Looper.java:123)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at android.app.ActivityThread.main(ActivityThread.java:4627)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at java.lang.reflect.Method.invokeNative(Native Method)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at java.lang.reflect.Method.invoke(Method.java:521)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at dalvik.system.NativeStart.main(Native Method)
  04-10 14:49:28.267: E/AndroidRuntime(1432): Caused by: java.lang.NullPointerException
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at com.mb.mysmart.DataHelperDon.<init>(DataHelperDon.java:23)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at com.mb.mysmart.MyService.<init>(MyService.java:20)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at java.lang.Class.newInstanceImpl(Native Method)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at java.lang.Class.newInstance(Class.java:1429)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   at android.app.ActivityThread.handleCreateService(ActivityThread.java:2940)
  04-10 14:49:28.267: E/AndroidRuntime(1432):   ... 10 more

MyDatabaseHelperDon Class,

     public class MyDatabaseHelperDon extends SQLiteOpenHelper {


public static int DATABASE_VERSION = 1;
public static String DATABASE_NAME = "don";
public static String TABLE_NAME = "Don";
public static String KEY_ID = "key_id";
public static String VALUE = "value";
public static String UNIT = "unit";
public static String DESCRIPTION = "description";

public MyDatabaseHelperDon(Context context, String name,
        CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    String CREATE_DON_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + VALUE + " NUMERIC," + UNIT + " TEXT,"
            + DESCRIPTION + " TEXT"+ ")";
    db.execSQL(CREATE_DON_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

}

感谢您的帮助

4 个答案:

答案 0 :(得分:0)

您过早地实例化数据库。在Context之前,服务不能用作onCreate(),例如,在实例化服务对象时不能。{/ p>

移动实例化

DataHelperDon databaseHelperDon = new DataHelperDon(this);

到服务生命周期中的onCreate()或更高版本。

答案 1 :(得分:0)

只需使用

DataHelperDon databaseHelperDon = new DataHelperDon(this);

在服务中起点太早,因为那时Context变量将为空。所以你需要在onCreate()方法中初始化。所以它会是一样的,

DataHelperDon databaseHelperDon;

现在在onCreate()

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    myTimer = new Timer();
    databaseHelperDon = new DataHelperDon(this);
    myTimer.scheduleAtFixedRate(new Task(), START_TIME, RETRY_TIME);
    timerRunning = true;

}

答案 2 :(得分:0)

databaseHelperDononCreate()的实施情况如下。那样可以解决你的问题。

@Override
public void onCreate() {
   databaseHelperDon = new DataHelperDon(this);
}

答案 3 :(得分:-1)

根据我知道

您可以使用AlarmManager定期调用事件

Here is link to create alaram service

或者您只是尝试使用代码

Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); // Start every 30 seconds alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);