Reputation:
Main activity
public class MainActivity extends AppCompatActivity { String response ;
@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 class
public class GetExample { OkHttpClient client;
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 File
<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>
Upvotes: 1
Views: 1027
Reputation: 309
For such crashing questions you can add your crash logs. I think this crash occurs for NetworkOnMainThreadException.This exception is thrown when your application attempts to perform a networking operation on its main thread. Your networking operations must perform on an another thread like :
Thread thread = new Thread() {
@Override
public void run() {
// your run method
}
};
thread.start();
Upvotes: 1