我只有这段非常简单的代码。我有一个列表,在 onCreate 方法中我将一些对象添加到此列表中以在屏幕上显示它们。我有一个广播接收器,当没有互联网连接时,它必须启用/禁用列表的某些元素。
如果应用程序已经在此活动的屏幕中时连接丢失,则广播接收器可以正常工作。问题是在进入此活动之前没有连接。在这种情况下,在 onresume() 中调用 oncreate() 方法后,接收器已注册,但是当我在接收器内部调用 getListView() 时,它没有任何子对象(尽管我已在 oncreate 方法中添加到适配器并且我根本没有使用任何线程加载)。
谁能告诉我为什么会这样?
public class MyActivity extends ListActivity {
private List<MyClass> myObjects;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//check if internet connection is available
boolean networkAvailable = ... ;
if (!networkAvailable) {
//No Internet connection: disabled non-cached objects
List<MyClass> cachedObjects = getCachedObjects();
for(int i = 0; i<myObjects.size(); i++){
MyClass myObject = myObjects.get(i);
if (!cachedSurveys.contains(myObject)) {
ListView listView = getListView();
//The problem is here: listView is empty when there was no connection
//before creating the activity so the broadcast receiver was called in a sticky way
View child = listView.getChildAt(i);
child.setEnabled(false);
}
}
} else {
// Internet connection: enable all myObjects
int size = getListView().getChildCount();
for (int i = 0; i < size; i++) {
View child = getListView().getChildAt(i);
child.setEnabled(true);
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myObjects = getMyObjects();
setListAdapter(new ArrayAdapter<MyClass>(this, android.R.layout.simple_list_item_1, myObjects));
getListView().setTextFilterEnabled(true);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(receiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
}
谢谢