我尝试处理ListView和SimpleCursorAdapter并遇到以下问题:我有ListView with SimpleCursorAdapter和SearchView。我尝试根据SearchView中的文本过滤ListView中的数据(数据库中的数据)。但是当我在模拟器上启动应用程序时,应用程序崩溃并出现NullPointerException。错误可能是什么?我做的一切都好吗?
public class ListViewFragmentActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
private static final int CM_DELETE_ID = 1;
public ListView listViewData;
public Button mAddButton, mViewButtonProject, mViewButtonStaff;
public Bundle mBundle;
private DatabaseHelper db;
private SimpleCursorAdapter scAdapter;
private android.support.v7.widget.SearchView sv;
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
drawNavigationDrawer();
returnBundle(savedInstanceState);
final Context context = this;
db = new ProjectDatabase(this);
db.open();
String[] from = new String[] { db.COLUMN_NAME, db.COLUMN_DESCRIPTION };
int[] to = new int[] { R.id.textViewName, R.id.textViewDescription };
scAdapter = new SimpleCursorAdapter(this, R.layout.list_view_item, null, from, to, 0);
listViewData = (ListView) findViewById(R.id.listViewData);
listViewData.setAdapter(scAdapter);
sv = (android.support.v7.widget.SearchView) findViewById(R.id.action_search);
sv.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
listViewData = (ListView) findViewById(R.id.listViewData);
SimpleCursorAdapter filterAdapter = (SimpleCursorAdapter)listViewData.getAdapter();
filterAdapter.getFilter().filter(newText);
return false;
}
});
registerForContextMenu(listViewData);
getSupportLoaderManager().initLoader(0, null, this);
}
这就是我在代码中执行的任务。我还没有做过什么?
NullPointerException错误引用此行:sv.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {...}
我将非常感谢任何帮助。
upd:我试试这个:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.search);
SearchView sv = (SearchView) MenuItemCompat.getActionView(searchItem);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(final String newText) {
scAdapter.setFilterQueryProvider(new FilterQueryProvider() {
@Override
public Cursor runQuery(CharSequence constraint) {
Cursor cursor = dbConnector.getFilteredData(constraint.toString());
return cursor;
}
});
return false;
}
});
return true;
}
在DB类中:
public Cursor getFilteredContacts(String filter) {
return database.query(...);
}