我正在尝试运行后台异步任务来加载我的数据。
我有 2 种加载数据的方法,我在AsyncTask
.
加载完成后,我有一个方法调用Filldata
,用数据填充 UI。
问题是目前它只使用首先完成下载数据的任何方法填充 UI。
有没有办法在一个内部运行多个方法,AsyncTask
还是我需要多个AsyncTasks
?
这是我的AsyncTask
public class PostTask extends AsyncTask<Void, String, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
boolean result = false;
loadNewsFeed();
loadResultsFeed();
publishProgress("progress");
return result;
}
protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.v("BGThread", "begin fillin data");
FillData();
}
}
这是我的完整代码
public void checkPreferences(){
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
ChosenMethod = preferences.getString("ChosenMethod", ChosenMethod);
ChosenLeagueID = preferences.getString("ChosenLeagueId", ChosenLeagueID);
ChosenTeamId = preferences.getString("ChosenTeamId", ChosenTeamId);
Log.v("lc", "newsurl" + newsFeedURL);
Log.v("myapp", "ChosenMethod Home = " + ChosenMethod);
Log.v("myapp", "ChosenLeagueID Home = " + ChosenLeagueID);
Log.v("myapp", "ChosenTeamID Home = " + ChosenTeamId);
if (ChosenMethod.equals("Team")) {
setContentView(R.layout.homeactteam2);
newsAmount = 5;
} else {
newsAmount = 10;
setContentView(R.layout.homeactteam);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Check Preferences which sets UI
checkPreferences();
PostTask posttask;
posttask = new PostTask();
posttask.execute();
Button backbtn = (Button) findViewById(R.id.backbtn);
//Listening to button event
backbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent previousScreen = new Intent(getApplicationContext(), ChooseTeamActivity.class);
ChosenMethod = "null";
SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ChosenMethod", ChosenMethod);
editor.commit();
previousScreen.putExtra("FullData", fulldata);
startActivity(previousScreen);
}
});
//((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
//
// public void onRefresh() {
// // Do work to refresh the list here.
// loadData();
// }
//});
//
}
public void loadNewsFeed(){
newsFeedRequest = "" + chosenLeagueId + "" + unixTimeStamp;
newsFeedURL = "" + newsFeedRequest;
String myhash = buildHmacSignature(apiKey, newsFeedURL);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(newsFeedURL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("requestToken", myhash));
pairs.add(new BasicNameValuePair("apiUser", apiUser));
try {
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
fulldata = String.valueOf(json);
Log.v("myApp","newsdata" + fulldata);
newsList = new ArrayList<String>();
newsList2 = new ArrayList<String>();
newsList3 = new ArrayList<String>();
imageList = new ArrayList<String>();
JSONObject obj = new JSONObject(json);
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("news");
Log.v("lc","newsAmount= " + newsAmount);
for(int t = 0; t < newsAmount; t++){
JSONObject newsTitleDict = jArray.getJSONObject(t);
imageList.add(newsTitleDict.getString("image_small"));
newsList3.add(newsTitleDict.getString("title"));
}
for(int t = 0; t < 1; t++){
JSONObject newsTitleDict = jArray.getJSONObject(t);
newsList.add(newsTitleDict.getString("title"));
// newsList2.add(newsTitleDict.getString("title"));
}
Log.v("BGThread", "Loaded news");
loadResultsFeed();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void loadResultsFeed(){
resultsFeedRequest = "" + chosenLeagueId + "" + ChosenTeamId + "" + unixTimeStamp;
resultsFeedURL = "https://secure.pitchero.com/_services/api/" + resultsFeedRequest;
String myhash = buildHmacSignature(apiKey, resultsFeedURL);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(resultsFeedURL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("requestToken", myhash));
pairs.add(new BasicNameValuePair("apiUser", apiUser));
try {
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
fulldata = String.valueOf(json);
Log.v("myApp","resultsdata" + fulldata);
newsList = new ArrayList<String>();
newsList2 = new ArrayList<String>();
newsList3 = new ArrayList<String>();
imageList = new ArrayList<String>();
JSONObject obj = new JSONObject(json);
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("results");
if(jArray.length() < 1) loadLastResults();
for(int t = 0; t < 1; t++){
resultsDict = jArray.getJSONObject(t);
HomeTeam = resultsDict.getString("hometeam");
AwayTeam = resultsDict.getString("awayteam");
HomeScore = resultsDict.getString("homescore");
AwayScore = resultsDict.getString("awayscore");
Attendance = resultsDict.getString("attendance");
Division = resultsDict.getString("division");
Log.v("lc","hometeam" + HomeTeam);
Log.v("lc","awayteam" + AwayTeam);
Log.v("BGThread", "Loaded results");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void loadLastResults(){
resultsFeedRequest = "" + chosenLeagueId + "" + ChosenTeamId + "&limit=31×tamp=" + unixTimeStamp;
resultsFeedURL = "" + resultsFeedRequest;
String myhash = buildHmacSignature(apiKey, resultsFeedURL);
Date anotherCurDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM");
String CurMonth = formatter.format(anotherCurDate);
int Int = Integer.parseInt(CurMonth);
int MonthInt = Int -1;
CurMonth = (String) (String.valueOf(MonthInt));
if (CurMonth.equals("1")){
lastMonth = "12";
}
else {
if(CurMonth.length() < 2){
lastMonth = "0" + CurMonth;
} else {
lastMonth = CurMonth;
}
}
Log.v("lc","month= " + CurMonth);
Log.v("lc","LastMonth= " + lastMonth);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(resultsFeedURL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("requestToken", myhash));
pairs.add(new BasicNameValuePair("apiUser", apiUser));
try {
post.setEntity (new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
fulldata = String.valueOf(json);
Log.v("myApp","resultsdata" + fulldata);
newsList = new ArrayList<String>();
newsList2 = new ArrayList<String>();
newsList3 = new ArrayList<String>();
imageList = new ArrayList<String>();
JSONObject obj = new JSONObject(json);
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("results");
for(int t = 0; t < 1; t++){
resultsDict = jArray.getJSONObject(t);
HomeTeam = resultsDict.getString("hometeam");
AwayTeam = resultsDict.getString("awayteam");
HomeScore = resultsDict.getString("homescore");
AwayScore = resultsDict.getString("awayscore");
Attendance = resultsDict.getString("attendance");
Division = resultsDict.getString("division");
Log.v("lc","hometeam" + HomeTeam);
Log.v("lc","awayteam" + AwayTeam);
Log.v("BGThread", "Loaded Last results");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class PostTask extends AsyncTask<Void, String, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
boolean result = false;
loadNewsFeed();
publishProgress("method1_complete");
loadResultsFeed();
publishProgress("method2_complete");
return result;
}
protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.v("BGThread", "begin fillin data");
FillData();
}
}
public void FillData(){
if (ChosenMethod.equals("Team")) {
arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);
String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]);
String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]);
arrayAdapter3 = new LazyAdapter(this, mStrings, news);
ListView list = getListView();
list.setTextFilterEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View header = inflater.inflate( R.layout.homeheader, list, false);
View header2 = inflater.inflate( R.layout.homeheader2, list, false);
View header3 = inflater.inflate( R.layout.homeheader3, list, false);
//setListAdapter (arrayAdapter);
resultsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.resultscell,
null);
TextView homeTeam = (TextView) resultsView.findViewById(R.id.HomeTeam);
homeTeam.setText(HomeTeam);
TextView awayTeam = (TextView) resultsView.findViewById(R.id.AwayTeam);
awayTeam.setText(AwayTeam);
TextView homeScore = (TextView) resultsView.findViewById(R.id.HomeScore);
homeScore.setText(HomeScore);
TextView awayScore = (TextView) resultsView.findViewById(R.id.AwayScore);
awayScore.setText(AwayScore);
TextView attendance = (TextView) resultsView.findViewById(R.id.Attendence);
attendance.setText("Att:" + Attendance);
TextView division = (TextView) resultsView.findViewById(R.id.Division);
division.setText(Division);
Log.v("BGThread", "Filled results");
adapter = new MergeAdapter();
adapter.addView(header);
adapter.addAdapter(arrayAdapter);
adapter.addView(header2);
adapter.addView(resultsView);
adapter.addView(header3);
adapter.addAdapter(arrayAdapter3);
setListAdapter(adapter);
Log.v("BGThread", "Filled Merge Adapter Team");
} else {
arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList);
arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2);
//arrayAdapter3 = new ArrayAdapter(this, R.layout.complex_item, newsList3);
String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]);
String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]);
arrayAdapter3 = new LazyAdapter(this, mStrings, news);
ListView list = getListView();
list.setTextFilterEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
View header3 = inflater.inflate( R.layout.homeheader3, list, false);
//setListAdapter (arrayAdapter);
adapter = new MergeAdapter();
adapter.addView(header3);
adapter.addAdapter(arrayAdapter3);
setListAdapter(adapter);
Log.v("BGThread", "Filled Merge Adapter League");
}
}