自定义Listview适配器与过滤器数据库Android

时间:2015-06-12 15:42:05

标签: android database listview filter

我正在尝试在列表视图上实现过滤器。我已将编辑文本放在我的列表中。我希望当我输入单词时,例如我按A显示所有起始A的名称。

//HERE IS MY DB HELPER CLASS 

public class FoodDbHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "pkfood_calories.DB";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_QUERY =
            "CREATE TABLE "+ Food.NewDishInfo.TABLE_NAME+"("
                    + Food.NewDishInfo.DISH_NAME+" TEXT NOT NULL,"
                    + Food.NewDishInfo.DISH_QUANTITY+" TEXT NOT NULL,"
                    + Food.NewDishInfo.DISH_CALORIE+" INTEGER,"
                    + Food.NewDishInfo.DISH_FAT+" TEXT NOT NULL,"
                    + Food.NewDishInfo.DISH_PROTEIN+" TEXT NOT NULL,"
                    + Food.NewDishInfo.DISH_SUGAR+" TEXT NOT NULL,"
                    + Food.NewDishInfo.DISH_VITAMINS+" TEXT NOT NULL);";
    public FoodDbHelper(Context context)
    {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
        Log.e("DATABASE OPERATION","Database created / opened...");
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_QUERY);
        Log.e("DATABASE OPERATION","Table created...");


    }
    public void addInformations(String name ,String quantity, Integer calorie, String fat ,
                                String protein,String sugar,String vitamins, SQLiteDatabase db){


        ContentValues contentValues = new ContentValues();
        contentValues.put(Food.NewDishInfo.DISH_NAME,name);
        contentValues.put(Food.NewDishInfo.DISH_QUANTITY,quantity);
        contentValues.put(Food.NewDishInfo.DISH_CALORIE,calorie);
        contentValues.put(Food.NewDishInfo.DISH_FAT,fat);
        contentValues.put(Food.NewDishInfo.DISH_PROTEIN,protein);
        contentValues.put(Food.NewDishInfo.DISH_SUGAR,sugar);
        contentValues.put(Food.NewDishInfo.DISH_VITAMINS,vitamins);
        db.insert(Food.NewDishInfo.TABLE_NAME, null, contentValues);
        Log.e("DATABASE OPERATION","one row inserted...");
    }
    public Cursor getInformations(SQLiteDatabase db){
        Cursor cursor;
        String[] projections = {Food.NewDishInfo.DISH_NAME,Food.NewDishInfo.DISH_QUANTITY,
                Food.NewDishInfo.DISH_CALORIE,Food.NewDishInfo.DISH_FAT,Food.NewDishInfo.DISH_PROTEIN,
                Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
        cursor= db.query(Food.NewDishInfo.TABLE_NAME,projections,null,null,null,null,null);
        return cursor;
    }

    public Cursor getFood(String dish_name,SQLiteDatabase sqLiteDatabase)
    {
        String[] projections = { Food.NewDishInfo.DISH_QUANTITY, Food.NewDishInfo.DISH_CALORIE, Food.NewDishInfo.DISH_FAT,
                Food.NewDishInfo.DISH_PROTEIN, Food.NewDishInfo.DISH_SUGAR, Food.NewDishInfo.DISH_VITAMINS};
        String selection = Food.NewDishInfo.DISH_NAME+" LIKE ?";
        String[] selection_args = {dish_name};
        Cursor cursor = sqLiteDatabase.query(Food.NewDishInfo.TABLE_NAME,projections,selection,selection_args,null,null,null);

        return cursor;

    }

这是我的数据列表活动

    listView = (ListView) findViewById(R.id.list_View);

        listDataAdapter = new ListDataAdapter(getApplicationContext(),
                R.layout.row_layout) {

            @Override
            protected void showCheckedButton(int position, boolean value) {
                // TODO Auto-generated method stub

                DataProvider item = (DataProvider) listDataAdapter
                        .getItem(position);
                Log.i("", "");

                item.setSelected(value);

                Button myButton = (Button) findViewById(R.id.findSelected);
                myButton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        StringBuffer responseText = new StringBuffer();
                        responseText
                               .append("The following dishes were selected...\n");

                        ArrayList<DataProvider> list = listDataAdapter
                                .getSelectedIndexes();

                        int sum = 0;
                        for (int i = 0; i < list.size(); i++) {
                            DataProvider dataProvider = list.get(i);

                            sum = sum + dataProvider.getCalorie();

                            responseText.append("\n" + dataProvider.getName()
                                    + " : " + dataProvider.getCalorie()
                                    + " kcal"
                                    );

                        }

                        Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
                                       +"\n"+"Total Calories In Your Menu Is : " +sum,
                                Toast.LENGTH_LONG).show();

                    }
                });


                    inputSearch.addTextChangedListener(new TextWatcher() {

                        @Override
                        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                            // When user changed the Text
                            DataListActivity.this.listDataAdapter.getFilter().filter(cs);
                        }

                        @Override
                        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                                      int arg3) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void afterTextChanged(Editable arg0) {
                            // TODO Auto-generated method stub
                        }
                    });


            }





        };
        listView.setAdapter(listDataAdapter);
        foodDbHelper = new FoodDbHelper(getApplicationContext());
        sqLiteDatabase = foodDbHelper.getReadableDatabase();
        cursor = foodDbHelper.getInformations(sqLiteDatabase);
        if (cursor.moveToFirst()) {
            do {
                String name, quantity, fat, protein, sugar, vitamins;
                boolean selected = false;
                String names = null;
                Integer calorie;

                name = cursor.getString(0);
                quantity = cursor.getString(1);
                calorie = Integer.valueOf(cursor.getString(2));
                fat = cursor.getString(3);
                protein = cursor.getString(4);
                sugar = cursor.getString(5);
                vitamins = cursor.getString(6);

                DataProvider dataProvider = new DataProvider(name, quantity,
                        calorie, fat, protein, sugar, vitamins, names, selected);

                listDataAdapter.add(dataProvider);

            } while (cursor.moveToNext());
        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                String name = (String) ((TextView) view
                        .findViewById(R.id.text_dish_name)).getText();
                String quantity = (String) ((TextView) view
                        .findViewById(R.id.text_dish_quantity)).getText();
                String calorie = (String) ((TextView) view
                        .findViewById(R.id.text_dish_calorie)).getText();
                String fat = (String) ((TextView) view
                        .findViewById(R.id.text_dish_fat)).getText();
                String protein = (String) ((TextView) view
                        .findViewById(R.id.text_dish_protein)).getText();
                String sugar = (String) ((TextView) view
                        .findViewById(R.id.text_dish_sugar)).getText();
                String vitamins = (String) ((TextView) view
                        .findViewById(R.id.text_dish_vitamins)).getText();

                String.valueOf(parent.getItemAtPosition(position));

                Toast.makeText(getApplicationContext(),
                        "dish name is : " + name, Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(getApplicationContext(),
                        Detail.class);
                intent.putExtra("Dish name", name);
                intent.putExtra("Dish quantity", quantity);
                intent.putExtra("Dish calorie", calorie);
                intent.putExtra("Dish fat", fat);
                intent.putExtra("Dish protein", protein);
                intent.putExtra("Dish sugar", sugar);

                intent.putExtra("Dish vitamins", vitamins);

                startActivity(intent);

            }

        });
    }

这是客户适配器代码

public abstract class ListDataAdapter extends ArrayAdapter {

    List list = new ArrayList();
    boolean index[];

    public ListDataAdapter(Context context, int resource) {

        super(context, resource);
        index = new boolean[list.size()];

    }

    static class LayoutHandler {
        TextView name, quantity, calorie, fat, protein, sugar, vitamins;
        CheckBox names;

    }

    @Override
    public void add(Object object) {

        super.add(object);
        list.add(object);
        index = new boolean[list.size()];

    }

    @Override
    public int getCount() {
        return list.size();

    }

    @Override
    public Object getItem(int position) {
        return list.get(position);

    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row = convertView;
        LayoutHandler layoutHandler;
        if (row == null) {
            LayoutInflater layoutInflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.row_layout, parent, false);
            layoutHandler = new LayoutHandler();
            layoutHandler.name = (TextView) row
                    .findViewById(R.id.text_dish_name);
            layoutHandler.quantity = (TextView) row
                    .findViewById(R.id.text_dish_quantity);
            layoutHandler.calorie = (TextView) row
                    .findViewById(R.id.text_dish_calorie);
            layoutHandler.fat = (TextView) row.findViewById(R.id.text_dish_fat);
            layoutHandler.protein = (TextView) row
                    .findViewById(R.id.text_dish_protein);
            layoutHandler.sugar = (TextView) row
                    .findViewById(R.id.text_dish_sugar);
            layoutHandler.vitamins = (TextView) row
                    .findViewById(R.id.text_dish_vitamins);
            layoutHandler.names = (CheckBox) row.findViewById(R.id.checkBox1);

            row.setTag(layoutHandler);

        } else {
            layoutHandler = (LayoutHandler) row.getTag();

        }
        DataProvider dataProvider = (DataProvider) this.getItem(position);
        layoutHandler.name.setText(dataProvider.getName());
        layoutHandler.quantity.setText(dataProvider.getQuantity());
        layoutHandler.calorie
                .setText(String.valueOf(dataProvider.getCalorie()));
        layoutHandler.fat.setText(dataProvider.getFat());
        layoutHandler.protein.setText(dataProvider.getProtein());
        layoutHandler.sugar.setText(dataProvider.getSugar());
        layoutHandler.vitamins.setText(dataProvider.getVitamins());

        //layoutHandler.names.setChecked(dataProvider.isSelected());
        layoutHandler.names.setTag(position);
        layoutHandler.names.setChecked(index[position]);
        layoutHandler.names
                .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                                                 boolean isChecked) {
                        // TODO Auto-generated method stub
                        int pos = (Integer) buttonView.getTag();
                        index[pos] = isChecked;
                        showCheckedButton(position, isChecked);

                    }
                });


        return row;
    }

    public ArrayList<DataProvider> getSelectedIndexes() {
        int size = list.size();
        ArrayList<DataProvider> selectedItems = new ArrayList<DataProvider>();
        for (int i = 0; i < size; i++) {
            DataProvider cItem = (DataProvider) list.get(i);
            if (index[i]) {
                selectedItems.add(cItem);
            }
        }

        return selectedItems;

    }

    protected abstract void showCheckedButton(int position, boolean value);

}

0 个答案:

没有答案