Android Widget:java.lang.NullPointerException

时间:2012-01-11 12:25:12

标签: android widget nullpointerexception

我写了一个带有alarmmanager的Android小部件作为更新过程。有时候我有一个nullpointer异常。但所有对象都已初始化......

public void UpdateWidget(Context con)
{
    //Log.d("berlinClock", "UpdateWidget="+i);
    RemoteViews views=new RemoteViews(con.getPackageName(),R.layout.widgetlayout);
    Calendar c = Calendar.getInstance(); 
    int h = c.get(Calendar.HOUR_OF_DAY);
    int m = c.get(Calendar.MINUTE);

    ComponentName thisWidget = new ComponentName(con,widget.class);

    //update views on remoteView
    // GOT NULLPOINTER EXEPTION IN FOLLOWING LINE
    views.setImageViewResource(R.id.wha1, R.drawable.cgrau);
    views.setImageViewResource(R.id.wha2, R.drawable.cgrau);
    ...
    }

这是Stacktrace:

java.lang.RuntimeException: Unable to start receiver ms.jung.android.berlinclock.widget: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2821)
at android.app.ActivityThread.access$3200(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2083)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at ms.jung.android.berlinclock.widget.UpdateWidget(widget.java:96)
at ms.jung.android.berlinclock.widget.onReceive(widget.java:34)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2810)

2 个答案:

答案 0 :(得分:1)

if(views!=null)
{
    ...
}

有了这个if条件它就不会崩溃了,我现在在许多例子中看到了这个解决方案,我认为这是最好的方法。

答案 1 :(得分:0)

我认为可能是因为您的RemoteViews对象尚未充气。

您可以尝试将视图放在布局中,并使该布局膨胀。

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RemoteViews view = inflater.inflate(R.layout.widgetlayout,null);