Android AutocompleteTextView错误:IllegalStateException:适配器的内容已更改,但ListView未收到通知
当在AutocompleteTextView上取消或键入fast时,我在这个类中有一个IllegalStateException错误。我读过一些关于这方面的文章,但我不能解决这个问题。 有人能更正我的代码吗 感谢您的帮助!! (对不起,我的英语不好) 这是全部错误:Android AutocompleteTextView错误:IllegalStateException:适配器的内容已更改,但ListView未收到通知,android,autocompletetextview,illegalstateexception,Android,Autocompletetextview,Illegalstateexception,当在AutocompleteTextView上取消或键入fast时,我在这个类中有一个IllegalStateException错误。我读过一些关于这方面的文章,但我不能解决这个问题。 有人能更正我的代码吗 感谢您的帮助!! (对不起,我的英语不好) 这是全部错误: java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notifica
java.lang.IllegalStateException: 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. [in ListView(-1, class android.widget.ListPopupWindow$DropDownListView) with Adapter(class com.turkeys.planandgo.Activity.MapActivity$AutoComplete)]
这是我的班级:
public class AutoComplete extends ArrayAdapter<String> implements Filterable {
private static final String LOG_TAG = "carEgiri";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "AIzaSyCDycjwe51YuMe7Sx8nHv9Z6C-kBGPEQ64";
private ArrayList<String> resultList;
private ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?sensor=false&key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
Log.d("====", "Requesst send");
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
Log.d("JSON","Parsing resultant JSON :)");
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
Log.d("JSON","predsJsonArray has length " + predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
Log.d("JSON",resultList.get(i));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
public AutoComplete(Context context, int textViewResourceId) {
super((Context) context, textViewResourceId);
}
@Override
public int getCount() {
if (resultList == null)
return 0;
return resultList.size();
}
@Override
public String getItem(int index) {
return resultList.get(index);
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint,FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
公共类自动完成扩展ArrayAdapter实现可过滤{
私有静态最终字符串日志\u TAG=“carEgiri”;
私有静态最终字符串PLACES\u API\u BASE=”https://maps.googleapis.com/maps/api/place";
私有静态最终字符串类型\u AUTOCOMPLETE=“/AUTOCOMPLETE”;
私有静态最终字符串输出_JSON=“/JSON”;
私有静态最终字符串API_KEY=“AIzaSyCDycjwe51YuMe7Sx8nHv9Z6C-kBGPEQ64”;
私有ArrayList结果列表;
专用ArrayList自动完成(字符串输入){
ArrayList resultList=null;
HttpURLConnection conn=null;
StringBuilder jsonResults=新建StringBuilder();
试一试{
StringBuilder sb=新的StringBuilder(PLACES\u API\u BASE+TYPE\u AUTOCOMPLETE+OUT\u JSON);
sb.追加(“?传感器=假&键=“+API_键”);
sb.append(“&input=“+urlcoder.encode”(输入,“utf8”));
URL=新URL(sb.toString());
conn=(HttpURLConnection)url.openConnection();
InputStreamReader in=新的InputStreamReader(conn.getInputStream());
Log.d(“=”,“请求发送”);
//将结果加载到StringBuilder中
int-read;
char[]buff=新字符[1024];
while((read=in.read(buff))!=-1){
附加(buff,0,read);
}
}捕获(格式错误){
e(Log_标记,“错误处理位置API URL”,e);
返回结果列表;
}捕获(IOE异常){
Log.e(Log_标签,“连接到位置API时出错”,e);
返回结果列表;
}最后{
如果(conn!=null){
连接断开();
}
}
试一试{
//根据结果创建JSON对象层次结构
Log.d(“JSON”,“解析结果JSON:)”;
JSONObject jsonObj=新的JSONObject(jsonResults.toString());
JSONArray predsjssonarray=jsonObj.getJSONArray(“预测”);
//从结果中提取位置描述
resultList=新的ArrayList(predsjSonaray.length());
Log.d(“JSON”,“predsJsonArray具有长度”+predsJsonArray.length());
对于(int i=0;i0){
notifyDataSetChanged();
}否则{
notifyDataSetionValidated();
}
}
};
回流过滤器;
}
}
请从performFiltering
方法中删除结果列表<代码>performFiltering方法正在后台线程中运行。信息更清晰 在响应网络调用方法add notifyDataSetChanged()时,我遇到了同样的问题,经过大量调试和研究,我通过覆盖notifyDataSetChanged()并评估suggestionList的大小来解决问题。它可能会帮助某人。代码片段如下所示:
private int size = 0;
@Override
public void notifyDataSetChanged() {
size = suggestionList.size();
super.notifyDataSetChanged();
}
并将getCount()中的大小返回为:
我的案例(应用程序)中的自定义过滤器如下所示:
private class CustomFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
suggestions.clear();
FilterResults filterResults = new FilterResults();
try {
if (originalList != null && constraint != null) { // Check if the Original List and Constraint aren't null.
try {
for (int i = 0; i < originalList.size(); i++) {
// if (originalList.get(i).toLowerCase().contains(constraint)) {
if (originalList.get(i).toLowerCase().contains(constraint.toString().toLowerCase())) {
suggestionList.add(originalList.get(i)); // If TRUE add item in Suggestions.
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
// Create new Filter Results and return this to publishResults;
filterResults.values = suggestionList;
filterResults.count = suggestionList.size();
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
私有类CustomFilter扩展了筛选器{
@凌驾
受保护的筛选器结果性能筛选(CharSequence约束){
建议。清晰();
FilterResults FilterResults=新的FilterResults();
试一试{
如果(originalList!=null&&constraint!=null){//检查原始列表和约束是否不是null。
试一试{
对于(int i=0;iprivate class CustomFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
suggestions.clear();
FilterResults filterResults = new FilterResults();
try {
if (originalList != null && constraint != null) { // Check if the Original List and Constraint aren't null.
try {
for (int i = 0; i < originalList.size(); i++) {
// if (originalList.get(i).toLowerCase().contains(constraint)) {
if (originalList.get(i).toLowerCase().contains(constraint.toString().toLowerCase())) {
suggestionList.add(originalList.get(i)); // If TRUE add item in Suggestions.
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
// Create new Filter Results and return this to publishResults;
filterResults.values = suggestionList;
filterResults.count = suggestionList.size();
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
//suggestions dataset
ArrayList<Item> suggestions = new ArrayList<>();
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
// rewrite array or clear it and fill new items in it
suggestions = (ArrayList<Item>)results.values
notifyDataSetChanged();
}
}
@Override
public int getCount() {
return suggestions.size();
}