[英]Running the code after an asynchronous task
因此,我正在尋找一種方法,在異步任務完成后僅運行一段代碼即可運行。 該代碼與Request.executeAsync();
在Android的facebooksdk中。 我將用於解釋的代碼是:
public class Home extends Activity {
TextView welcomeTextView;
private JSONObject userProfile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userProfileFetched = false;
welcomeTextView = (TextView)findViewById(R.id.welcome);
populateUserProfile();
Log.d("USER_PROFILE", userProfile.toString()); //NullPointerException occurs here
}
private void populateUserProfile() {
Request.newMeRequest(Session.getActiveSession(), new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
userProfile = response.getGraphObject().getInnerJSONObject();
}
}).executeAsync();
}
}
上面帶有注釋的行指出了我的應用程序意外關閉的行。 當我第一次開始該活動時,將使用一些內部管理方法調用onCreate
方法。 然后,調用函數populateUserProfile()
異步執行me
請求。 如果將response.getGraphObject().getInnerJSONObject().toString()
在onCompleted()
函數中,則可以清楚地看到我正在尋找的理想結果,即登錄用戶的JSONObject,但就像在上面的代碼,如果我將該函數的返回值分配給userProfile
變量,然后在onCreate()
方法中調用該函數后將其記錄下來,則我的應用程序意外停止,並且在Log
行中拋出了NullPointerException。
我知道這是因為me
在登錄userProfile
JSONObject時me
請求尚未完成,這就是為什么它尚未分配給任何東西的原因,所以我需要知道我該如何等待populateUserProfile()
函數中的onCompleted
方法這樣才能將userProfile
對象成功分配給已登錄用戶的信息?
換句話說,我如何等待me
請求的異步任務完成,然后將userProfile
登錄到LogCat?
希望我很清楚,期待有一個解釋性的答案。
想到的解決方案是使用AsyncTask < T, T, T>
,然后在onPostExecute
方法中調用您的函數。
編輯:這是developers
一個示例,不要看它做了什么,只要了解一下概念即可。 在doInBackground
方法中,所有耗時的工作都已完成,完成后它會調用onPostExecute
,因此您可以放心地假設其中所有的Internet工作都已完成並且可以繼續。
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
// here you call the function, the task is ended.
}}
populateUserProfile(){
new AsyncTask<Void, Void, JSONObject>() {
@Override
protected JSONObject doInBackground(Void params) {
return response.getGraphObject().getInnerJSONObject();
}
@Override
protected void onPostExecute(JSONObject result) {
Log.d("USER_PROFILE", result.toString());
}
}.execute();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.