从onResponse传递值到onPostExecute的值继续变为null

时间:2019-05-26 19:25:20

标签: java android

我正在通过异步任务连接到API。我需要将两个值从API传递到应用程序,在onResponse中,我已经记录了值并正确设置了它们。但是在onPostExecute中,其中之一不断变为空

我已经尝试检查来自API的不同值并记录日志,以查看我要查找的值是否存在或者连接是否有效,一切正常,直到遇到onPostExecute,我只得到一个值

<div v-show="isLoading">Loading...</div>
<v-baller-chart v-if="isDataLoaded" :data="chartData"></v-baller-chart>
<button v-show="isDataFailed" type="button" @click="handleGetChart">TRY AGAIN</button>

基本上,我所需要的只是关于如何获得此值的建议,我觉得在将其转换为字符串时可能会犯错,但是在日志中,在onResponse中它显示的还不错,所以我不知道。谢谢您的所有建议

1 个答案:

答案 0 :(得分:0)

改造具有执行请求的两种技术,一种是同步(execute()),另一种是异步(enqueue())。您正在使用异步技术,因此,当您执行AsyncTask时,您的doInBackground()方法会立即调用enqueue(),完成并在您执行之前调用onPostExecute()请求已完成。

您有两个选择。首先,您可以保留当前的AsyncTask,但将enqueue()替换为execute()。这看起来像:

public class ChooseLocationTask extends AsyncTask<String, Void, Void> {

    private final OkHttpClient client = new OkHttpClient.Builder()
            //default timeout for not annotated requests
            .readTimeout(15000, TimeUnit.MILLISECONDS)
            .connectTimeout(15000, TimeUnit.MILLISECONDS)
            .writeTimeout(15000, TimeUnit.MILLISECONDS)
            .build();
    private final Request request;


    private final TextView location;
    private final TextView value;
    String state;
    Number probability;
    String probablityString;

    public ChooseLocationTask(TextView location, int selected, TextView value){
        this.location = location;
        this.value = value;
    }

    @Override
    protected Void doInBackground(String... urls) {
        request = new Request.Builder().url(urls[0]).build();

        try {
            final Response<?> response = client.newCall(request).execute();
            if(response.isSuccessful()) {
                final JSONObject jsonObject = new JsonObject(response.body().string());
                //etc...
            }
        } catch (IOException e) {
           //...
        }

        //I'd recommend you return values as well, rather than assigning them to
        //instance variables
        return null;
    }

    @Override
    protected void onPostExecute(Void voids){
        if(isCancelled()){
            voids= null;
        } else {
            location.setText(state);
            value.setText("your chance to see Northern lights today is" + probablityString);
            Log.d("value", "onPostExecute: " + probablityString);
        }
        Log.d("post", "onPostExecute: " + probability);
    }

或者,您可以完全摆脱AsyncTask,只需致电enqueue()