我正在制作一个android应用程序,在其中我添加了一个菜单文件,在其中添加了一项以执行搜索。然后在MainActivity上,我添加了一个searchView变量,我正试图在onCreatOptionsmenu()
方法中对其进行扩展。当我尝试运行应用程序时,我得到了这个错误,"java.lang.NullPointerException:尝试在null对象引用上调用虚拟方法'void android.widget.SearchView.setSearchableInfo(android.app.SearchableInfo('">
这是我的菜单main.xml 的代码
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:title="@string/search"
android:orderInCategory="1"
app:showAsAction ="ifRoom"
android:id="@+id/action_search"
/>
</menu>
searchview 的主要活动代码
public class MainActivity extends AppCompatActivity {
private SearchView searchView;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
mCorona_Stats_Adapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
mCorona_Stats_Adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int menuItemThatWasSelected = item.getItemId();
if(menuItemThatWasSelected == R.id.action_search){
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}
}
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.passengerearth.coronago"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
AndroidX使用androidx命名空间。
您正在使用androidx
。所以添加androidx支持。
<item
android:id="@+id/action_search"
.....................
app:actionViewClass="androidx.appcompat.widget.SearchView" />
以及下面MainActivity部分的导入。
import androidx.appcompat.widget.SearchView;