当前位置 : 主页 > 手机开发 > android >

android中的自动完成功能无法使用动态数据

来源:互联网 收集:自由互联 发布时间:2021-06-11
我在 Android中面临自动完成的问题.我试图在匹配的每个按键上动态地从其他应用程序读取数据,而不是在Activity本身中对数据进行硬编码.请在下面找到我的程序,并建议我在哪里错了. 注意
我在 Android中面临自动完成的问题.我试图在匹配的每个按键上动态地从其他应用程序读取数据,而不是在Activity本身中对数据进行硬编码.请在下面找到我的程序,并建议我在哪里错了.

注意:在第一次按键时,结果将被填充.之后,如果我清除输入的文本并输入不同的字符,结果将不会显示在自动完成下拉框中.我在每次按键时从其他应用程序获取,但没有填充在自动完成下拉框中.

我尝试使用textView.showDropDown();和adapter.setNotifyOnChange(true);选项.但没用.

package com.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class HelloAutoCompleteActivity extends Activity {
List countries = new ArrayList();
    String url = ""; //some application url
AutoCompleteTextView textView;
ArrayAdapter<String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
    textView.addTextChangedListener(new CostomTextWatcher());
    textView.setThreshold(1);
    adapter = new ArrayAdapter<String>(this, R.layout.list_item, countries);
    textView.setAdapter(adapter);
}

private class CostomTextWatcher implements TextWatcher {

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        if (s.length() > 0) {
            countries.clear();
            String readTwitterFeed = readFeed(s.toString());
            System.out.println(readTwitterFeed);
            try {
                JSONObject menuObject = new JSONObject(readTwitterFeed);
                JSONArray menuitemArray = menuObject
                        .getJSONArray("objectNameList");
                for (int i = 0; i < menuitemArray.length(); i++) {
                    System.out.println(menuitemArray.get(i));
                    countries.add(menuitemArray.get(i).toString());
                }
                // adapter.notifyDataSetChanged();
                // adapter.setNotifyOnChange(true);
                // textView.setAdapter(adapter);
                // textView.setThreshold(1);
                // textView.setAdapter(adapter);
                // textView.showDropDown();
                // adapter.setNotifyOnChange(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

public String readFeed(String val) {

    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(
            url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            System.out.println("200");
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            System.out.println("else block");
            Log.e(HelloAutoCompleteActivity.class.toString(),
                    "Failed to download file");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return builder.toString();
}

}

您也可以使用Filter接口来实现此功能.事实证明,Filter.performFiltering()仅在此类目的的情况下从UI线程调用.以下是我用来执行此操作的一些代码:

Filter filter = new Filter() {

    @Override
    public CharSequence convertResultToString(Object resultValue) {
        return resultValue.toString();
    }

    @Override
    protected FilterResults performFiltering(CharSequence charSequence) {
        if( charSequence == null ) return null;
        try {
            // This call hits the server with the name I'm looking for and parses the JSON returned for the first 25 results
            PagedResult results = searchByName( charSequence.toString(), 1, 25, true);
            FilterResults filterResults = new FilterResults();
            filterResults.values = results.getResults();
            filterResults.count = results.getResults().size();
            return filterResults;
        } catch (JSONException e) {
            return new FilterResults();
        }
    }

    @Override
    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
        if( filterResults != null ) {
            adapter.clear();
            adapter.addAll( (List<MyObject>)filterResults.values );
        }
    }
};

然后使用Filter:

private AutoCompleteTextView beverageName;
    ...

    beverageName = findViewById( R.id.beverageName );
    ListAdapter adapter = ...
    adapter.setFilter(filter);
    beverageName.setAdapter(adapter);

或者你也可以使用这个链接

http://www.grobmeier.de/android-autocomplete-with-json-data-served-by-struts-2-05122011.html
网友评论