NetworkOnMainThreadException错误?

时间:2014-02-04 21:44:31

标签: android networkonmainthread

我已经完成了以下代码来显示一个简单的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();
   }

}

4 个答案:

答案 0 :(得分:1)

您需要在非UI线程上调用getTwitterTimeline。从AsyncTaskLoader拨打电话。像(Notepad ++中的盲代码):

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    final 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);
    new AsyncTask<Void, Void, String>() {
        public String doInBackground(Void ... params) {
            return getTwitterTimeline();
        }
        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";
                }
                TextView tweetTextView = (TextView)rootView.findViewById(R.id.twitterfeed);
                tweetTextView.setText(tweets);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }.execute();
    return rootView;
}

答案 1 :(得分:0)

您需要在另一个线程中运行getTwitterTimeline。我建议在onCreateView()中创建一个AsyncTask。您获得的例外情况是因为在您等待Twitter回复时无法绘制UI。因此,“主线上的网络”问题。

见这里:

http://developer.android.com/reference/android/os/AsyncTask.html

答案 2 :(得分:0)

使用AsyncTask类获取您的推特数据,您无法使用UI线程从网络获取数据。

答案 3 :(得分:0)

您正在主线程上进行网络通信。你不被允许这样做。您可以使用AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html 

只是为了进行测试,您可以在主要活动中添加以下内容,但这是不好的做法。

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
相关问题