2017-01-23 215 views
-2

有人可以請解釋爲什麼變量picture的值僅存在於OnInBackground()變量值無法從DoInBackground()中獲取

當我在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()

+0

您不必在'doInBackground'中返回值,因爲它已經在內部類的全局變量中。把這個'AsyncTask '改成這個'AsyncTask ' – MohammedAlSafwan

+0

@MohammedAlSafwanplease瞭解一些java的基礎知識......它不是全局變量,而是字段 – Selvin

+0

它是多線程...請求。 executeAsync(); http://ideone.com/PPHi95 – Selvin

回答

0

中檢索到的值如何從doInBackground呼叫request.executeAsync。因此,doInBackground將立即返回並且onPostExecute可能會在調用onCompleted回調之前被調用。

+0

Ahhhh你是對的!我改變它在executeAndWait()和工作正常,謝謝 – Lorenzo