Reputation: 16777
I have a LinearLayout with programmatically added children:
for (int i = 0; i < answers.size(); i++) {
final AnswerView answerView = new AnswerView(getContext(), i);
addView(answerView);
}
Then I'm trying to access random child:
private void updateOpenAnswer() {
new AsyncTask<Void, Void, Integer>() {
@Override
protected Integer doInBackground(Void... voids) {
return API.getOpenAnswer();
}
@Override
protected void onPostExecute(Integer answerIndex) {
super.onPostExecute(answerIndex);
Log.i(TAG, "Child count: " + getChildCount());
if (answerIndex != -1) {
Log.i(TAG, "Open answer: " + answerIndex);
final AnswerView answerView = (AnswerView) getChildAt(answerIndex);
if (answerView != null) {
answerView.setAnswerOpen(true);
} else {
Log.e(TAG, "Null at " + answerIndex);
}
}
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
updateOpenAnswer is called once in a second in runnable. And for some calls of updateOpenAnswer getChildAt returns null and getChildCount returns 0! For example, null for 2 and 3, and not null for 0,1,4,5. The views at 2 and 3 really exist and I see them. Why it returns null?
Upvotes: 0
Views: 2052
Reputation: 33505
final AnswerView answerView = new AnswerView(getContext(), i);
Most likely problem is getContext()
that returns null. Try to change it to
YourActivity.this // this also returns Context
And now it should works.
Don't remember that getChildAt()
will return a view only for the positions which are displaying. So if you are scrolling and want to get child that is not "in View" null will be returned.
Upvotes: 1