我已经完成了以下代码来显示一个简单的 twitter 提要,但它出现了一个错误。可能是因为我在做片段,但我不确定。我遵循了一个关于如何创建 twitter 提要的教程,所以它应该可以工作,但我不知道。大家能找到问题吗?
package info.android.icecreamparties;
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.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class HomeFragment extends Fragment {
TextView tweetTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
TextView about = (TextView)rootView.findViewById(R.id.homepageintro);
Typeface bb = Typeface.createFromAsset(getActivity().getAssets(), "BebasNeue.otf");
about.setTypeface(bb);
String twitterTimeline = getTwitterTimeline();
try {
String tweets = "";
JSONArray jsonArray = new JSONArray(twitterTimeline);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int j = i + 1;
tweets += "Tweet #" + j + " \n";
tweets += "Date:" + jsonObject.getString("created_at") + "\n";
tweets += "Post:" + jsonObject.getString("text") + "\n\n";
}
tweetTextView = (TextView)rootView.findViewById(R.id.twitterfeed);
tweetTextView.setText(tweets);
} catch (JSONException e) {
e.printStackTrace();
}
return rootView;
}
public String getTwitterTimeline() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"http://api.twitter.com/1/statuses/user_timeline/BBCNews.json?count=10&include_rts=1&callback=?");
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 {
// Display couldn't obtain the data from twitter
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}