-1

我是 Android 开发的新手。这是我的代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {


/** Called when the activity is first created. */

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,     this.fetchTwitterPublicTimeline()));
  }

  public ArrayList<String> fetchTwitterPublicTimeline() {
      ArrayList<String> listItems = new ArrayList<String>();

      try {
          URL twitter = new URL("http://twitter.com/statuses/public_timeline.json");
          URLConnection tc = twitter.openConnection();
          BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
          String line;

          while ((line = in.readLine()) != null) {
              JSONArray ja = new JSONArray(line);
              for (int i = 0; i < ja.length(); i++) {
                  JSONObject jo = (JSONObject) ja.get(i);
                  listItems.add(jo.getString("text"));
              }
          }
      } catch (MalformedURLException 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();
      }

      return listItems;

  } 


}

这是我的 acitivity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
    <ListView android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

logcat 在下面(或在此链接上):

03-21 09:16:15.530: E/AndroidRuntime(31912):    ... 11 more
03-21 09:16:33.590: E/AndroidRuntime(31991): FATAL EXCEPTION: main
03-21 09:16:33.590: E/AndroidRuntime(31991): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.simplebrowser/com.example.simplebrowser.MainActivity}: android.os.NetworkOnMainThreadException
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.os.Looper.loop(Looper.java:137)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.app.ActivityThread.main(ActivityThread.java:5041)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at java.lang.reflect.Method.invokeNative(Native Method)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at java.lang.reflect.Method.invoke(Method.java:511)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at dalvik.system.NativeStart.main(Native Method)
03-21 09:16:33.590: E/AndroidRuntime(31991): Caused by: android.os.NetworkOnMainThreadException
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at com.example.simplebrowser.MainActivity.fetchTwitterPublicTimeline(MainActivity.java:38)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at com.example.simplebrowser.MainActivity.onCreate(MainActivity.java:29)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.app.Activity.performCreate(Activity.java:5104)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-21 09:16:33.590: E/AndroidRuntime(31991):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-21 09:16:33.590: E/AndroidRuntime(31991):    ... 11 more

我已经按照这个教程进行操作,但我似乎无法让它工作。

4

3 回答 3

0

您必须执行网络任务AsyncTask以避免阻塞 UI 线程。

无法启动活动 ComponentInfo{com.example.simplebrowser/com.example.simplebrowser.MainActivity}:android.os.NetworkOnMainThreadException

于 2013-03-20T22:30:24.273 回答
0

您不能调用fetchTwitterPublicTimeline()主 UI 线程。在处理程序或计时器线程中将其称为延迟。

这是一个简单的例子:

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        fetchTwitterPublicTimeline();
    }
}, 400);

更好的做法是使用真正的Thread或更好的AsyncTask. 参考一个非常有用的例子。

于 2013-03-20T22:30:39.780 回答
0

引起:android.os.NetworkOnMainThreadException,首先阅读您的异常并搜索解决方案,如果您没有找到任何问题,请发布问题。最简单的解决方案是使用 AsyncTask。有 doInBackGround() 和 onPostExecute()。

//This Run in background
protected void doInBackground(String url){

//fetch objects
//parse objects

//it pass parsedObjects to onPostExecute method
 return parsedObjects;
} 

//This run on current thread (Ui thread in this case) 
protected void onPostExecute(ParsedObjects o){
//Receives parsedObejct from doInBackground
//update UI
}
于 2013-03-21T11:06:35.137 回答