-4

可能重复:
Android - android.os.NetworkOnMainThreadException

我关注网络http://codehenge.net/blog/2011/05/android-programming-tutorial-a-simple-twitter-feed-reader/ 我尝试运行这个示例代码但是当 Emulator Open Application , Emulator show alert对话框“不幸的是,AppName 已停止”谢谢帮助 >.< Example.java

package facebook.appwall;

import java.net.URL;
import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Example extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ArrayList<Tweet> tweets = getTweets("android", 1);

        ListView listView = (ListView) findViewById(R.id.ListViewId);
        listView.setAdapter(new UserItemAdapter(this, R.layout.listitem1, tweets));
    }

    public class UserItemAdapter extends ArrayAdapter<Tweet> {
        private ArrayList<Tweet> tweets;

        public UserItemAdapter(Context context, int textViewResourceId, ArrayList<Tweet> tweets) {
            super(context, textViewResourceId, tweets);
            this.tweets = tweets;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.listitem1, null);
            }

            Tweet tweet = tweets.get(position);
            if (tweet != null) {
                TextView username = (TextView) v.findViewById(R.id.username);
                TextView message = (TextView) v.findViewById(R.id.message);
                ImageView image = (ImageView) v.findViewById(R.id.avatar);

                if (username != null) {
                    username.setText(tweet.username);
                }

                if(message != null) {
                    message.setText(tweet.message);
                }

                if(image != null) {
                    image.setImageBitmap(getBitmap(tweet.image_url));
                }
            }
            return v;
        }
    }

    public Bitmap getBitmap(String bitmapUrl) {
        try {
            URL url = new URL(bitmapUrl);
            return BitmapFactory.decodeStream(url.openConnection() .getInputStream()); 
        }
        catch(Exception ex) {return null;}
    }

    public ArrayList<Tweet> getTweets(String searchTerm, int page) {
        String searchUrl = "http://search.twitter.com/search.json?q=@" 
                            + searchTerm + "&rpp=100&page=" + page;

        ArrayList<Tweet> tweets = new ArrayList<Tweet>();

        HttpClient client = new  DefaultHttpClient();
        HttpGet get = new HttpGet(searchUrl);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        String responseBody = null;
        try{
            responseBody = client.execute(get, responseHandler);
        }catch(Exception ex) {
            ex.printStackTrace();
        }

        JSONObject jsonObject = null;
        JSONParser parser=new JSONParser();

        try {
            Object obj = parser.parse(responseBody);
            jsonObject=(JSONObject)obj;

        }catch(Exception ex){
            Log.v("TEST","Exception: " + ex.getMessage());
        }

        JSONArray arr = null;

        try {
            Object j = jsonObject.get("results");
            arr = (JSONArray)j;
        }catch(Exception ex){
            Log.v("TEST","Exception: " + ex.getMessage());
        }

        for(Object t : arr) {
            Tweet tweet = new Tweet(
                    ((JSONObject)t).get("from_user").toString(),
                    ((JSONObject)t).get("text").toString(),
                    ((JSONObject)t).get("profile_image_url").toString()
                    );
            tweets.add(tweet);
        }

        return tweets;
    }

    public class Tweet {
        public String username;
        public String message;
        public String image_url;

        public Tweet(String username, String message, String url) {
            this.username = username;
            this.message = message;
            this.image_url = url;
        }
    }
}

主要的.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">
<ListView android:id="@+id/ListViewId" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"/>
</LinearLayout>

listview1.xml

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="wrap_content" 
    android:gravity="left|center" 
    android:layout_width="wrap_content" 
    android:paddingBottom="5px" 
    android:paddingTop="5px" 
    android:paddingLeft="5px">
    <ImageView android:id="@+id/avatar" 
        android:layout_width="wrap_content" 
        android:layout_height="fill_parent" 
        android:layout_marginRight="6dip" 
        android:src="@drawable/ic_launcher"/>
    <LinearLayout android:orientation="vertical" 
        android:layout_width="0dip" 
        android:layout_weight="1" 
        android:layout_height="fill_parent">
        <TextView android:id="@+id/username" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:gravity="center"/>
        <TextView android:id="@+id/message" 
            android:layout_width="wrap_content"
             android:layout_height="wrap_content" 
             android:layout_marginLeft="10px" 
             android:textColor="#0099CC"/>
    </LinearLayout>
</LinearLayout>

日志猫

12-18 22:32:32.562: E/dalvikvm(8406): Could not find class 'org.json.simple.parser.JSONParser', referenced from method facebook.appwall.Example.getTweets
12-18 22:32:32.582: W/dalvikvm(8406): VFY: unable to resolve new-instance 927 (Lorg/json/simple/parser/JSONParser;) in Lfacebook/appwall/Example;
12-18 22:32:32.582: D/dalvikvm(8406): VFY: replacing opcode 0x22 at 0x0040
12-18 22:32:32.592: D/dalvikvm(8406): DexOpt: unable to opt direct call 0x17ae at 0x42 in Lfacebook/appwall/Example;.getTweets
12-18 22:32:33.282: D/dalvikvm(8406): GC_CONCURRENT freed 111K, 8% free 2679K/2908K, paused 180ms+10ms, total 357ms
12-18 22:32:33.282: D/dalvikvm(8406): WAIT_FOR_CONCURRENT_GC blocked 159ms
12-18 22:32:33.292: I/dalvikvm-heap(8406): Grow heap (frag case) to 3.334MB for 635812-byte allocation
12-18 22:32:33.382: D/dalvikvm(8406): GC_FOR_ALLOC freed 4K, 7% free 3295K/3532K, paused 86ms, total 89ms
12-18 22:32:33.772: W/System.err(8406): android.os.NetworkOnMainThreadException
12-18 22:32:33.772: W/System.err(8406):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
12-18 22:32:33.792: W/System.err(8406):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
12-18 22:32:33.792: W/System.err(8406):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
12-18 22:32:33.801: W/System.err(8406):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
12-18 22:32:33.801: W/System.err(8406):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
12-18 22:32:33.812: W/System.err(8406):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-18 22:32:33.812: W/System.err(8406):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-18 22:32:33.812: W/System.err(8406):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-18 22:32:33.822: W/System.err(8406):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-18 22:32:33.833: W/System.err(8406):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:653)
12-18 22:32:33.852: W/System.err(8406):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
12-18 22:32:33.852: W/System.err(8406):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
12-18 22:32:33.872: W/System.err(8406):     at facebook.appwall.Example.getTweets(Example.java:102)
12-18 22:32:33.882: W/System.err(8406):     at facebook.appwall.Example.onCreate(Example.java:37)
12-18 22:32:33.902: W/System.err(8406):     at android.app.Activity.performCreate(Activity.java:5104)
12-18 22:32:33.902: W/System.err(8406):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-18 22:32:33.922: W/System.err(8406):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-18 22:32:33.922: W/System.err(8406):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-18 22:32:33.922: W/System.err(8406):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-18 22:32:33.922: W/System.err(8406):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-18 22:32:33.942: W/System.err(8406):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 22:32:33.942: W/System.err(8406):     at android.os.Looper.loop(Looper.java:137)
12-18 22:32:33.952: W/System.err(8406):     at android.app.ActivityThread.main(ActivityThread.java:5039)
12-18 22:32:33.962: W/System.err(8406):     at java.lang.reflect.Method.invokeNative(Native Method)
12-18 22:32:33.962: W/System.err(8406):     at java.lang.reflect.Method.invoke(Method.java:511)
12-18 22:32:33.973: W/System.err(8406):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-18 22:32:33.973: W/System.err(8406):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-18 22:32:33.992: W/System.err(8406):     at dalvik.system.NativeStart.main(Native Method)
12-18 22:32:33.992: D/AndroidRuntime(8406): Shutting down VM
12-18 22:32:34.002: W/dalvikvm(8406): threadid=1: thread exiting with uncaught exception (group=0x40a70930)
12-18 22:32:34.062: E/AndroidRuntime(8406): FATAL EXCEPTION: main
12-18 22:32:34.062: E/AndroidRuntime(8406): java.lang.NoClassDefFoundError: org.json.simple.parser.JSONParser
12-18 22:32:34.062: E/AndroidRuntime(8406):     at facebook.appwall.Example.getTweets(Example.java:108)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at facebook.appwall.Example.onCreate(Example.java:37)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at android.app.Activity.performCreate(Activity.java:5104)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at android.os.Looper.loop(Looper.java:137)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at android.app.ActivityThread.main(ActivityThread.java:5039)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at  java.lang.reflect.Method.invokeNative(Native Method)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at java.lang.reflect.Method.invoke(Method.java:511)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-18 22:32:34.062: E/AndroidRuntime(8406):     at dalvik.system.NativeStart.main(Native Method)
4

2 回答 2

0
 android.os.NetworkOnMainThreadException
12-18 22:32:33.772: W/System.err(8406):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)

将您的网络活动 (getTweets()) 移出主线程。使用类似AsyncTask的东西

于 2012-12-18T15:52:59.517 回答
0

NetworkOnMainThreadException :

当应用程序尝试在其主线程上执行网络操作时引发的异常。

表示您正在尝试从 UI 线程运行网络操作,因此将所有与网络相关的代码放在AsyncTask 的 doInBackground方法中,并在 doInBackground 方法执行完成时使用 onPostExecute 更新 UI

如果您使用的是API LEVEL 9 或 GREATER FROM 9 ,则在 Activity 的 onCreate 中添加StrictMode以避免此错误

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()  
                 .penaltyLog()
                 .build());
于 2012-12-18T15:53:52.697 回答