Connecting Your App to the Backend
Now that the UI is in place, we need to connect the app to the backend API. There are two separate parts to this:
- Add code that gets the handle needed to access the backend API service. (All requests to the backend will use this handle.)
- Add click handlers for the UI that respond to user actions by sending requests to the backend.
Adding code to get the backend service handle
Backend API requests are made through a service handle object. Let's add a
utility method to obtain a handle to the backend service in our
AppConstants.java
.
To add code to get the backend service handle:
-
Open the file
AppConstants.java
in Android Studio. -
Replace the contents of the file with the following code:
package com.google.devrel.samples.helloendpoints; import android.app.Activity; import android.app.Dialog; import android.content.Context; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.appspot.<your_project_id>.helloworld.Helloworld; import javax.annotation.Nullable; public class AppConstants { /** * Class instance of the JSON factory. */ public static final JsonFactory JSON_FACTORY = new AndroidJsonFactory(); /** * Class instance of the HTTP transport. */ public static final HttpTransport HTTP_TRANSPORT = AndroidHttp.newCompatibleTransport(); /** * Retrieve a Helloworld api service handle to access the API. */ public static Helloworld getApiServiceHandle() { // Use a builder to help formulate the API request. Helloworld.Builder helloWorld = new Helloworld.Builder(AppConstants.HTTP_TRANSPORT, AppConstants.JSON_FACTORY,null); return helloWorld.build(); } }
Replace the value
<your_project_id>
in the imports listed above with the actual project ID for the backend API, using Android studio's code completion. Alternatively, you can copy the actual project ID listed in the project navigator line/libs/helloworld-v1-1.17.0-rc-SNAPSHOT.jar/com.appspot.the_actual_project_id.helloworld
.