我尝试使用此link显示Twitter时间轴用户Feed。与我的代码不同的是我在Fragment类中尝试它。在这段代码中不需要twitter4j.jar库,是不是?这是代码
public class WhatsHotFragment extends Fragment {
public WhatsHotFragment() {
}
TextView tweetTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_whats_hot,
container, false);
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.tweetTextView);
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();
}
}
但我得到错误logcat:
01-19 10:41:37.137: E/AndroidRuntime(1435): Process: com.tugasbesar.medantrain, PID: 1435
01-19 10:41:37.137: E/AndroidRuntime(1435): android.os.NetworkOnMainThreadException
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
01-19 10:41:37.137: E/AndroidRuntime(1435): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
01-19 10:41:37.137: E/AndroidRuntime(1435): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
01-19 10:41:37.137: E/AndroidRuntime(1435): at java.net.InetAddress.getAllByName(InetAddress.java:214)
01-19 10:41:37.137: E/AndroidRuntime(1435): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-19 10:41:37.137: E/AndroidRuntime(1435): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-19 10:41:37.137: E/AndroidRuntime(1435): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-19 10:41:37.137: E/AndroidRuntime(1435): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-19 10:41:37.137: E/AndroidRuntime(1435): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-19 10:41:37.137: E/AndroidRuntime(1435): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-19 10:41:37.137: E/AndroidRuntime(1435): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-19 10:41:37.137: E/AndroidRuntime(1435): at com.tugasbesar.medantrain.WhatsHotFragment.getTwitterTimeline(WhatsHotFragment.java:64)
01-19 10:41:37.137: E/AndroidRuntime(1435): at com.tugasbesar.medantrain.WhatsHotFragment.onCreateView(WhatsHotFragment.java:38)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.app.Fragment.performCreateView(Fragment.java:1700)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.app.BackStackRecord.run(BackStackRecord.java:684)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.os.Handler.handleCallback(Handler.java:733)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.os.Handler.dispatchMessage(Handler.java:95)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.os.Looper.loop(Looper.java:136)
01-19 10:41:37.137: E/AndroidRuntime(1435): at android.app.ActivityThread.main(ActivityThread.java:5017)
01-19 10:41:37.137: E/AndroidRuntime(1435): at java.lang.reflect.Method.invokeNative(Native Method)
01-19 10:41:37.137: E/AndroidRuntime(1435): at java.lang.reflect.Method.invoke(Method.java:515)
01-19 10:41:37.137: E/AndroidRuntime(1435): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-19 10:41:37.137: E/AndroidRuntime(1435): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-19 10:41:37.137: E/AndroidRuntime(1435): at dalvik.system.NativeStart.main(Native Method)
他说
这个项目在android 2.2中测试,单独调用url 如果发生NetworkonMainThreadExecption,则在android 3.0+中运行。
使用@amit singh
中的AsyncTask类更新了代码public class WhatsHotFragment extends Fragment {
public WhatsHotFragment() {
}
TextView tweetTextView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_whats_hot,
container, false);
new MyAsyncTask().execute();
tweetTextView = (TextView) rootView.findViewById(R.id.tweetTextView);
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();
}
public class MyAsyncTask extends AsyncTask<Void, Void, String>
{
@Override
protected void onPreExecute()
{
// Show progress dialog if you need...
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params)
{
String twitterTimeline = getTwitterTimeline();
return twitterTimeline;
}
@Override
protected void onPostExecute(String twitterTimeline)
{
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.setText(tweets);
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
super.onPostExecute(twitterTimeline);
}
}
}
答案 0 :(得分:0)
这样做 -
公共类MyAsyncTask扩展了AsyncTask { @覆盖 protected void onPreExecute() { //如果需要,显示进度对话框...... super.onPreExecute(); }
@Override
protected String doInBackground(Void... params)
{
String twitterTimeline = getTwitterTimeline();
return twitterTimeline;
}
@Override
protected void onPostExecute(String twitterTimeline)
{
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.tweetTextView);
tweetTextView.setText(tweets);
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
super.onPostExecute(result);
}
}
并从onCreateView -
调用此行new MyAsyncTask().execute();
如果你遇到任何问题,那么你可以问。