2012-02-10 100 views
0

我正在做一個有3個按鈕的小部件。我需要爲每個按鈕調用一個函數。我這樣做是這樣的:android widget按鈕崩潰

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

有什麼問題?

+0

你能告訴我空行指針是什麼行嗎?發佈實際的logcat。如果這裏什麼都沒有,我會把LOG信息放進去,看看它在哪裏崩潰。 – Kaediil 2012-02-10 20:57:03

回答

0

Kaediil是對的,你必須通過在代碼中放置Log.d()語句來縮小故障點。我看到很多地方的指針可能仍然是空的,從而拋出錯誤。該行: thisWidget = new ComponentName(context,SteauaWidget.class); 看起來很奇怪。另外,由於錯誤特別提到了 my.widget.MyWidget,它有理由說MyWidget.class沒有正確實例化,或者沒有給出時間來完成加載,從而產生下面的NullPointerException。