findViewById(R.id.searchView)导致java空指针异常

时间:2016-06-14 22:03:38

标签: java android

我的问题非常简短。我有一个带有搜索按钮和列表视图的xml布局,以及一个活动。

XLM:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <SearchView android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <ListView android:id="@+id/locationList"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
    </ListView>

</LinearLayout>

活动

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {

    private SearchView searchView;
    private ListView locationListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        searchView = (SearchView) findViewById(R.id.searchView);
        locationListView = (ListView) findViewById( R.id.locationList );
    }

searchView = (SearchView) findViewById(R.id.searchView);只是给出了空指针异常。我检查将其更改为EditText,它可以正常工作。有人知道它为什么不起作用吗?

由于

1 个答案:

答案 0 :(得分:0)

与评论过您问题的所有人一样,您尝试查找搜索结果的行无法为您提供NullPointerException,因为您没有使用null的搜索结果。 findViewById()返回一个视图,如果它存在于setContentView()中提供的布局中,即activity_main,否则返回null。我建议你做两件事:

  • 检查包含searchview的布局是否名为“activity_main”
  • 将调试点放在您找到搜索视图的下一行上 然后运行调试工具,启动您的活动,检查您是否有空的搜索视图。如果是,它可能与您的布局名称有关。如果没有,请在您的其他地方搜索 您获得空指针异常的代码。
相关问题