java - 使用 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
解决方案
你确定你从中得到的价值Spinner
是1
或者你,如果它0
改变它
case 0:
{
spinnerPostion = 0;
query = "SELECT * FROM " + EMP_TABLE
+ " ORDER BY " + PROFIT + " DESC ";
break;
}
推荐阅读
- python - Airflow 1.9.0 无法对任务进行排队
- regex - 如何替换所有电子邮件的域名
- c++ - 迷失在指针的世界中
- mysql - 尝试优化执行时间较长的查询
- java - 在java中使用反射面临的问题
- vba - 显示上次用户在 vba 中打开共享工作簿的时间
- amazon-web-services - 如何处理 SQS + Lambda 中的消费者执行错误?
- dart - Flutter 调用 showTimePicker 函数导致错误:在 null 上调用了 getter 'modalBarrierDismissLabel'
- linux - 如何在unix中分配命令的输出
- ssl - Certify The Web - CheckDNS 错误解析 DnsSecRecursiveDdnsResolver?