私は非常に単純なこのコードを持っています。リストがあり、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);
}
}
ありがとう