[英]How to move data from background thread to ui thread
我是編程初學者,了解不多。 我使用谷歌方向 api 來獲取兩個標記之間的距離。 顯然,它在后台線程上執行此操作。 我可以使用 runnable 在我的 ui 上顯示接收到的距離,但我無法將距離保存在全局變量中以用於其他計算。
這是我的代碼的樣子:
public class MyClass {
private List<Distance> distances = new ArrayList<>();
private void calculateDistance (LatLng origin, LatLng destination) {
DirectionsApiRequest directions = new DirectionsApiRequest(mGeoApiContext);
directions.origin(origin);
directions.destination(destination).setCallback(new PendingResult.Callback<DirectionsResult>() {
@Override
public void onResult(DirectionsResult result) {
Distance distance = result.routes[0].legs[0].distance;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//adding the distance result from this method to the distances arraylist above
distances.add(distance);
}
});
}
}
}
}
不幸的是,我的距離數組列表在此方法之外仍然為空。 在我嘗試將距離結果添加到數組列表的同一空間內,我能夠在視圖或 Toast 上顯示結果。 此外,當我將結果添加到我的數組列表時,如果我在此方法中檢查數組列表的大小,它會顯示結果已添加。 但是如果我在這個方法之外訪問我的數組列表,它是空的。 但我需要能夠收集距離列表(注意,此方法是從 for 循環調用的)並將每個收集的距離添加到我的距離數組列表中,並在該方法之外執行計算以獲得總距離。 請幫我想辦法。 並且請讓您的解釋盡可能簡單或技術性較低,因為我是該領域的初學者。
如果您正在使用 android,您可以查看 Android Annotations。 您可以通過簡單地聲明@Background 來創建后台方法,然后使用@UiThread 注釋在主線程上添加內容。
https://developer.android.com/studio/write/annotations
這是一個非常強大的學習工具。 您只需要幾個依賴項
所以事實證明這真的不是問題。 正在保存這些值。 在調用calculateDirections 方法后,我只是過早地檢查我的arraylist 的大小
所以就在 calculateDistance(); 之后我運行一個祝酒詞來檢查arraylist 的大小。 它的 0
嗯是的。
calculateDistance
不計算距離。 它向服務器發送一個請求,詢問距離,並記下當答案回來時要做什么。 如果發送請求,那么打印ArrayList的大小,當然是0,因為答案還沒回來。
當答案回來時, onResult
方法就會運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.