2014-02-14 31 views
1

此代碼通過顯示數據庫中的所有數據正常工作,但我在過濾中遇到問題。我嘗試了很多代碼,但沒有任何工作,有人可以幫我嗎?感謝過濾SimpleCursorAdapter

package com.example.dictionary; 


    import java.util.List; 
    import com.example.dictionary.R; 
    import android.os.Bundle; 
    import android.app.Activity; 
    import android.database.Cursor; 
    import android.support.v4.widget.SimpleCursorAdapter; 
    import android.text.Editable; 
    import android.text.TextWatcher; 
    import android.widget.Button; 
    import android.widget.EditText; 
    import android.widget.ListView; 


    public class MainActivity extends Activity{ 
     Cursor cursor; 
     ListView listView; 
     SimpleCursorAdapter adapter; 
     Button back, clear; 
     List<String> items; 
     String get; 
     EditText et; 
     int textlength = 0; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     et = (EditText) findViewById(R.id.editText1); 

打開我的數據庫,並獲得所有數據

 Historydb db = new Historydb(this); 
     db.open();   
     cursor = db.getword(); 
     startManagingCursor(cursor); 
     cursor.moveToFirst(); 
     adapter = new SimpleCursorAdapter(this, 
        android.R.layout.simple_list_item_1, cursor, 
        new String[] { "word" }, new int[] { android.R.id.text1 }); 

     listView = (ListView) findViewById(R.id.listView1); 
     listView.setAdapter(adapter); 

我在的EditText設置addtextchangelistener。

 et.addTextChangedListener(new TextWatcher() { 
     public void afterTextChanged(Editable s) { 

     // Abstract Method of TextWatcher Interface. 
     } 

     public void beforeTextChanged(CharSequence s, int start, int count,int after) { 
     // Abstract Method of TextWatcher Interface. 

     } 
      public void onTextChanged(CharSequence s, int start, int before,int count) { 


      adapter.getFilter().filter(s); 


      }}); 
    } 

} 

回答

2

它不工作,因爲adapter.getfilter().filter(cs);不適合SimpleCursorAdapter直接工作。 您必須首先使用adapter.setFilterQueryProvider來代替SimpleCursorAdapter

這裏是完整的描述:ListView, SimpleCursorAdapter, an an EditText filter -- why won't it do anything?

這:Using an EditText to filter a SimpleCursorAdapter-backed ListView

+0

感謝先生adam此線程爲我工作http://stackoverflow.com/questions/5322412/listview-simplecursoradapter-an-an-edittext-filter-why-wont-it-do-anything –

2

試試這個....

@Override 
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { 
// When user changed the Text 
((SimpleAdapter) YourActivity.this.adapter).getFilter().filter(cs); 
} 
+1

感謝先生,但是它不能正常工作。 –

+0

你用我的代碼試過了什麼?意思是可以在編輯後發佈代碼? –

+0

public void onTextChanged(CharSequence s,int start,int before,int count){(SimpleCursorAdapter)MainActivity.this.adapter).getFilter()。filter(s); } 這裏sir Anil –