Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java AsynTask完成工作后返回函数值_Java_Android_Android Asynctask - Fatal编程技术网

Java AsynTask完成工作后返回函数值

Java AsynTask完成工作后返回函数值,java,android,android-asynctask,Java,Android,Android Asynctask,我有一个返回字符串的函数,其中有一个AsynTask。我的问题是,我的函数必须在AsynTask完成其工作后返回值 这是我的代码: public String getWeather(Context cont,int cityid,String latitude, String longitude){ this.latitude=latitude; this.longitude=longitude; new get_scores() { protected

我有一个返回字符串的函数,其中有一个AsynTask。我的问题是,我的函数必须在AsynTask完成其工作后返回值

这是我的代码:

public String getWeather(Context cont,int cityid,String latitude, String longitude){
    this.latitude=latitude;
    this.longitude=longitude;

    new get_scores() {
        protected void onPreExecute() {
            super.onPreExecute();

        }

        protected void onPostExecute(Boolean result) {

        }
    }.execute();

    return weatherdata;
}

我想返回天气数据,但在完成任务后。这可能需要几秒钟。

创建异步任务的原因不是在UI线程上运行。return语句是UI线程的一部分,因此return语句将始终返回null,因为它在后台线程启动时继续执行代码

你有两种可能:

1-您在UI踏板上运行代码,您的应用程序无法在此函数中工作,直到它到达return语句并返回变量的计算值。请不要那样做

这就是我要做的。不要从此函数返回任何内容,因此将其更改为return void,删除return语句,调用asynctask,然后从onPostExecute调用一个函数,该函数将操作在doInBackground上赋值的变量


我看不出您在后台做什么,但它是必须完成任务的地方,所以实现它并在那里给变量赋值,使其不再为null。

一个解决方案是
`onPostExecute()
返回
值。您可以通过将
AsyncTask
设置为正常,然后将
return
语句更改为

public String getWeather(Context cont,int cityid,String latitude, String longitude){
this.latitude=latitude;
this.longitude=longitude;

new get_scores() {
    protected void onPreExecute() {
        super.onPreExecute();

    }

    protected void onPostExecute(Boolean result) {

    }
}.execute();

  return new get_scores().execute();

}

这样做,您可能需要添加一个
进度条/对话框
,这样用户就不会认为应用程序卡住了。只要任务不超过2秒或3秒(最多),并且您不希望用户在任务完成之前能够执行任何其他操作,那么这就可以了。我会用
try/catch
进行一些错误检查,或者确保在应用程序无法返回的情况下返回一些内容weatherdata
的值来自哪里?@codeMagic:from doInBackground in asyntask然后执行该操作并在
onPostExecute()中返回它
@codeMagic:但我的主函数必须返回值,而不是onPostExecute()
doInBackground()
将值返回到
onPostExecute()
,因此您应该从我的想法中准确地获得值。。。在计算返回值之前执行return语句时,不能返回某些内容。