使用Searchview在SqLite数据库中搜索

时间:2019-01-08 17:44:34

标签: android sqlite searchview simplecursoradapter

我正在将数据插入SqLite数据库的两个片段中,第一个用于食物,第二个用于饮料。 My screen。在每个窗口中搜索都可以正常工作,但是当我交换片段或在搜索栏中键入某些内容然后将其删除时,将显示所有数据。 Problem我想用一个片段来搜索食物,一个片段来寻找饮料。我不确定问题出在查询还是搜索视图方法中。

这是我在CreateOptionMenu上的方法

  @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_search, menu);
    MenuItem item = menu.findItem(R.id.menuSeach);
    SearchView searchView = (SearchView) item.getActionView();


    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            Log.d(TAG, "onQueryTextSubmit ");
            cursor = productData.getProductListByFood(query);
            if (cursor == null) {
                Toast.makeText(getContext(), "No records found!", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getContext(), cursor.getCount() + " records found!", Toast.LENGTH_LONG).show();
            }
           todoAdapter.swapCursor(cursor);

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            Log.d(TAG, "onQueryTextChange ");
            cursor = productData.getProductListByFood(newText);
            if (cursor != null) {
               todoAdapter.swapCursor(cursor);
            }
            return false;
        }

    });
}

我用于搜索的查询是

 public Cursor getProductListByFood(String search) {
    SQLiteDatabase db = productData.getReadableDatabase();

    String typeQuery = "select * from " + PRODUCT_TABLE + " WHERE " + COL_PRODUCT_TYPE + "  LIKE '%Food%' " + " AND " + COL_PRODUCT_NAME + "  LIKE  '%" + search + "%' " + " OR " + COL_PRODUCT_PRICE + " LIKE '%" + search + "%' ";
    Cursor cursor = db.rawQuery(typeQuery, null);


    if (cursor == null) {
        return null;
    } else if (!cursor.moveToFirst()) {
        cursor.close();
        return null;
    }
    return cursor;
}

饮料,食物碎片和查询的代码相似。如果有问题,这里也是我的适配器

public Adapter(Context context, Cursor c, int flags) {
    super(context, c, flags);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.adapter_layout,parent,false);
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
   TextView tvProduct = (TextView) view.findViewById(R.id.txtview);


        String name = cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
        String price = cursor.getString(cursor.getColumnIndexOrThrow("PRICE"));
        tvProduct.setText(String.format("%s - %s",name,price));



}

0 个答案:

没有答案