我创建了一个 AsyncTask,它在执行时从网站加载数据。目前我收到一个空指针异常,我认为这是因为我试图过早地填充 UI,所以我希望创建某种 if 语句来说明 AsyncTask 是否未完成显示加载图形以及何时填充数据。但我不知道该怎么做,有人知道我怎么能做到这一点,或者至少为我指明了正确的方向。
到目前为止,这是我的代码
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();
FillData();
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 = "website/" + chosenLeagueId + "/news?timestamp=" + unixTimeStamp;
newsFeedURL = "https://www.website.com" + 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"));
}
} 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 = "website/" + chosenLeagueId + "/results?&team_id=" + ChosenTeamId + "&limit=31×tamp=" + unixTimeStamp;
resultsFeedURL = "https://www.website.com" + 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();
} 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 = "website/" + chosenLeagueId + "/results?month=04&team_id=" + ChosenTeamId + "&limit=31×tamp=" + unixTimeStamp;
resultsFeedURL = "https://www.website.com" + 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);
}
} 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();
loadResultsFeed();
loadLastResults();
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] + " ");
}
}
}
public void FillData(){
if (ChosenMethod.equals("Team")) {
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);
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);
adapter = new MergeAdapter();
adapter.addView(header);
adapter.addAdapter(arrayAdapter);
adapter.addView(header2);
adapter.addView(resultsView);
adapter.addView(header3);
adapter.addAdapter(arrayAdapter3);
setListAdapter(adapter);
} 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);
}
}