变量值不会从DoInBackground()

时间:2017-01-23 20:08:29

标签: java android android-asynctask

有人可以解释一下为什么变量picture的值仅存在于OnInBackground()中?

当我在OnPostExecute中访问它时,该值将丢失。

public class GetPostAsync extends AsyncTask<Void, Integer, String>
{

    String picture="";

    public GetPostAsync(Context context){
        c=context;
    }

    protected void onPreExecute (){
    }

    protected String doInBackground(Void...arg0) {
        try {
            GraphRequest request = GraphRequest.newGraphPathRequest(
                    AccessToken.getCurrentAccessToken(),
                    "/myquery",
                    new GraphRequest.Callback() {
                        @Override
                        public void onCompleted(GraphResponse response) {
                            try {
                                JSONObject jobj = response.getJSONObject();
                                picture = jobj.getString("picture");

                                Log.i("TEST","pic: "+picture);  //return the right value
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            request.executeAsync();
        }
        catch(Exception e) {
        }
        return picture;
    }

    protected void onProgressUpdate(Integer...a){
    }

    protected void onPostExecute(String result) {
        Log.i("TEST","pic: "+picture);  //return empty 
    }
}

我已在活动顶部声明picture。我不知道如何保留我在Onbackground()

中检索的值

1 个答案:

答案 0 :(得分:0)

您正在request.executeAsync致电doInBackground。因此,doInBackground会立即返回,并且在调用onPostExecute回调之前可能会调用onCompleted