我有一个令人沮丧的艰难时期搞清楚这一点。我想我只是不明白如何正确组装AsyncTask。我在我的班级中有这个方法,但希望它作为AsyncTask运行,而不是在调用时将所有内容都阻塞。有人可以帮忙吗?提前谢谢。
private void getDatesNames() {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
ArrayList<String> dates = new ArrayList<String>();
ArrayList<String> teams = new ArrayList<String>();
try {
contacts = json.getJSONArray(TAG_CONTACTS);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
if ((c.getString(TAG_EMAIL1)).contains(league)) {
// Storing each json item in variable
String id = c.getString(TAG_ID);
String email1 = c.getString(TAG_EMAIL1);
String email2 = c.getString(TAG_EMAIL2);
dates.add(id);
teams.add(email1);
teams.add(email2);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
LinkedHashSet hs1 = new LinkedHashSet();
LinkedHashSet hs2 = new LinkedHashSet();
hs1.addAll(dates);
hs2.addAll(teams);
dates.clear();
teams.clear();
dates.addAll(hs1);
teams.addAll(hs2);
for (int i = 0; i < dates.size(); ++i) {
adapter1.add(dates.get(i));
}
for (int i = 0; i < teams.size(); ++i)
{
adapter2.add(teams.get(i));
}
答案 0 :(得分:0)
将你的慢速东西放在doInBackground中。在你填写两个数组的地方,最好只让它们成为私人决赛,所以不同方面可以看到它们。
AsyncTask<Void, Void, Void> newTask = new AsyncTask<Void, Void, Void>() {
private final ArrayList<String> dates = new ArrayList<String>();
private final ArrayList<String> teams = new ArrayList<String>();
@Override
protected void onPreExecute() {
//You dont' really need anything here, so you could leave out onPreExecute()...
}
@Override
protected ArrayList<String> doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
contacts = json.getJSONArray(TAG_CONTACTS);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
if ((c.getString(TAG_EMAIL1)).contains(league)) {
// Storing each json item in variable
String id = c.getString(TAG_ID);
String email1 = c.getString(TAG_EMAIL1);
String email2 = c.getString(TAG_EMAIL2);
dates.add(id);
teams.add(email1);
teams.add(email2);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
LinkedHashSet hs1 = new LinkedHashSet();
LinkedHashSet hs2 = new LinkedHashSet();
hs1.addAll(dates);
hs2.addAll(teams);
dates.clear();
teams.clear();
dates.addAll(hs1);
teams.addAll(hs2);
}
@Override
protected void onPostExecute(ArrayList<String> fileList) {
// dismiss dialog if necessary
for (int i = 0; i < dates.size(); ++i) {
adapter1.add(dates.get(i));
}
for (int i = 0; i < teams.size(); ++i)
{
adapter2.add(teams.get(i));
}
}
};
newTask.execute();
答案 1 :(得分:0)
您需要在getDateNames()
中运行doInBackground(String... arg)
。看看this tutorial。它也适用于JSON并使用AsyncTasks。