我有一个简单的小部件,我尝试在onUpdate方法之外更新其内容。我创建了:上下文和appWidgetManager字段变量,并且编译器未给出任何错误,但是在声明AppWidgetManager的这两行中收到了NullPointerException异常。
有人可以帮助我理解为什么将它们转换为字段变量仍能使NPE保持静止吗?
private void ref(int z) {
views.setTextViewText(R.id.igePrint, ige[z].azIge);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, views);
//Log.e("<<check value>>", "the value of z is: " + z);
}
以及其余的一些代码:
package com.example.napiige;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.TextView;
public class MainActivity extends AppWidgetProvider {
RemoteViews views;
String azIge;
String igeBack;
static MainActivity[] ige = new MainActivity[3];
int x;
public static ComponentName thisWidget;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
x = (Integer)msg.obj;
ref(x);
}
};
Context context;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
views = new RemoteViews(context.getPackageName(), R.layout.example_appwidget);
thisWidget = new ComponentName(context, MainActivity.class);
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this provider
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
String ig1 = context.getString(R.string.ige1);
String ig2 = context.getString(R.string.ige2);
String ig3 = context.getString(R.string.ige3);
ige = new MainActivity[3];
ige[0] = new MainActivity();
ige[1] = new MainActivity();
ige[2] = new MainActivity();
ige[0].azIge = ig1;
ige[1].azIge = ig2;
ige[2].azIge = ig3;
Runnable myRunnable1 = new Task();
Thread myThread = new Thread(myRunnable1);
myThread.start();
appWidgetManager.updateAppWidget(thisWidget, views);
}
}
private void ref(int z) {
views.setTextViewText(R.id.igePrint, ige[z].azIge);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, views);
//Log.e("<<check value>>", "the value of z is: " + z);
}
class Task implements Runnable {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(3000);
// refreshing the text inside the loop calling the above refreshTextView method
int data = i;
Message msg = handler.obtainMessage(1, (int)data);
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
最佳答案
此处的appWidgetManager
字段为null,因为您从未为其分配值。