如何实现搜索(编辑文本)功能?

时间:2022-06-01 20:25:12

I have a listview that gets all words from sqlite and a edittext (that I want to filter/search words from the database).

我有一个listview,可以从sqlite和edittext获取所有单词(我想从数据库中过滤/搜索单词)。

I would like to implement a TextWatcher, it's much better, but I don't know how to do it using my code. I'm a newbie.

我想实现一个TextWatcher,它更好,但我不知道如何使用我的代码。我是新手。

public class DictionaryListActivity extends Activity {

TextView userTextView;
EditText searchEditText;

ListView dictionaryListView;

String logTagString="DICTIONARY";
ArrayList<WordDefinition> allWordDefinitions=new ArrayList<WordDefinition>();


DictionaryDatabaseHelper myDictionaryDatabaseHelper;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dictionary_list);

    Log.d("DICTIONARY", "second activity started");


    userTextView=(TextView) findViewById(R.id.personTextView);
    userTextView.setText(getIntent().getStringExtra(MainActivity.USER_NAME_STRING)+"'s Dictionary");

    searchEditText=(EditText) findViewById(R.id.searchEditText);

    dictionaryListView=(ListView) findViewById(R.id.dictionaryListView);

    myDictionaryDatabaseHelper=new DictionaryDatabaseHelper(this, "Dictionary", null, 1);
    sharedPreferences=getSharedPreferences(MainActivity.SHARED_NAME_STRING, MODE_PRIVATE);


    boolean initialized=sharedPreferences.getBoolean("initialized", false);

    if (initialized==false) {
        //Log.d(logTagString, "initializing for the first time");
        initializeDatabase();
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putBoolean("initialized", true);
        editor.commit();

    }else {
        Log.d(logTagString, "db already initialized");
    }

    allWordDefinitions=myDictionaryDatabaseHelper.getAllWords();

    dictionaryListView.setAdapter(new BaseAdapter() {

        @Override
        public View getView(int position, View view, ViewGroup arg2) {
            if (view==null) {
                view=getLayoutInflater().inflate(R.layout.list_item, null);
            }
            TextView textView=(TextView) view.findViewById(R.id.listItemTextView);
            textView.setText(allWordDefinitions.get(position).word);

            return view;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return allWordDefinitions.size();
        }
    });

    dictionaryListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position,
                long arg3) {
            Intent intent =new Intent(DictionaryListActivity.this, WordDefinitionDetailActivity.class);
            intent.putExtra("word", allWordDefinitions.get(position).word);
            intent.putExtra("definition", allWordDefinitions.get(position).definition);

            startActivity(intent);
        }
    });



private void initializeDatabase() {
    InputStream inputStream=getResources().openRawResource(R.raw.dictionary);
    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
    DictionaryLoader.loadData(bufferedReader, myDictionaryDatabaseHelper);

}

 }

DictionaryDatabaseHelper

public class DictionaryDatabaseHelper extends SQLiteOpenHelper {

final static String DICTIONARY_DATABASE="dictionary";
final static String ITEM_ID_COLUMN="id";
final static String WORD_COLUMN="word";
final static String DEFINITION_COLUMN="definition";


final static String CREATE_DATABASE_QUERY="CREATE TABLE "+DICTIONARY_DATABASE+" ( "+
ITEM_ID_COLUMN+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
WORD_COLUMN+" TEXT , "+
DEFINITION_COLUMN+" TEXT)";


final static String ON_UPGRADE_QUERY="DROP TABLE "+DICTIONARY_DATABASE;

Context context;


public DictionaryDatabaseHelper(Context context, String name,
        CursorFactory factory, int version) {
    super(context, DICTIONARY_DATABASE, factory, version);
    this.context=context;

}

@Override
public void onCreate(SQLiteDatabase database) {
        database.execSQL(CREATE_DATABASE_QUERY);    
}

@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
    database.execSQL(ON_UPGRADE_QUERY);
    onCreate(database);

}

public long insertData(WordDefinition wordDefinition) {
    SQLiteDatabase database=this.getWritableDatabase();
    ContentValues values=new ContentValues();

    values.put(WORD_COLUMN, wordDefinition.word);
    values.put(DEFINITION_COLUMN, wordDefinition.definition);

    return database.insert(DICTIONARY_DATABASE, null, values);      

}

public long updateData(WordDefinition wordDefinition) {
    SQLiteDatabase database=this.getWritableDatabase();
    ContentValues values=new ContentValues();

    values.put(WORD_COLUMN, wordDefinition.word);
    values.put(DEFINITION_COLUMN, wordDefinition.definition);

    return database.update(DICTIONARY_DATABASE, values, WORD_COLUMN+" =?", new String[]{wordDefinition.word});  

}

public void deleteData(WordDefinition wordDefinition) {
    SQLiteDatabase database=this.getWritableDatabase();
    String queryString="DELETE FROM "+DICTIONARY_DATABASE+" WHERE "+WORD_COLUMN+" = '"+wordDefinition.word+"'";

    database.execSQL(queryString);
}

public ArrayList<WordDefinition> getAllWords() {
    ArrayList<WordDefinition> arrayList=new ArrayList<WordDefinition>();
    SQLiteDatabase database=this.getReadableDatabase();

    String selectAllQueryString="SELECT * FROM "+DICTIONARY_DATABASE;
    Cursor cursor=database.rawQuery(selectAllQueryString, null);

    if (cursor.moveToFirst()) {
        do {            
            WordDefinition wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(WORD_COLUMN)), cursor.getString(cursor.getColumnIndex(DEFINITION_COLUMN)));
            arrayList.add(wordDefinition);              
        } while (cursor.moveToNext());          
    }   
    return arrayList;
}

public WordDefinition getWordDefinition(String word) {
    SQLiteDatabase database=this.getReadableDatabase();
    WordDefinition wordDefinition=null;

    String selectQueryString="SELECT * FROM "+DICTIONARY_DATABASE+ " WHERE "+WORD_COLUMN+" = '"+word+ "'";
    Cursor cursor=database.rawQuery(selectQueryString, null);

    if (cursor.moveToFirst()) {
        wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(WORD_COLUMN)), cursor.getString(cursor.getColumnIndex(DEFINITION_COLUMN)));

    }   

    return wordDefinition;

}

public WordDefinition getWordDefinition(long id) {
    SQLiteDatabase database=this.getReadableDatabase();
    WordDefinition wordDefinition=null;

    String selectQueryString="SELECT * FROM "+DICTIONARY_DATABASE+ " WHERE "+ITEM_ID_COLUMN+" = '"+id+ "'";
    Cursor cursor=database.rawQuery(selectQueryString, null);

    if (cursor.moveToFirst()) {
        wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(WORD_COLUMN)), cursor.getString(cursor.getColumnIndex(DEFINITION_COLUMN)));

    }   

    return wordDefinition;

}

public void initializeDatabaseFortheFirstTime(ArrayList<WordDefinition> wordDefinitions) {
    SQLiteDatabase database=this.getWritableDatabase();
    database.execSQL("BEGIN");

    ContentValues contentValues=new ContentValues();

    for (WordDefinition wordDefinition : wordDefinitions) {
        contentValues.put(WORD_COLUMN, wordDefinition.word);
        contentValues.put(DEFINITION_COLUMN, wordDefinition.definition);            
        database.insert(DICTIONARY_DATABASE, null, contentValues);
    }
    database.execSQL("COMMIT");

}


}

1 个解决方案

#1


0  

Try this following code:

请尝试以下代码:

Globally you need to defined searchProducts.

在全球范围内,您需要定义searchProducts。

List<WordDefinition> searchProducts;  

searchEditText.addTextChangedListener(new TextWatcher() {

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

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

       @Override
        public void afterTextChanged(Editable s) {
         String text = s.toString();
         getSearchResult(text);
        }
});

In method of getSearchResult you can see searching logic. You can change as per your requirements.

在getSearchResult的方法中,您可以看到搜索逻辑。您可以根据自己的要求进行更改。

public void getSearchResult(String s) {
                    myDictionaryDatabaseHelper=new DictionaryDatabaseHelper(this, "Dictionary", null, 1);
                    allWordDefinitions=myDictionaryDatabaseHelper.getAllWords();
                    searchProducts = new ArrayList<WordDefinition>();

                    for (int i = 0; i < allWordDefinitions.size(); i++) {
                        if (s.equals("")) {
                        } else {
                        if (allWordDefinitions.get(i).YOUR_MODEL_METHODNAME
                                    .toLowerCase(Locale.getDefault()).contains(s)) {
                            searchProducts.add(allWordDefinitions.get(i));
                        }
                    }
                listUpdate(searchProducts);
            }

        }

        private void listUpdate(List<WordDefinition> searchProducts) {
          // Here you call your adapter.
        }

If code works for you then please mark it as acceptable.

如果代码适合您,请将其标记为可接受。

#1


0  

Try this following code:

请尝试以下代码:

Globally you need to defined searchProducts.

在全球范围内,您需要定义searchProducts。

List<WordDefinition> searchProducts;  

searchEditText.addTextChangedListener(new TextWatcher() {

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

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

       @Override
        public void afterTextChanged(Editable s) {
         String text = s.toString();
         getSearchResult(text);
        }
});

In method of getSearchResult you can see searching logic. You can change as per your requirements.

在getSearchResult的方法中,您可以看到搜索逻辑。您可以根据自己的要求进行更改。

public void getSearchResult(String s) {
                    myDictionaryDatabaseHelper=new DictionaryDatabaseHelper(this, "Dictionary", null, 1);
                    allWordDefinitions=myDictionaryDatabaseHelper.getAllWords();
                    searchProducts = new ArrayList<WordDefinition>();

                    for (int i = 0; i < allWordDefinitions.size(); i++) {
                        if (s.equals("")) {
                        } else {
                        if (allWordDefinitions.get(i).YOUR_MODEL_METHODNAME
                                    .toLowerCase(Locale.getDefault()).contains(s)) {
                            searchProducts.add(allWordDefinitions.get(i));
                        }
                    }
                listUpdate(searchProducts);
            }

        }

        private void listUpdate(List<WordDefinition> searchProducts) {
          // Here you call your adapter.
        }

If code works for you then please mark it as acceptable.

如果代码适合您,请将其标记为可接受。