android小部件按钮崩溃

时间:2012-02-10 17:37:22

标签: android android-widget

我正在做一个有3个按钮的小部件。我需要为每个按钮调用一个函数。我这样做:

public class myWidget extends AppWidgetProvider {


@Override
public void onReceive(Context context, Intent intent) {

    final String action = intent.getAction();
    if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
        final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
            this.onDeleted(context, new int[] { appWidgetId });
        }
    } else {
  // check, if our Action was called
         if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
                String msg = "null";
                try {
                    msg = intent.getStringExtra("msg");

                    if(msg.equals("nextpage"))
                        callFunction1();

                    if(msg.equals("prevpage"))
                                       callFunction2();

                    if(msg.equals("ref")) 
                                         callfunction3();
                } catch (NullPointerException e) {

                }
         }

        super.onReceive(context, intent);
    }
}

@Override
public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds ) {



    remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
    this.appWidgetManager = appWidgetManager;
    thisWidget = new ComponentName(context, SteauaWidget.class);

    Intent active = new Intent(context, MyWidget.class);
    active.setAction(ACTION_WIDGET_RECEIVER);
    active.putExtra("msg", "ref");

    PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 1, active, 0);

    remoteViews.setOnClickPendingIntent(R.id.button3, actionPendingIntent);

    Intent nextPage = new Intent(context, MyWidget.class);
    nextPage.setAction(ACTION_WIDGET_RECEIVER);
    nextPage.putExtra("msg", "nextpage");

    PendingIntent pendingNextPage = PendingIntent.getBroadcast(context, 2, nextPage, 0);

    remoteViews.setOnClickPendingIntent(R.id.button2, pendingNextPage);

    Intent prevPage = new Intent(context, MyWidget.class);
    prevPage.setAction(ACTION_WIDGET_RECEIVER);
    prevPage.putExtra("msg", "prevpage");

    PendingIntent pendingPrevPage = PendingIntent.getBroadcast(context, 3, prevPage, 0);

    remoteViews.setOnClickPendingIntent(R.id.button1, pendingPrevPage);


}

但我的小部件在logcat中崩溃了这条消息:

java.lang.RuntimeException:无法启动接收器my.widget.MyWidget:java.lang.NullPointerException

问题是什么?

1 个答案:

答案 0 :(得分:0)

Kaediil是对的,你必须通过在整个代码中放置Log.d()语句来缩小失败点。我看到很多地方指针仍然可以为空,从而抛出错误。这条线: thisWidget = new ComponentName(context,SteauaWidget.class); 看起来很奇怪。此外,由于错误特别提到 my.widget.MyWidget我可以理解MyWidget.class没有正确实例化,或者没有时间完成加载,从而产生以下NullPointerException。