2016-03-26 10 views
1

主な活動okHttp:なぜ私のアプリケーションが応答

パブリッククラスMainActivityがAppCompatActivity { 文字列の応答を拡張し得るdidntはクラッシュしています。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    } 

ます。public voidクリック(ビューV){ GetExample例=新しいGetExample();

try { 
     response = example.run(); 
     Toast.makeText(MainActivity.this, "response is :" + response, Toast.LENGTH_LONG).show(); 

    } catch (IOException e) { 
     Toast.makeText(MainActivity.this, "error" + e, Toast.LENGTH_LONG).show(); 

    } 
    } 
} 

GetExampleクラス

パブリッククラスGetExample { OkHttpClientクライアント。

public String run() throws IOException { 
    client = new OkHttpClient(); 
    Request request = new Request.Builder().url("http://grocit.pe.hu/getcategories.php").build(); 
    Response response = client.newCall(request).execute(); 
    return response.body().string(); 
} 
} 

なクラッシュ質問用のXMLファイル

<RelativeLayout 
    android:layout_height="match_parent" 
    android:layout_width="match_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 
<Button 
    android:layout_width="300dp" 
    android:layout_height="300dp" 
    android:onClick="click" 
    android:text="click me!" 
    /> 
</RelativeLayout> 

答えて

1

あなたのクラッシュログを追加することができます。このクラッシュはNetworkOnMainThreadExceptionで発生します。この例外は、アプリケーションがメインスレッドでネットワーク操作を実行しようとしたときにスローされます。 ネットワークの操作は、次のような別のスレッドで実行する必要があります。

Thread thread = new Thread() { 
      @Override 
      public void run() { 
       // your run method 
      } 
     }; 
    thread.start(); 
関連する問題