2013-05-15 101 views
0

我有以下代碼:GSON和谷歌

public String test(){ 
     URL url = null; 
     try { 
      url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN"); 
     } catch (MalformedURLException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     BufferedReader reader = null; 
     String x = ""; 
     try { 
      reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); 
      for (String line; (line = reader.readLine()) != null;) { 
       System.out.println(line); 
       x = line; 
      } 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } finally{ 
      if (reader !=null) try{reader.close();} catch (IOException ignore) { 
      }{} 
     } 
     JsonElement root = new JsonParser().parse(x); 
     return x; 
    } 
} 

現在我想插入文字下面的TextView。

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_create_competetion); 

    TextView tv = (TextView) findViewById(R.id.competetion_text); 
    JsonCollector jc = new JsonCollector(); 

    tv.setText(jc.test()); 

但是,當我嘗試運行它。我收到以下錯誤:

FATAL EXCEPTION: main 
E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
E/AndroidRuntime(1800): at android.app.ActivityThread.access$600(ActivityThread.java:141) 
E/AndroidRuntime(1800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
E/AndroidRuntime(1800): at android.os.Handler.dispatchMessage(Handler.java:99) 
    E/AndroidRuntime(1800): at android.os.Looper.loop(Looper.java:137) 
    E/AndroidRuntime(1800):  at android.app.ActivityThread.main(ActivityThread.java:5039) 
    E/AndroidRuntime(1800):  at java.lang.reflect.Method.invokeNative(Native Method) 
    E/AndroidRuntime(1800):  at java.lang.reflect.Method.invoke(Method.java:511) 
    E/AndroidRuntime(1800):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
    E/AndroidRuntime(1800):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
    E/AndroidRuntime(1800):  at dalvik.system.NativeStart.main(Native Method) 
    E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException 
    E/AndroidRuntime(1800):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 
    E/AndroidRuntime(1800):  at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 
    E/AndroidRuntime(1800): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByName(InetAddress.java:214) 
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70) 
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50) 
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340) 
E/AndroidRuntime(1800):  at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316) 
    E/AndroidRuntime(1800):  at libcore.net.http.HttpEngine.connect(HttpEngine.java:311) 
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290) 
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240) 
E/AndroidRuntime(1800): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282) 

誰能告訴我爲什麼會發生這種情況?

請注意,我已經添加下面一行在我的Android清單:

<uses-permission android:name="android.permission.INTERNET" /> 
+0

注意,在你的logcat行:「產生的原因:android.os.NetworkOnMainThreadException」 – RvdK

回答

4

你在主線程上執行HTTP通信,這就是爲什麼你得到一個NetworkOnMainThreadException。這樣做在一個單獨的線程,使用AsyncTask將是一個理想的解決方案,下面是你如何能夠實現它的一個例子:

private TextView tv; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_create_competetion); 

    tv = (TextView) findViewById(R.id.competetion_text); 
    JsonCollector jc = new JsonCollector(); 

    // Create and execute a new AsyncTask, the TextView will 
    // be updated asynchronously when the task has finished. 
    updateTextView(); 
} 

private void updateTextView() { 
    new AsyncTask<Void, Void, String>() { 

     @Override 
     /* Runs on a separate thread */ 
     protected String doInBackground(Void... params) { 
      String result = null; 
      BufferedReader reader = null; 
      try { 
       URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN"); 
       reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); 
       for (String line; (line = reader.readLine()) != null;) { 
        System.out.println(line); 
        result = line; 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } finally { 
       if (reader != null) { 
        try { 
         reader.close(); 
        } catch (IOException e) { 
         // Ignore 
        } 
       } 
      } 

      return result; 
     } 

     @Override 
     /* Runs on the UI/Main thread when doInBackground() 
     * has finished */ 
     protected void onPostExecute(String result) { 
      if(result != null) { 
       // Update the TextView only if we got a result 
       // from the HTTP request 
       tv.setText(result); 
      } 
     } 

    }.execute(); 
} 
+0

你可以給我上如何實現這樣的例子? –

+0

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

+1

@MarcRasmussen我已經用示例更新了我的答案。 –

1

如果您需要在主線程聯網在OnCreate添加幾行代碼()方法

StrictMode.ThreadPolicy policy = 
     new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy);