Hello,
I have just this piece of code which is quite simple. I have a list and in the onCreate method I added some objects to this list to show them on the screen. I have a broadcast receiver which has to enable/disable some elements of the list when there aren't internet connection.
The broadcast receiver works good if the connection is lost when the application is already in the screen of this activity. The problem is when there is no connection before entering this activity. In this case after calling oncreate() method in the onresume() the receiver is registered, but when I call getListView() inside the receiver it hasn't got any child (though I've added to the adaptor in the oncreate method and I haven't loaded then using any thread at all).
Can anyone tell me why this is happening?
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);
}
}
Thanks