gpt4 book ai didi

Android等待截击完成并稍后更新用户界面

转载 作者:行者123 更新时间:2023-11-30 05:09:55 25 4
gpt4 key购买 nike

我正在使用 volley 包从网站 (JSON) 检索数据。

这是我的方法

  private void getEarthquakeList(){
// ...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
//Earthquake Feeder
String url ="https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_month.geojson";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response is: ",response);
//Parsing Json
parseJson(response);
final ListView earthquakeListView = (ListView)findViewById(R.id.list);
//Sort the array according to magnitude
earthquakeArrayList.sort((a, b) -> Double.compare(b.getTime(), a.getTime()));
mAdapter = new EarthquakeAdapter(getApplicationContext(), earthquakeArrayList);
earthquakeListView.setAdapter(mAdapter);

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error",error.getMessage());
}
});

// Add the request to the RequestQueue.
queue.add(stringRequest);
}

问题是,现在我正在该方法返回响应后更新 UI。

这些是行

//Sort the array according to a date
earthquakeArrayList.sort((a, b) -> Double.compare(b.getTime(), a.getTime()));
mAdapter = new EarthquakeAdapter(getApplicationContext(), earthquakeArrayList);
earthquakeListView.setAdapter(mAdapter);

当我在 MainActivity 中运行时没有问题,用户打开应用程序并获取地震列表。

当我想切换到我每隔几分钟监控一次的服务时,或者当网站内容发生变化时,问题就开始了。所以我想要我的方法而不更新其中的 UI。问题是,如果我不更新 onResponse 内的 UI,UI 线程将继续并导致一个空数组。

所以如果我不在里面做这个数组earthquakeArrayList 保持空

public void onResponse(String response) 

想法如何将两者分开,一方面运行方法并获取数据,另一方面主线程将能够访问数据而不是完成执行。谢谢EG

最佳答案

目前推荐的解决方案是使用 LiveData . LiveData 适用于 Observer Pattern ,因此您可以让任意数量的观察者观察服务和 Activity 中的更新数据,但他们需要处于相同的上下文中。这些主题有点高级,但却是将 UI 与数据层分离的好方法。你可以通过这两个链接

关于Android等待截击完成并稍后更新用户界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53911606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com