I found a lot of questions on the same topic. But I am unable to figure out what I am doing wrong here.
Exception: "The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread"
I have a TextWatcher to my AutoCompleteTextView. I am trying to update the dropdown list when the text changes. I am fetching data for the dropdown from two different sources. And each one of them running inside different threads.
mTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable editable) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
suggestionNewText = s.toString();
list = new ArrayList<Map<String, String>>();
runOnUiThread(new Runnable() {
@Override
public void run() {
//data processing
list.add(data);
handler.sendEmptyMessage(1);
}
});
Thread webAutoComplete = new Thread(new Runnable() {
@Override
public void run() {
//data process
list.add(data);
handler.sendEmptyMessage(1);
}
});
try {
webAutoComplete.start();
} catch (NullPointerException e) {
} catch (IllegalStateException e) {
}
}
};
And the handler for the adapter is next to the textwatcher.
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1: {
((Activity) CONTEXT).runOnUiThread(new Runnable() {
public void run() {
try {
if (list != null)
suggestionAdapter = new UrlSuggestionAdapter(
CONTEXT,
list,
R.layout.two_line_autocomplete,
new String[] { "title", "url" },
new int[] { R.id.title, R.id.url
});
if (list != null) {
refreshAdapter(list);
getUrl.setAdapter(suggestionAdapter);
}
} catch (Exception e) {
}
}
});
break;
}
case 2: {
break;
}
}
}
};
public synchronized void refreshAdapter(List<Map<String, String>> items) {
list = items;
if (list != null) {
suggestionAdapter.notifyDataSetChanged();
}
}
The whole code above is inside Activity's OnCreate() method. I don't get the exception always. It happens on specific occasion. This issue is not yet resolved. I have added the notifydatasetchanged() method after the creation of adapter. Still that doesn't solve the problem. Can anyone point out what I am doing wrong here?
Fixed the error by adding
suggestionAdapter.notifyDataSetChanged();
on whenever the list is changed instead of calling it after a n number of insertions.