从非活动类中的异步任务获取结果 [英] get result from async task in not activity class

查看:55
本文介绍了从非活动类中的异步任务获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用异步任务从数据库中获取数据.我有:

I use async task to get data from my database. i have :

public class BackgroundDatabaseTask extends AsyncTask<String, Void, String> {
    String jsonData;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... values) {
        String jsonData = Driver.returnJsonDataFromDatabase(values[0]);
        return jsonData;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        jsonData = result;
    }
}

在其他课程中,我将其用作:

And in other class i use it like:

private static String returnJsonDataBackgroundTaskExecute(String fromWhichTableGetData) {

    try {
        return new BackgroundDatabaseTask().execute(fromWhichTableGetData).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    return "Error in BackgroundDatabaseTask";
}

但是 get()阻塞了我的主线程.那么,如何在其他非活动类中获得异步任务的结果?我想在非活动类中运行它,所以我的类没有onCreate方法,但是我的MainActivity类具有活动.

But get() block my main thread. So, how can I get result of my async task in other non activity class? I want run this in not activity class, so my class don't have onCreate method, but I have activity from my MainActivity class.

更新:现在我使用线程解决了这个问题,但这是一个很好的解决方案?

UPDATE: Now i solve this problem using thread but it is a good solution?

Runnable runnable = new Runnable() {
        @Override
        public void run() {
            listOfDataFromDatabase = GetterDataFromDatabase.returnJsonDataBackgroundTaskExecute(tableNameFromWhichIGetData);
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

现在我可以使用其他方法访问此可变的 listOfDataFromDatabase .

now i have acces to this varaible listOfDataFromDatabase in other method .

推荐答案

您可以在Asynctask类中定义一个接口,然后在所需的任何地方实现它,并从该接口回调中获取结果

You can define an interface in your Asynctask class then implement it where ever you want and get the result from that interface callback

MyTask extends AsynTask{
public interface DataListener{
void onDataReceived(String result);
}
/// then on your onPostExecute method , get an instance of the interface then push the result to the interface method 
dataListener.onDataReceived(result);
}

也许这会有所帮助

这篇关于从非活动类中的异步任务获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆