android使用从async返回的类对象

时间:2015-12-03 22:40:08

标签: java android asynchronous

private class QueryResult {
    List<String> name = new ArrayList<>();
    List<String> location = new ArrayList<>();
    List<String> type = new ArrayList<>();
    List<Calendar> end = new ArrayList<>();
    List<Calendar> start = new ArrayList<>();
    public QueryResult( List<String> name,List<String> location,List<String> type, List<Calendar> end, List<Calendar> start ) {
        this.name=name;
        this.location=location;
        this.type=type;
        this.end=end;
        this.start=start;
    }

我想返回5个arraylists,所以我返回

return new QueryResult(namee,locationn,typee,end,strt);

此queryresult类在异步类中是私有的。

我在mainactivity中将此async称为oncreate。但我不能使用那个arraylists。因为它是私人类,我只能这样做

 Object obj= new RetrieveFeedTask().execute().get();

但我不能对那个obj做任何事情。我应该让类公开使用该数组吗?什么是解决方案?或者我应该返回多种不同类型的数组 用不同的方法?我找不到。我无法检索那些数组

我在doinbackground中返回那些数组,但我不认为现在哪种异步方法很重要。

Retrieve Object value from AsyncTask

这不起作用,因为它在写mainactivity或main时会出错。

我上了公共课,但我得到了吸气但仍然无法工作

1 个答案:

答案 0 :(得分:0)

首先,永远不要调用AsyncTask.execute.get。这样做会消除使用AsyncTask的全部原因和优势,并且99.9%的时间都是错误的。它会冻结您的手机,使其无响应。

其次,永远不要在onCreate中使用它。 onCreate有一个看门狗计时器,你可以绊倒计时器,你的应用程序将被终止。

使用AsyncTask的正确方法是将所有需要任务结果的代码放在onPostExecute函数(或从那里调用的函数)中。调用execute之后不要把它放进去,也不要调用get来获取结果。然后只调用AsyncTask.execute()。

这有一两个例外情况,但如果您不太了解自己回答这个问题,那么您就不能正确地确定这些例外 - 所以只需要#&# 39;不要这样做。