autocomplete in android not working with dynamic data

前端 未结 2 1942
鱼传尺愫
鱼传尺愫 2021-01-19 09:16

I am facing problem with auto complete in android. Instead of hard coding data in Activity itself, I tried to read the data dynamically from other application on every key p

相关标签:
2条回答
  • 2021-01-19 09:33

    I don't know what JSON you are using to parse. But here is an example of dynamic auto complete using Wikipedia Suggest JSON. All you need to do is change the JSON Part.

    package com.yourapplication.wiki;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    
    import android.app.Activity;
    import android.os.AsyncTask;
    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 WikiSuggestActivity extends Activity {
        public String data;
        public List<String> suggest;
        public AutoCompleteTextView autoComplete;
        public ArrayAdapter<String> aAdapter;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            suggest = new ArrayList<String>();
            autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
            autoComplete.addTextChangedListener(new TextWatcher(){
    
                public void afterTextChanged(Editable editable) {
                    // TODO Auto-generated method stub
    
                }
    
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    // TODO Auto-generated method stub
    
                }
    
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    String newText = s.toString();
                    new getJson().execute(newText);
                }
    
            });
    
        }
       class getJson extends AsyncTask<String,String,String>{
    
        @Override
        protected String doInBackground(String... key) {
            String newText = key[0];
            newText = newText.trim();
            newText = newText.replace(" ", "+");
            try{
                HttpClient hClient = new DefaultHttpClient();
                HttpGet hGet = new HttpGet("http://en.wikipedia.org/w/api.php?action=opensearch&search="+newText+"&limit=8&namespace=0&format=json");
                ResponseHandler<String> rHandler = new BasicResponseHandler();
                data = hClient.execute(hGet,rHandler);
                suggest = new ArrayList<String>();
                JSONArray jArray = new JSONArray(data);
                for(int i=0;i<jArray.getJSONArray(1).length();i++){
                String SuggestKey = jArray.getJSONArray(1).getString(i);
                suggest.add(SuggestKey);
                }
    
            }catch(Exception e){
                Log.w("Error", e.getMessage());
            }
            runOnUiThread(new Runnable(){
                public void run(){
                     aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
                     autoComplete.setAdapter(aAdapter);
                     aAdapter.notifyDataSetChanged();
                }
            });
    
            return null;
        }
    
       }
    }
    

    Hope it helps Thank You!.

    0 讨论(0)
  • 2021-01-19 09:52

    You can use the Filter interface to implement this as well. Turns out Filter.performFiltering() is called off the UI thread just for this type of purpose. Here is some code I use to do this:

     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 );
            }
        }
    };
    

    Then using the Filter:

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

    or u can use this link also

    http://www.grobmeier.de/android-autocomplete-with-json-data-served-by-struts-2-05122011.html
    
    0 讨论(0)
提交回复
热议问题