【问题标题】:Updating ListView from BroadcastReceiver - adapter nullpointerexception从 BroadcastReceiver 更新 ListView - 适配器 nullpointerexception
【发布时间】:2013-09-07 14:53:18
【问题描述】:

我有一个BroadcastReceiver,它会在设定的时间创建一个通知。创建通知后,我想更新我的ListView,它包含在名为PendingFragmentFragment 中。我意识到我只能在应用程序运行时才能做到这一点 - 这很好。

所以,在我的BroadcastReceiver 我这样做:

PendingFragment.getInstance().updateTheList();

然后在PendingFragment中有getInstance()方法和updateTheList()方法。

private static PendingFragment instance;

    public static PendingFragment getInstance() {
        if (null == instance) {

            instance = new PendingFragment();
        }
        return instance;
    } 

public void updateTheList() {

        simpleAdpt.refreshMyAdapter();
}

refreshMyAdapter() 是自定义适配器的子类。它所做的只是删除一些项目,然后调用simpleAdpt.notifyDataSetChanged();

我的问题是我在updateTheList() 中有一个nullpointerexception,这可能意味着 simpleAdpt 为空。我不知道为什么,因为我可以在屏幕上查看包含项目的 ListView - 那么它怎么可能为空?

【问题讨论】:

  • 建议不要在receiver中做长期任务,因为receiver大多存活10秒左右,所以你应该通过服务来执行任务。
  • 我只创建一个通知并在我的Fragment 中调用 updateTheList() 方法。该方法正在被调用,所以我知道问题不在于接收者已经“死亡”。
  • 那么,把片段代码也贴出来,也许有人能找到错误! :)
  • PendingFragment 是包含列表的片段吗?如果是,我不明白您为什么期望 instance 拥有有效的数据成员。
  • @Luksprog 是 - PendingFragment 包含列表。你能解释一下第二句吗:-)

标签: android listview android-listview broadcastreceiver android-broadcast


【解决方案1】:

正如Luksprog 在 cmets 中指出的那样,我的fragment 中的instance 没有理由拥有“有效数据成员”。

要解决这个问题,在FragmentonCreateView() 中,只需输入instance = this;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2020-06-25
    • 1970-01-01
    相关资源
    最近更新 更多