【问题标题】:Access ListView from another Class for a Search Function - NullPointerException从另一个类访问 ListView 以获取搜索功能 - NullPointerException
【发布时间】:2014-09-08 10:11:01
【问题描述】:

我想在我的应用中实现一个简单的搜索功能。 我已经实现了所有与布局相关的东西,它可以正常工作。 现在,我想使用搜索功能从ListView 中查找项目。

问题是,我的ListView 不在同一个班级。当我尝试从其他班级访问我的ListView 时,我一直得到NullPointerException

这是我的 MainActivity 中的内容:

    public boolean onQueryTextChange(String newText) {

    // this is your adapter that will be filtered
    if (TextUtils.isEmpty(newText))
    {

      //  new otherActivity().listView.clearTextFilter(); NullPointerException



    }
    else
    {
    //   new otherActivity().listView.setFilterText(newText.toString()); NullPointerException

    }

    return true;
}

在我的 otherActivity 中,我确实在onCreate() 方法之外有ListView listView;,在onCreate() 方法内部有listView = (ListView) findViewById(R.id.listView);

我还尝试将整个 ListView 放在 onCreate() 方法之外,但最终也变成了 NullPointerException

【问题讨论】:

  • 您应该通过在捆绑包中发送带有意图的参数来指定要采取的操作,您不能从另一个活动中引用您的 listView。只需启动 otherActivity 并传递您的过滤器文本
  • 您应该将数据保存在 ListView 中显示的数据库或独立类中,然后对该数据执行过滤,而不是尝试访问 ListView。

标签: java android listview android-listview nullpointerexception


【解决方案1】:

您可以通过一些可能的方式在有其引用的类中使用ListView

1.) Pass reference of ListView in other class constructor
2.) create a static getter method of ListView in your Activity having ListView
3.) Use Application class to setter and getter of ListView instance
4.) Another way is have an instance of Activity with as static getter method and
    use that to get instance of your ListView in another Class.

上述这些可能的方式可能会根据您的要求而有所不同

【讨论】:

    【解决方案2】:
     new otherActivity()
    

    您不应该以这种方式创建活动。

    使用 Intent 来启动您的 Activity。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-21
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多