【问题标题】:Android - check if instance of async task is running and cancel it before executing a new oneAndroid - 检查异步任务实例是否正在运行并在执行新任务之前将其取消
【发布时间】:2014-12-15 19:55:52
【问题描述】:

我有一个非常大数量的位图的网格视图。为了防止内存不足错误,我只加载了一些位图并使用 onScrollListener 我回收了非必要的位图并创建了需要显示的位图。加载位图过程在异步任务中完成。这是每次滚动停止时调用的更新方法

AsyncCaller asyncCaller;

public void updateImageList(int first, int last){
        if(!asyncCaller.isCancelled()){asyncCaller.cancel(true);}
        asyncCaller=null;
        asyncCaller=new AsyncCaller();
        asyncInput input=new asyncInput();
        input.first=first;
        input.last=last;
        input.id=Integer.toString(asyncId);
        asyncId++;
        asyncCaller.execute(input);
}

其中 asyncCaller 是一个类变量。

此代码在 asyncCaller.execute(input); 处导致 NullPointerException;线。有人能告诉我为什么我在调用执行之前向 asyncCaller 分配了一个新实例吗?

我使用 asyncCaller 作为类变量,以便在当前运行的 AsyncTask 完成之前进行新滚动时能够取消它。没有理由让它继续运行,因为不再需要这些位图。

如果我在 updateImageList 方法中使用 asyncCaller 作为局部变量,则无法取消当前正在运行的实例...对吗?

编辑:这个问题毫无意义,因为这个问题是我的一个简单错误。我将问题与我的代码一起更正并为任何寻找类似内容的人提供参考

【问题讨论】:

  • 但是您将 asyncCaller 设置为 null
  • 你给它赋了空值o.O

标签: android android-asynctask cancellation


【解决方案1】:

替换这一行

asyncCaller.execute(input);

new AsyncCaller().execute(input);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    相关资源
    最近更新 更多