mercredi 8 juillet 2015

Search ListView using Filter

I have a list view with multiple items in row. I have also created a search box above.I want to implement search functionality on the basis of particular fields of the list.but problam is that when i type into EditText,Crashed...!

my codes:

import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.ListView;


public class Test extends Activity {

private MyDatabase            MyDataBase;
private SQLiteDatabase        mydb;
private ListView              list;
private AdapterNote           adapter;
private ArrayList<StructNote> itemLists = new ArrayList<StructNote>();
private EditText              edtTextSRCH;
public String                 SearchResult;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);

    edtTextSRCH = (EditText) findViewById(R.id.edtTextSRCH);
    list = (ListView) findViewById(R.id.list);
    adapter = new AdapterNote(itemLists);
    list.setAdapter(adapter);
    MyDataBase = new MyDatabase(this);
    mydb = MyDataBase.getReadableDatabase();

    fillFromDb(); //for fill items from database (Before search)

    //Search
    edtTextSRCH.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {

            SearchResult = edtTextSRCH.getText().toString();
            searchdatabase();
        }


        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}


        @Override
        public void afterTextChanged(Editable arg0) {}
    });

}


private void fillFromDb() {
    itemLists.clear();
    Cursor cursor = mydb.rawQuery("select * from test order by title limit 0,10 ", null); 
    while (cursor.moveToNext()) {
        StructNote test1 = new StructNote();
        test1.title = cursor.getString(cursor.getColumnIndex("title"));
        itemLists.add(test1);
    }
    cursor.close();
    mydb.close();
    adapter.notifyDataSetChanged();
}

public void searchdatabase() {
    Cursor cursor = null;
    itemLists.clear();
    cursor = mydb.rawQuery("SELECT * FROM test WHERE title LIKE '%" + SearchResult + "%'", null);
    while (cursor.moveToNext())
    {
        StructNote test1 = new StructNote();
        test1.title = cursor.getString(cursor.getColumnIndex("title"));
        itemLists.add(test1);
    }
    cursor.close();
    mydb.close();
    adapter.notifyDataSetChanged();
}}

the problam occured on searchdatabase(),but i don't know what's wrong
LogCat:

attempt to re-open an already-closed object

Any help will be appreciated
Thank You...

Aucun commentaire:

Enregistrer un commentaire