gpt4 book ai didi

android - AsyncTask 仍在阻塞 UI(UI 未响应)

转载 作者:行者123 更新时间:2023-11-29 01:27:36 27 4
gpt4 key购买 nike

我有一个新闻应用程序,我可以在其中获取一些 XML 和 API 并立即插入到数据库中。我在获取/插入数据库过程中使用 AsyncTask。但是我仍然遇到障碍(UI 没有响应)

for (int i = 0; i < urls.size(); i++) {
MyAsyncTask myAsyncTask = new MyAsyncTask(urls.get(i));
myAsyncTask.execute();
}

AsyncTask 类:

  private class MyAsyncTask extends AsyncTask<Void,Void,Void> {

Url mUrl;
public MyAsyncTask(Url url){
this.mUrl = url;
}


@Override
protected Void doInBackground(Void... params) {
connect(mUrl.getUrl(),mUrl.getSourceName(),mUrl.getChoice(),mUrl.getId());
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
whenToInflate[mUrl.getId()] = true;
mProgressState += 15;
mProgress.setProgress(mProgressState);

if (areAllTrue(whenToInflate)) {
inflate(1907);
Arrays.fill(whenToInflate, false);
}
}
}

连接方法:

private void connect(String url, final String sourceSite, final int sourceChoice, final int i) {


stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
if (sourceChoice == 14) {
database.insertFixtures(response, "FOOTBALL");
} else if (sourceChoice == 10 || sourceChoice == 20) {
database.insertNews(response, sourceChoice);
} else {
if (sourceChoice == 1) response = URLDecoder.decode(URLEncoder.encode(response, "iso8859-1"), "UTF-8");
database.insertNewsXML(response, sourceSite, sourceChoice);
}


} catch (IllegalStateException | IllegalArgumentException | UnsupportedEncodingException e) {
e.printStackTrace();
}

}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();

}
});

VolleySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);
}

VolleySingleton 类:

public class VolleySingleton {
private static VolleySingleton instance;
private static VolleySingleton ourInstance = new VolleySingleton();
private RequestQueue requestQueue;

private VolleySingleton() {
}

private VolleySingleton(Context context) {
requestQueue = Volley.newRequestQueue(context);
}

public static VolleySingleton getInstance() {
return ourInstance;
}

public static VolleySingleton getInstance(Context context) {
if (instance == null) {
instance = new VolleySingleton(context);
}
return instance;
}

public RequestQueue getRequestQueue() {
return requestQueue;
}


public <T> void addToRequestQueue(Request<T> req) {
req.setTag("App");
getRequestQueue().add(req);
}
}

最佳答案

那是因为你在更新Progress的进度。所以这就是它给出错误的原因。在 onProgressUpdate 方法 AsyncTask 中更新进度。

关于android - AsyncTask 仍在阻塞 UI(UI 未响应),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33056074/

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