我只有这段代码,非常简单。我有一个列表,在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);
}
}
谢谢