我试图在我的应用程序中使用statuc变量来跟踪某个变量,我的服务代码,我只粘贴了必要的内容
public class TestService extends Service {
public static HashMap<Long, Integer> testMap;
@Override
public void onCreate() {
registerReceiver();
testMap = new HashMap<Long, Integer>();
}
private final BroadcastReceiver testReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(UPDATE)) {
long key = intent.getLongExtra("key", -1);
int value = intent.getIntExtra("value", -1);
//Make sure I insert it once for testing purposes
if (testMap.get(key) == null)
testMap.put(key, value);
//This one prints the value fine
Log.i(TAG,testMap.get(key));
}
}
};
}然后我尝试在我的游标适配器中访问它,但是我总是得到null,
private static class MyCursorAdapter extends CursorAdapter {
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.test_layout, parent, false);
}
@Override
public void bindView(View view, final Context context, Cursor cursor) {
Integer value = TestService.testMap.get(key);
//When I check value here, it's always null
if (value != null)
Log.i(TAG, value)
else
Log.i(TAG, "Key value is NULL")
}}
我做错了什么?
发布于 2015-03-30 03:17:17
确保您没有完成您的服务,因为每次它调用onCreate()时,您都在重新初始化您的静态变量。顺便说一句,这不是一个好的方法,此外,静态全局变量也不是一个好主意。您应该通过意图或绑定来与您的服务通信,而不是共享静态变量。
https://stackoverflow.com/questions/29333466
复制相似问题