【问题标题】:findViewById(R.id.searchView) causing java null pointer exceptionfindViewById(R.id.searchView) 导致 java 空指针异常
【发布时间】:2017-08-25 04:52:18
【问题描述】:

我有一个非常简短的问题。我有一个带有搜索按钮和列表视图的 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,它可以工作。有人知道为什么它不起作用吗?

谢谢

【问题讨论】:

  • 在你找到SearchView 的这一行不能给你NullPointerException,因为你没有在那里使用指针。它可能会给你一个空的searchView,但不是例外。请仔细查看堆栈跟踪。
  • 能否在活动中显示SearchView 导入?它可以从支持库中导入。如果是这种情况,您的XML 也应该如此。另外,发布堆栈跟踪。
  • 报错基本是android.widget.SearchView cannot be cast to android.support.v7.widget.SearchView,所以我只是将import android.v7.widget.SearchView;改为import android.widget.SearchView;。但感谢您的支持。

标签: java android


【解决方案1】:

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

  • 检查包含搜索视图的布局是否命名为“activity_main”
  • 在查找搜索视图的下一行放置一个调试点
    然后运行你的调试工具,开始你的活动,检查你是否有一个空的搜索视图。如果是,则可能与您的布局名称有关。如果没有,请在您的其他地方搜索
    出现空指针异常的代码。

【讨论】:

  • 报错基本是android.widget.SearchView cannot be cast to android.support.v7.widget.SearchView,所以我只是将import android.v7.widget.SearchView;改为import android.widget.SearchView;。但感谢您的支持。
猜你喜欢
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多