Android小部件onReceive崩溃

时间:2013-04-12 18:42:58

标签: java android widget

基本上当我点击小部件上的特定按钮时,我想获取数据库中的下一条记录。当我在应用程序中使用它时,函数本身工作正常。但是在小部件中,它正在崩溃。我认为这是onReceive函数本身就是问题,尽管我只是设置onReceive来更新textview它崩溃为nullpointerexception。

  

public static String NEXT_RECORD =“next_record”;

以下是调用它的地方:

  

Intent intent = new Intent(context,MyWidgetProvider.class);
  intent.setAction(NEXT_RECORD); PendingIntent pendingIntent =   PendingIntent.getBroadcast(背景下,         0,intent,PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.TextView02,pendingIntent);

和onreceive

  @Override
  public void onReceive(Context context, Intent intent) {
   super.onReceive(context, intent);
   if(NEXT_RECORD.equals(intent.getAction())){
       newid = mDbHelper.getNextRecord(1, keyid);
    }

  }



04-12 14:47:57.591: E/AndroidRuntime(30633): FATAL EXCEPTION: main
04-12 14:47:57.591: E/AndroidRuntime(30633): java.lang.RuntimeException: Unable to start receiver com.example.app.hs.MyWidgetProvider: java.lang.NullPointerException
04-12 14:47:57.591: E/AndroidRuntime(30633):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2362)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at android.app.ActivityThread.access$1500(ActivityThread.java:142)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at android.os.Looper.loop(Looper.java:137)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at android.app.ActivityThread.main(ActivityThread.java:4931)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at java.lang.reflect.Method.invokeNative(Native Method)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at java.lang.reflect.Method.invoke(Method.java:511)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
04-12 14:47:57.591: E/AndroidRuntime(30633):    at dalvik.system.NativeStart.main(Native Method)
04-12 14:47:57.591: E/AndroidRuntime(30633): Caused by: java.lang.NullPointerException
04-12 14:47:57.591: E/AndroidRuntime(30633):    at com.example.app.hs.MyWidgetProvider.onReceive(MyWidgetProvider.java:100)

1 个答案:

答案 0 :(得分:0)

Caused by: java.lang.NullPointerException
    at com.example.app.hs.MyWidgetProvider.onReceive(MyWidgetProvider.java:100)

如果newid = mDbHelper.getNextRecord(1, keyid);抛出此NPE,则mDbHelper为空。在尝试阅读之前,只需实例化mDbHelper

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    if (NEXT_RECORD.equals(intent.getAction())) {
        mDbHelper = new DbHelper(context); // I guessed at the constructor's parameters
        newid = mDbHelper.getNextRecord(1, keyid);
    }

}