1+ package com .example .buttonapp ;
2+
3+ import android .os .Bundle ;
4+ import android .widget .Button ;
5+ import android .widget .Toast ;
6+ import androidx .appcompat .app .AppCompatActivity ;
7+ import java .io .IOException ;
8+ import okhttp3 .Call ;
9+ import okhttp3 .Callback ;
10+ import okhttp3 .OkHttpClient ;
11+ import okhttp3 .Request ;
12+ import okhttp3 .Response ;
13+
14+ public class MainActivity extends AppCompatActivity {
15+
16+ private final OkHttpClient client = new OkHttpClient ();
17+ // 10.0.2.2 is how the Android Emulator sees your computer's localhost
18+ private final String SERVER_URL = "http://10.0.2.2:8080/" ;
19+
20+ @ Override
21+ protected void onCreate (Bundle savedInstanceState ) {
22+ super .onCreate (savedInstanceState );
23+ setContentView (R .layout .activity_main );
24+
25+ Button btnOne = findViewById (R .id .btn_one );
26+ Button btnTwo = findViewById (R .id .btn_two );
27+
28+ btnOne .setOnClickListener (v -> makeRequest ("button1" ));
29+ btnTwo .setOnClickListener (v -> makeRequest ("button2" ));
30+ }
31+
32+ private void makeRequest (String path ) {
33+ Request request = new Request .Builder ()
34+ .url (SERVER_URL + path )
35+ .build ();
36+
37+ client .newCall (request ).enqueue (new Callback () {
38+ @ Override
39+ public void onFailure (Call call , IOException e ) {
40+ runOnUiThread (() ->
41+ Toast .makeText (MainActivity .this , "Network Error: " + e .getMessage (), Toast .LENGTH_LONG ).show ());
42+ }
43+
44+ @ Override
45+ public void onResponse (Call call , Response response ) throws IOException {
46+ final String responseData = response .isSuccessful () ? "Success!" : "Server Error: " + response .code ();
47+ runOnUiThread (() ->
48+ Toast .makeText (MainActivity .this , responseData , Toast .LENGTH_SHORT ).show ());
49+ }
50+ });
51+ }
52+ }
0 commit comments