我正在构建我的第一个Android应用程序 - 这将在列表中显示我的推文。
我设法让应用程序提前工作,但推文有时需要很长时间才能下载,应用程序会变得无法响应或崩溃。
我决定在应用程序中添加一个线程,这样它就不会没有响应,但现在它根本不起作用:/
有谁知道什么是错的?这是我学习java的第三天,我似乎无法弄清问题是什么。
以下是代码:
package com.app.first;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class Twitter extends ListActivity {
public ProgressDialog pd = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Show the ProgressDialog on this thread
pd = ProgressDialog.show(this, "Working..", "Downloading Data...",
true, false);
new LoadTwitterFeed().execute();
}
public class LoadTwitterFeed extends AsyncTask<String, Integer, String> {
String tweets[] = new String[9];
public String readTwitterFeed() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"https://api.twitter.com/1/statuses/user_timeline.json?screen_name=jjmpsp&include_rts=false&count=10");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String readTwitterFeed = readTwitterFeed();
try {
JSONArray jsonArray = new JSONArray(readTwitterFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
tweets[i] = jsonObject.getString("text").toString();
}
} catch (Exception e) {
e.printStackTrace();
}
setListAdapter(new ArrayAdapter<String>(Twitter.this,
android.R.layout.simple_list_item_1, tweets));
return null;
}
@Override
protected void onPostExecute(String result) {
// what to do when the task ends.
pd.hide();
}
}
}
答案 0 :(得分:2)
在onPostExecute中设置此代码
setListAdapter(new ArrayAdapter<String>(Twitter.this,
android.R.layout.simple_list_item_1, tweets));