Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester

Week 12 Theory – Displaying Maps; Consuming Web Services Using HTTP

Week 12 – Maps and Consuming Web Services over HTTP · 90 min read · 31 MCQs to check yourself

Embed Google Maps and add markers using the Maps SDK (Java project)

ProgrammingHut – Getting started with Retrofit (Java)

REST APIs explained in 5 minutes

Part A – Displaying maps

1. Three ways to show a map in an Android app

Approach How Needs API key / billing? Use
1. Map intent ACTION_VIEW with a geo: URI or a Google Maps URL – opens the Google Maps app No Show a place, directions – simplest
2. Google Maps SDK for Android Embed an interactive GoogleMap inside your activity (SupportMapFragment / MapView) Yes – API key from Google Cloud with a billing account enabled (mobile map loads are not charged per load, but billing must be set up) Custom markers, polylines, your own UI
3. OpenStreetMap (osmdroid / MapLibre) Open-source map library No Google key Free alternative
(WebView with an embedded web map) Load a web map page Depends Quick prototypes

2. Showing a location with an intent (no key)

// marker at coordinates with a label
Uri uri = Uri.parse("geo:33.6844,73.0479?q=33.6844,73.0479(Faisal Mosque)");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, uri);
mapIntent.setPackage("com.google.android.apps.maps");     // open in Google Maps if installed
startActivity(mapIntent);

// search a place by name
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=COMSATS+University+Islamabad")));

// turn-by-turn navigation
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=33.6844,73.0479&mode=d")));

// universal URL (works on any device, opens the app or the browser)
startActivity(new Intent(Intent.ACTION_VIEW,
        Uri.parse("https://www.google.com/maps/search/?api=1&query=33.6844,73.0479")));
URI Meaning
geo:lat,lng Show the map at coordinates
geo:lat,lng?z=15 Zoom level 15 (1 = world … 20 = buildings)
geo:0,0?q=lat,lng(Label) Marker with a label
geo:0,0?q=place+name Search for a place
google.navigation:q=...&mode=d/w/b Navigation: driving / walking / bicycling

Latitude (−90 to +90, north–south) and longitude (−180 to +180, east–west) are written in decimal degrees. Islamabad ≈ 33.68° N, 73.05° E.

3. Working with the Google Maps SDK

Setup steps

  1. Google Cloud Console → create a project → enable Maps SDK for Android → create an API key → restrict it to your app's package name + SHA-1 certificate fingerprint. Billing must be enabled on the project.
  2. Add the dependency com.google.android.gms:play-services-maps (and optionally maps-ktx).
  3. Put the key in the manifest (better: via local.properties with the Secrets Gradle Plugin, never commit keys to GitHub):
<meta-data android:name="com.google.android.geo.API_KEY" android:value="${MAPS_API_KEY}" />
  1. Add a SupportMapFragment to the layout and get the map asynchronously:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(@NonNull GoogleMap map) {
        LatLng campus = new LatLng(33.6844, 73.0479);
        map.addMarker(new MarkerOptions().position(campus).title("Campus").snippet("Main gate"));
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(campus, 15f));
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        map.getUiSettings().setZoomControlsEnabled(true);
    }
}

(Android Studio also has a ready Google Maps Views Activity template.)

Map features

Feature API
Markers addMarker(MarkerOptions().position(latLng).title(..).snippet(..).icon(..))
Camera moveCamera / animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom))
Map types MAP_TYPE_NORMAL, SATELLITE, TERRAIN, HYBRID, NONE
Shapes addPolyline (routes), addPolygon (areas), addCircle (radius)
UI controls Zoom buttons, compass, my-location button (isMyLocationEnabled needs location permission)
Events setOnMapClickListener, setOnMarkerClickListener, setOnInfoWindowClickListener
Geocoding Geocoder converts address ↔ coordinates (reverse geocoding)

Related services: Places API (search places), Directions/Routes API (routes), Geofencing (enter/exit areas – week 16).

Part B – Consuming web services using HTTP

4. HTTP and web service basics

A web service is software on a server that other programs (like your app) call over the network using HTTP to get or send data. Most mobile apps are clients of web services (weather, login, payments, news).

HTTP (HyperText Transfer Protocol) is a request–response protocol; HTTPS adds TLS encryption (Android blocks plain HTTP by default since Android 9 – cleartext traffic).

HTTP request = method + URL + headers + optional body. HTTP response = status code + headers + body (usually JSON).

Method Purpose (CRUD) Example
GET Read data GET /api/courses
POST Create new data POST /api/feedback with JSON body
PUT Replace/update PUT /api/students/7
PATCH Partial update PATCH /api/students/7
DELETE Delete DELETE /api/students/7
Status code Meaning
200 OK Success
201 Created New resource created
204 No Content Success, no body
400 Bad Request Invalid input
401 Unauthorized Login/token missing or wrong
403 Forbidden No permission
404 Not Found Resource does not exist
500 Internal Server Error Server-side failure
503 Service Unavailable Server overloaded/down

Common headers: Content-Type: application/json, Authorization: Bearer <token>, Accept.

Requirements in an Android app

  1. <uses-permission android:name="android.permission.INTERNET" /> (normal permission).
  2. Never call the network on the main (UI) thread – Android throws NetworkOnMainThreadException; use a background thread (ExecutorService) or a library that does it for you, such as Retrofit with enqueue().
  3. Use HTTPS.
  4. Handle no internet, timeouts and errors gracefully (show a message and a Retry button).

5. Consuming web services – HttpURLConnection and Retrofit

5.1 HttpURLConnection (built-in, low level)

// Network work must NOT run on the main thread – use a background thread
ExecutorService executor = Executors.newSingleThreadExecutor();
Handler mainHandler = new Handler(Looper.getMainLooper());

executor.execute(() -> {                       // background thread
    String result;
    HttpURLConnection conn = null;
    try {
        URL url = new URL("https://jsonplaceholder.typicode.com/users");
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) sb.append(line);
            result = sb.toString();
        } else {
            result = "Error " + conn.getResponseCode();
        }
    } catch (IOException e) {
        result = "Network error: " + e.getMessage();
    } finally {
        if (conn != null) conn.disconnect();
    }
    String finalResult = result;
    mainHandler.post(() -> textView.setText(finalResult));   // back on the UI thread
});

5.2 Retrofit (recommended library, by Square)

Retrofit turns an HTTP API into a Java interface; it builds requests, runs them on background threads and converts JSON to objects (with Gson or Moshi). It uses OkHttp underneath.

// build.gradle.kts (Module: app)
implementation("com.squareup.retrofit2:retrofit:2.11.0")
implementation("com.squareup.retrofit2:converter-gson:2.11.0")

// 1. model – User.java (field names match the JSON keys)
public class User {
    public int id;
    public String name, email, phone;
}

// 2. API interface – ApiService.java
public interface ApiService {
    @GET("users") Call<List<User>> getUsers();
    @GET("users/{id}") Call<User> getUser(@Path("id") int id);
    @GET("posts") Call<List<Post>> postsByUser(@Query("userId") int userId);
    @POST("posts") Call<Post> createPost(@Body Post post);
}

// 3. Retrofit instance – RetrofitClient.java
public class RetrofitClient {
    private static ApiService api;
    public static ApiService getApi() {
        if (api == null) {
            api = new Retrofit.Builder()
                    .baseUrl("https://jsonplaceholder.typicode.com/")   // must end with /
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                    .create(ApiService.class);
        }
        return api;
    }
}

// 4. call it – enqueue() runs the request on a background thread
//    and delivers the result on the main thread
RetrofitClient.getApi().getUsers().enqueue(new Callback<List<User>>() {
    @Override
    public void onResponse(Call<List<User>> call, Response<List<User>> response) {
        if (response.isSuccessful() && response.body() != null) {
            adapter.setUsers(response.body());
        }
    }
    @Override
    public void onFailure(Call<List<User>> call, Throwable t) {
        Toast.makeText(MainActivity.this, "Network error: " + t.getMessage(), Toast.LENGTH_LONG).show();
    }
});
Annotation Use
@GET, @POST, @PUT, @PATCH, @DELETE HTTP method + relative path
@Path("id") Replace {id} in the URL
@Query("userId") Add ?userId=1
@Body Send an object as JSON body
@Header, @Headers Add headers (e.g. Authorization)

Other HTTP clients: OkHttp (direct), Ktor client (Kotlin Multiplatform), Volley (older Google library). Images from URLs are loaded with Glide or Coil.

6. JSON parsing and networking best practices

JSON (JavaScript Object Notation) – lightweight text format of objects { "key": value } and arrays [ ... ]; values can be strings, numbers, booleans, null, objects or arrays.

[
  { "id": 1, "name": "Leanne Graham", "email": "Sincere@april.biz",
    "address": { "city": "Gwenborough" } }
]

Manual parsing with org.json:

try {
    JSONArray arr = new JSONArray(jsonText);
    for (int i = 0; i < arr.length(); i++) {
        JSONObject o = arr.getJSONObject(i);
        String name = o.getString("name");
        String city = o.getJSONObject("address").getString("city");
    }
} catch (JSONException e) {
    e.printStackTrace();
}

Automatic parsing: Gson/Moshi map JSON fields to the fields of a Java class (@SerializedName("full_name") if names differ). XML is an older alternative format (SOAP services).

Best practices

Short and long questions

1. Give the meaning of HTTP status codes 200, 201, 400, 401, 404 and 500.

Model answer

200 OK – success; 201 Created – resource created; 400 Bad Request – invalid request data; 401 Unauthorized – authentication required/failed; 404 Not Found – resource does not exist; 500 Internal Server Error – the server failed.

2. Name the HTTP methods used for CRUD operations.

Model answer

Create – POST; Read – GET; Update – PUT (replace) or PATCH (partial); Delete – DELETE.

3. Compare showing maps with an intent and with the Google Maps SDK.

Model answer

The intent hands the location to the Google Maps app: simple, no API key or billing, but the user leaves your app and you cannot customise the map. The Maps SDK embeds an interactive map in your UI with markers, polylines, camera control and events, but needs a Google Cloud API key with billing enabled and more code.

4. Write code to show a location on Google Maps using coordinates without an API key.

Model answer

startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("geo:33.6844,73.0479?q=33.6844,73.0479(Campus)"))) – this opens the Google Maps app with a labelled marker; no key or permission is needed.

5. List the steps to display a Google Map with a marker using the Maps SDK.

Model answer

(1) Create an API key for Maps SDK for Android in Google Cloud (restricted to package and SHA-1). (2) Add play-services-maps dependency and the key as com.google.android.geo.API_KEY meta-data. (3) Put a SupportMapFragment in the layout. (4) Call getMapAsync(this). (5) In onMapReady add a marker with MarkerOptions and move the camera with CameraUpdateFactory.newLatLngZoom.

6. What is JSON? Differentiate between JSONObject and JSONArray.

Model answer

JSON is a lightweight, human-readable text format for data exchange, made of key–value objects and ordered arrays. A JSONObject is an unordered set of key–value pairs in curly braces; a JSONArray is an ordered list of values in square brackets.

7. Why does Android throw NetworkOnMainThreadException?

Model answer

Network calls can take seconds; running them on the main (UI) thread would freeze the interface and cause ANR errors, so Android forbids it. Network code must run on a background thread, e.g. with an ExecutorService or libraries like Retrofit (enqueue).

8. What are web services? Explain how an Android app consumes a RESTful web service over HTTP. Describe HTTP methods, status codes, JSON, threading requirements, and give code using both HttpURLConnection and Retrofit.

Model answer

A web service is a server-side program exposing data and operations over the network; most modern services are RESTful – resources identified by URLs, manipulated with HTTP methods, exchanging JSON. The Android app is the client.

HTTP: request = method + URL + headers + body; response = status code + headers + body. Methods: GET (read), POST (create), PUT/PATCH (update), DELETE (delete). Status codes: 2xx success (200 OK, 201 Created), 4xx client errors (400, 401, 403, 404), 5xx server errors (500, 503). HTTPS is required by default (cleartext blocked since Android 9).

Requirements: INTERNET permission; no network on the main thread (NetworkOnMainThreadException) – use a background thread (ExecutorService) or Retrofit's enqueue(); handle timeouts, errors and offline state with progress and retry UI.

JSON: objects { "name": "Ali" } and arrays [ ... ]; parsed manually with JSONObject/JSONArray or automatically with Gson/Moshi into Java model classes.

HttpURLConnection: inside executor.execute(() -> { ... }): HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) { /* read conn.getInputStream() with a BufferedReader */ }; then parse and update the UI with handler.post(...) or runOnUiThread(...).

Retrofit: public class User { public int id; public String name; }; public interface ApiService { @GET("users") Call<List<User>> getUsers(); }; new Retrofit.Builder().baseUrl("https://jsonplaceholder.typicode.com/").addConverterFactory(GsonConverterFactory.create()).build().create(ApiService.class); call api.getUsers().enqueue(new Callback<List<User>>() { onResponse(...) {...} onFailure(...) {...} }) and show results in a RecyclerView. Annotations @Path, @Query, @Body and @Header customise requests; OkHttp works underneath and can add logging and caching.

Best practice: put networking in a Repository called by a ViewModel (MVVM), cache data, never embed secret keys, and use WorkManager for guaranteed background uploads.

9. Explain the different ways of displaying maps in an Android application. Describe in detail how to embed a Google Map with markers using the Maps SDK, including setup, code and common map features.

Model answer

Ways: (1) Map intents – ACTION_VIEW with geo: URIs (geo:lat,lng, ?z=zoom, ?q=lat,lng(Label), ?q=place+name), google.navigation: for navigation or a Google Maps URL; they open the Maps app and need no key. (2) Google Maps SDK for Android – an embedded, programmable map. (3) Open-source libraries such as osmdroid/MapLibre using OpenStreetMap data. (4) A web map inside a WebView.

Maps SDK setup: create a project in Google Cloud Console, enable Maps SDK for Android, enable billing, create an API key and restrict it to the app's package name and SHA-1 fingerprint; add the play-services-maps dependency; add meta-data android:name="com.google.android.geo.API_KEY" in the manifest (value supplied from local.properties via the Secrets Gradle Plugin); add a fragment with android:name="com.google.android.gms.maps.SupportMapFragment" to the layout.

Code: the activity implements OnMapReadyCallback; in onCreate: ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);; in onMapReady(GoogleMap map): LatLng campus = new LatLng(33.6844, 73.0479); map.addMarker(new MarkerOptions().position(campus).title("Campus").snippet("Main gate")); map.moveCamera(CameraUpdateFactory.newLatLngZoom(campus, 15f));.

Features: map types (normal, satellite, terrain, hybrid), UI settings (zoom controls, compass, my-location button with location permission), markers with custom icons and info windows, polylines (routes), polygons and circles (areas), click listeners for map and markers, animated camera movement, Geocoder for address ↔ coordinates, plus Places, Directions and Geofencing APIs.

10. What is Retrofit? List the steps to use it.

Model answer

Retrofit is a type-safe HTTP client library by Square that converts an HTTP API into a Java interface. Steps: add retrofit and a converter dependency; create data model classes; define an interface with annotated methods (@GET("users")); build a Retrofit instance with baseUrl and GsonConverterFactory and create the service; call enqueue() with a Callback and update the UI in onResponse, handling errors in onFailure.

This lesson ends with a quiz of 31 MCQs. Open the lesson on PrepOasis to take it and save your progress.

Previous: Week 11 Lab 11 – Open the SMS or Email Application with Prefilled Text · Next: Week 12 Lab 12 – Display Data from an API Using Retrofit and a RecyclerView

All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester