主要活动
公共类MainActivity扩展AppCompatActivity { 字符串响应;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){ GetExample example = new 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>
答案 0 :(得分:1)
对于此类崩溃问题,您可以添加崩溃日志。我认为NetworkOnMainThreadException会发生此崩溃。当您的应用程序尝试在其主线程上执行网络操作时,会抛出此异常。 您的网络操作必须在另一个线程上执行,如:
Thread thread = new Thread() {
@Override
public void run() {
// your run method
}
};
thread.start();