2016-03-26 36 views
1

主要活动okHttp:为什么我的应用程序崩溃没得到响应

公共类MainActivity扩展AppCompatActivity { 字符串响应;

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

公共无效点击(视图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(); 
相关问题