2014-01-31 14 views
0

我有autocomletetextview,它從服務器獲取json響應。當文本逐個輸入但快速輸入文本時,它工作正常。以前的數據與新的自動完成文本視圖一起輸入

它增加了每個字母的值,這是最後一個響應的列表。我已經嘗試了下面的代碼。我該如何解決這個問題?我非常感謝任何幫助。感謝提前。

BaseActivity:

public class SimpleAdapter extends BaseAdapter { 

    private Activity activity; 
    private ArrayList<HashMap<String, String>> data; 
    private static LayoutInflater inflater=null; 
    public ImageLoader imageLoader ; 
    Bitmap image; 
    private DisplayImageOptions defaultOptions; 

    public SimpleAdapter(Activity a, ArrayList<HashMap<String, String>> d) { 
     activity = a; 
     data=d; 
     inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     defaultOptions = new DisplayImageOptions.Builder().build(); 

     ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(activity) 
     .threadPoolSize(2) 
     .memoryCache(new WeakMemoryCache()) 
     .discCacheFileNameGenerator(new Md5FileNameGenerator()) 
     .build(); 

     imageLoader = ImageLoader.getInstance(); 

    imageLoader.init(config); 

     imageLoader.init(ImageLoaderConfiguration.createDefault(activity)); 
    } 

    public int getCount() { 
     return data.size(); 
    } 

    public Object getItem(int position) { 
     return position; 
    } 

    public long getItemId(int position) { 
     return position; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     View vi=convertView; 
     if(convertView==null) 
      vi = inflater.inflate(R.layout.list_row, null); 

     TextView title = (TextView)vi.findViewById(R.id.textView1); // title 
     TextView artist = (TextView)vi.findViewById(R.id.textView2); // artist name 
     TextView duration = (TextView)vi.findViewById(R.id.textView3); // duration 
     ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image 

     HashMap<String, String> song = new HashMap<String, String>(); 
     song = data.get(position); 

     // Setting all values in listview 
     title.setText(song.get("firstname")); 
     artist.setText(song.get("lastname")); 
     duration.setText(song.get("time")); 
     imageLoader.displayImage(song.get("link"), thumb_image, defaultOptions); 

     return vi; 
    } 


} 

MainActivity

public class AutoCompleteTextViewActivity extends Activity implements TextWatcher{ 
     /** Called when the activity is first created. */ 
     private TextView selection; 
     private AutoCompleteTextView actv; 


     SimpleAdapter adapter; 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      selection=(TextView)findViewById(R.id.selection); 
      actv=(AutoCompleteTextView)findViewById(R.id.actv); 
      actv.addTextChangedListener(this); 



     } 

     public void afterTextChanged(Editable s) { 
      // 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) { 

      Suggest Suggestdetails=new Suggest(); 
     if(aList!=null){ 

      Suggestdetails.execute(); 
     aList.clear(); 
      } else{ 

     listView.setAdapter(adapter); 
     adapter.notifyDataSetChanged(); 

} 


     } 

     public class Suggest extends AsyncTask<Void, Void, JSONObject> { 
      @Override 
      protected JSONObject doInBackground(Void... params) { 

       String ResponseBody = null; 

       try { 


        //geoaddress here 

        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost("http://example.com/suggest.php"); 

        // Add your data 
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 

        nameValuePairs.add(new BasicNameValuePair("name", actv.getText().toString())); 


        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

        // Execute HTTP Post Request 
        HttpResponse response = httpclient.execute(httppost); 

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "iso-8859-1"), 8); 
        StringBuilder sb = new StringBuilder(); 
        sb.append(reader.readLine() + "\n"); 
        String line = "0"; 
        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 
        reader.close(); 
        String result = sb.toString(); 

        Log.d("Fb tr",result); 
        // parsing data 
        return new JSONObject(result); 
       } catch (Exception e) { 
        e.printStackTrace(); 
        return null; 
       } 
      } 



      @Override 
      protected void onPostExecute(JSONObject result) { 




       if (result != null) { 
        // do something 
    //    JSONObject tr = result; 

      List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>(); 

       try{ 
        JSONArray arr=result.getJSONArray("Array"); 


       for(int i=0;i<arr.length();i++) 
       { 
        JSONObject e1 = arr.getJSONObject(i); 

        JSONObject json= (JSONObject) e1.get("data"); 

        String firstname = json.getString("firstname").trim(); 
        String lastname = json.getString("lastname").trim(); 
        String link = json.getString("link").trim(); 
        String time = json.getString("time").trim(); 


        HashMap<String, String> hm = new HashMap<String,String>(); 
         hm.put("firstname", firstname); 
         hm.put("lastname", lastname); 
         hm.put("link", link); 
         hm.put("time", time); 
         aList.add(hm); 

        } 


       }catch(Exception e){ 
        e.printStackTrace(); 

       } 


       String[] from = { "firstname","lastname","time","link"}; 


       int[] to = { R.id.textView1,R.id.textView2,R.id.textView3,R.id.list_image}; 

       adapter = new SimpleAdapter(AutoCompleteTextViewActivity.this,aList, R.layout.list_row,from,to); 

        actv.setAdapter(adapter); 

        adapter.notifyDataSetChanged(); 


       } else { 
        // error occured 
       } 
      } 


     } 

    } 
+0

看到我的答案在這裏的http: //stackoverflow.com/questions/19858843/how-to-dynamically-add-suggestions-to- autocompletetextview-with-preserving-chara – pskink

+0

@pskink它也有圖像。我昨天發佈了相同的查詢,你建議Spannanble,但你檢查並說,它不會工作。 – jason

+0

aaa它是你....確定我會在十分鐘內用我修改過的光標回答 – pskink

回答

1

你的代碼更新,我希望它運行良好:d [更新]

public class AutoCompleteTextViewActivity extends Activity implements TextWatcher { 
     /** Called when the activity is first created. */ 
     private TextView selection; 
     private AutoCompleteTextView actv; 

     List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>(); 

     SimpleAdapter adapter; 
     private Suggest Suggestdetails; 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main); 
      selection=(TextView)findViewById(R.id.selection); 
      actv=(AutoCompleteTextView)findViewById(R.id.actv); 

      String[] from = { "firstname","lastname","time","link"}; 

      int[] to = { R.id.textView1,R.id.textView2,R.id.textView3,R.id.list_image}; 
      adapter = new SimpleAdapter(AutoCompleteTextViewActivity.this,aList, R.layout.list_row,from,to); 

      actv.setAdapter(adapter); 

      actv.addTextChangedListener(this); 
     } 

     public void afterTextChanged(Editable s) { 
      // 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) { 

      if (Suggestdetails!=null && Suggestdetails.getStatus().equals(AsyncTask.Status.RUNNING)){ 
       Suggestdetails.cancel(true); 
      } 

      Suggestdetails=new Suggest(); 
      Suggestdetails.execute(); 
     } 

     public class Suggest extends AsyncTask<Void, Void, List<HashMap<String,String>>> { 

      @Override 
      protected List<HashMap<String,String>> doInBackground(Void... params) { 

       String ResponseBody = null; 
       try { 
        //geoaddress here 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost("http://example.com/suggest.php"); 

        // Add your data 
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 

        nameValuePairs.add(new BasicNameValuePair("name", actv.getText().toString())); 

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

        // Execute HTTP Post Request 
        HttpResponse response = httpclient.execute(httppost); 

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "iso-8859-1"), 8); 
        StringBuilder sb = new StringBuilder(); 
        sb.append(reader.readLine() + "\n"); 
        String line = "0"; 
        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 

         if (isCancelled()) return null; 
        } 
        reader.close(); 
        String result = sb.toString(); 

        Log.d("Fb tr",result); 
        List<HashMap<String,String>> resultList = new ArrayList<HashMap<String,String>>(); 

        if (isCancelled()) return null; 

        try{ 
         JSONObject resultJson = new JSONObject(result); 
         JSONArray arr=resultJson.getJSONArray("Array"); 
         for(int i=0;i<arr.length();i++) 
         { 
          JSONObject e1 = arr.getJSONObject(i); 

          JSONObject json= (JSONObject) e1.get("data"); 

          String firstname = json.getString("firstname").trim(); 
          String lastname = json.getString("lastname").trim(); 
          String link = json.getString("link").trim(); 
          String time = json.getString("time").trim(); 


          HashMap<String, String> hm = new HashMap<String,String>(); 
          hm.put("firstname", firstname); 
          hm.put("lastname", lastname); 
          hm.put("link", link); 
          hm.put("time", time); 
          resultList.add(hm); 

          if (isCancelled()) return null; 

         } 
        }catch(Exception e){ 
         e.printStackTrace(); 
        } 
        return resultList; 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

       return null; 
      } 

      @Override 
      protected void onPostExecute(List<HashMap<String,String>>... result) { 
       if (result != null) { 
        aList.clear(); 
        aList.addAll(result[0]); 
        adapter.notifyDataSetChanged(); 
       } else { 
        // error occured 
       } 
      } 
     } 
    } 
+0

此代碼在postexecute中不起作用。當設置了適配器並在異步後通知了數據時,我在下拉列表中看不到任何數據。請查看它。謝謝 – jason

+0

我已更新代碼。我錯過了onPostExecute的參數。 –

+0

我得到這個錯誤'類型爲AutoCompleteTextViewActivity.Suggest的方法onPostExecute(List > ...)必須重載一個超類方法' – jason