首页 > 解决方案 > 使用 Spinner 过滤 ListView

问题描述

我正在尝试为 ListView 创建一个过滤器Employees

我正在收集其中的spinner值,MainActivity因为它使用显示Toast

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            //first,  we have to retrieve the item position as a string
            // then, we can change string value into integer
            String item_position = String.valueOf(position);
            positonInt = Integer.valueOf(item_position);
            Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }

    });

稍后在MainActivity我通过调用方法设置适配器getEmployeeList

    List<Employee> employeeList = dataBaseHelper.getEmployeeList(positonInt);
    adaptor = new EmployeeAdaptor(MainActivity.this, employeeList);
    empListView.setAdapter(adaptor);

我试图通过调用下面的方法来实现这一点,具体取决于将Spinner位置值传递给方法getEmployeeList(),然后在 switch 语句中使用该方法来创建查询以填充ListView

public List<Employee> getEmployeeList(int spinnerPostion) {


    switch (spinnerPostion) {
        case 1:  spinnerPostion = 0;
            query = "SELECT * FROM " + EMP_TABLE
                    + " ORDER BY " + PROFIT + " DESC ";
            break;
    }

    List<Employee> employeesList = new ArrayList<>();

    //Referencing the active database to read infromation
    SQLiteDatabase db = this.getReadableDatabase();

    //Executing the query
    //  -Using a Cursor so we can iterate through all readable data in the db
    Cursor cursor = db.rawQuery(query, null);

    if (cursor.moveToFirst()) {
        //If there are results loop through and create a new Item
        //for every item in the db
        do {
            int employeeID = cursor.getInt(0);
            String employeeName = cursor.getString(1);
            String employeeSecondName = cursor.getString(2);
            int profit = cursor.getInt(3);
            Employee menu_emp = new Employee(employeeID, employeeName, employeeSecondName, profit);
            employeesList.add(menu_emp);

        } while (cursor.moveToNext());
    } else {
        // Empty List contains no Items
    }

    //Closing connection to the database and cursor
    cursor.close();
    db.close();

    return employeesList;
}  

该方法getEmployeeList()在没有 switch 语句的情况下工作,并在我刚刚设置时填充列表,String query但是当我尝试使用 switch 语句执行此操作时出现错误。

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dropit/com.example.dropit.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference

标签: javaandroidsqliteandroid-studio

解决方案


你确定你从中得到的价值Spinner1

或者你,如果它0改变它

case 0:
{
    spinnerPostion = 0;
        query = "SELECT * FROM " + EMP_TABLE
                + " ORDER BY " + PROFIT + " DESC ";
        break;
}

推荐阅读