簡體   English   中英

從onResponse傳遞值到onPostExecute的值繼續變為null

[英]Passing value from onResponse to onPostExecute keep turning to null

我正在使用異步任務連接到API。 我需要將兩個值從API傳遞到應用程序,在onResponse中,我已經記錄了值並正確設置了它們。 但是在onPostExecute中,其中之一不斷變為null

我已經嘗試檢查來自API的不同值並記錄日志,以查看我要查找的值是否存在,或者連接是否有效,一切正常,直到到達onPostExecute為止,在這里我僅獲得一個值

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

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


    private TextView location;
    private 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 onProgressUpdate(Void...values){
        super.onProgressUpdate(values);
    }
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
    }
    @Override

    protected Void doInBackground(String... urls) {
        request = new Request.Builder().url(urls[0]).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d("CallMsg", String.valueOf(call));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("Response", String.valueOf(response));
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    JSONObject weather = jsonObject.getJSONObject("weather");
                    JSONObject location = weather.getJSONObject("location");
                    state = location.getString("state");

                    JSONObject percentage = jsonObject.getJSONObject("probability");
                    JSONObject calculated = percentage.getJSONObject("highest");
                    probability = calculated.getInt("value");
                    probablityString = probability.toString();
                    Log.d("percentage", probability.toString());
                    Log.d("String",probablityString);
                    Log.d("location",state);

                } catch (JSONException e){
                    e.printStackTrace();
                }
            }
        });

        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);
    }

}

基本上,我所需要的只是關於如何獲取此值的建議,我覺得在將其轉換為字符串時可能會出錯,但是在日志中,在onResponse中它顯示的還不錯,所以我不知道。 謝謝你的建議

改造有兩種執行請求的技術,一種是同步( 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM