仅在搜索之后,适配器才显示数据

时间:2014-12-30 12:27:43

标签: android sql eclipse android-listview

感谢您提前的时间。我是android的新手,我想了解更多。我有一个代码,只有在点击搜索后才显示来自sql的数据,而且我不知道怎样才能让它显示来自sql的所有数据,让我们首先说明alfabetical命令,如果搜索的话用于显示与搜索请求匹配的数据。

public class EmployeeList extends ListActivity {

    protected EditText searchText;
    protected SQLiteDatabase db;
    protected Cursor cursor;
    protected ListAdapter adapter;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        searchText = (EditText) findViewById(R.id.searchText);
        db = (new DatabaseHelper(this)).getWritableDatabase();

    }


    public void onListItemClick(ListView parent, View view, int position, long id) {
        Intent intent = new Intent(this, EmployeeDetails.class);
        Cursor cursor = (Cursor) adapter.getItem(position);
        intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
        startActivity(intent);
    }

    public void search(View view) {
        // || is the concatenation operation in SQLite
        cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?", 
                        new String[]{"%" + searchText.getText().toString() + "%"});
        adapter = new SimpleCursorAdapter(
                this, 
                R.layout.employee_list_item, 
                cursor, 
                new String[] {"firstName", "lastName", "title"}, 
                new int[] {R.id.firstName, R.id.lastName, R.id.title});
        setListAdapter(adapter);
    }
}

感谢。

1 个答案:

答案 0 :(得分:0)

我看到你在XML布局中使用onClick,对吧? 任何方式,没问题。

添加新方法populateList(),如下所示

public void populateList(boolean useWhere) {
    // || is the concatenation operation in SQLite
    if(useWhere){
        cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?", new String[]{"%" + searchText.getText().toString() + "%"});
    }else{
        cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employee");
    }
    adapter = new SimpleCursorAdapter(
            this, 
            R.layout.employee_list_item, 
            cursor, 
            new String[] {"firstName", "lastName", "title"}, 
            new int[] {R.id.firstName, R.id.lastName, R.id.title});
    setListAdapter(adapter);
}

更改search()如下:

public void search(View view){
    populateList(true);
}

向活动的populateList(false);添加致电onCreate()

所以oncreate activity,会在没有WHERE的情况下调用搜索到execuste,当点击按钮时,它会执行WHERE sql

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        searchText = (EditText) findViewById(R.id.searchText);
        db = (new DatabaseHelper(this)).getWritableDatabase();
        populateList(false);
}