Android SharedPreferences Tutorial and Example

Parsing JSON in Android with Gson and Volley

Android applications frequently receive data from an API as JSON, then convert that payload into objects that the interface can display. Gson performs this deserialization, while Volley manages the HTTP request, network callback, and delivery of the server response. Together, they provide a compact data layer for Android projects.

Connection quality can change during a normal day in Australia. A commuter in Sydney, Melbourne, or Brisbane may move between mobile data, suburban rail, and free café Wi-Fi. Applications should therefore handle timeouts and intermittent connectivity without blocking the main thread.

The Australian app market includes Google Play releases, regional businesses, and loyalty services from retailers such as Woolworths and Coles. Android developers must account for users on different devices, network speeds, and screen sizes while keeping data requests efficient and dependable.

Personal information also requires care. Eligible organisations, generally those with an annual turnover of $3 million or more, must comply with the Privacy Act 1988 and the Australian Privacy Principles. APIs should collect and expose only the data the application genuinely needs, with suitable security and retention controls.

Set up the project

Add Gson and Volley to the module-level Gradle file. These dependencies provide the JSON mapper and networking components used throughout the example.

dependencies {
    implementation 'com.google.code.gson:gson:2.11.0'
    implementation 'com.android.volley:volley:1.2.1'
}

Volley needs internet access. Add the permission to the application manifest; it is a normal permission and does not require a runtime prompt from the user.

<uses-permission android:name="android.permission.INTERNET" />

Use an HTTPS API endpoint and check its response structure before creating the Java classes. The examples here expect a JSON object containing a status field and an items array.

Model the JSON response

Gson maps JSON properties to Java fields through reflection. The @SerializedName annotation connects a field to its exact property name, which is useful when an API uses names such as published_at.

public class Article {
    @SerializedName("id")
    public int id;

    @SerializedName("title")
    public String title;

    @SerializedName("summary")
    public String summary;

    @SerializedName("published_at")
    public String publishedAt;
}

public class ArticleFeed {
    public String status;
    public List<Article> items;
}

Field names do not always match the payload, but an annotation can handle that variation. Gson ignores unknown properties by default, although missing fields receive their default Java values. Null checks remain important because an absent string or list is represented differently from an empty string or empty collection.

Build a Volley request

A JsonObjectRequest performs the GET request and provides separate callbacks for a successful response and a network failure. The request body is null because GET requests normally send their parameters through the URL.

JsonObjectRequest request = new JsonObjectRequest(
    Request.Method.GET,
    endpoint,
    null,
    response -> handleResponse(response),
    error -> handleError(error)
);

request.setTag(this);
requestQueue.add(request);

Initialise the RequestQueue once, normally in an Activity, Application, or repository. For an Activity, cancel tagged requests when it is destroyed so that an obsolete screen does not update a replacement screen. An application-scoped queue is more suitable when several screens share the same service.

GET requests can safely use Volley’s retry policy when the server supports repeated reads. Avoid automatic retries for operations that create, modify, or delete data, since those operations may not be idempotent.

Parse successful response data

Volley delivers the response body as a string on the main thread. Pass that string to Gson and request the class that represents the root JSON object.

private void handleResponse(String response) {
    try {
        Gson gson = new Gson();
        ArticleFeed feed = gson.fromJson(response, ArticleFeed.class);

        if (feed == null || feed.items == null) {
            showEmptyState();
            return;
        }

        showArticles(feed.items);
    } catch (JsonSyntaxException exception) {
        showErrorMessage("The server returned unreadable data.");
    }
}

The mapper does not need a manual conversion for every field. Once fromJson returns an ArticleFeed, its nested Article objects are ready for a RecyclerView adapter. When a parsed row offers secondary commands, this contextual menu guide demonstrates a familiar Android interaction pattern.

Handle errors and empty states

Volley reports transport failures, timeouts, invalid HTTP responses, and server errors through VolleyError. The response status can distinguish a missing endpoint from a temporary service problem.

private void handleError(VolleyError error) {
    int status = error.networkResponse == null
        ? 0
        : error.networkResponse.statusCode;

    if (status == 404) {
        showErrorMessage("These articles are no longer available.");
    } else if (status >= 500) {
        showErrorMessage("The service is temporarily unavailable.");
    } else {
        showErrorMessage("Check your connection and try again.");
    }
}

Keep the raw exception out of the user interface, but record enough technical information in application logs to diagnose the failure. A retry button belongs beside the affected content rather than replacing a list that is already usable. Caching a successful GET response briefly can also help commuters moving between paid mobile data and untrusted public Wi-Fi, provided cached information is appropriate to store.

Choose a parsing and networking boundary

Gson and Volley solve adjacent problems rather than competing with one another. Their responsibilities become clearer when they are compared directly.

Concern Gson Volley
Primary role Converts JSON text into Java objects Manages HTTP requests and callbacks
Main input A JSON string or reader A URL, method, headers, and optional body
Common output Mapped fields, lists, and nested objects Response strings and error callbacks
Failure handling May throw a JSON syntax exception Reports network and HTTP failures
Typical use Object mapping and deserialization Request queues, retries, caching, and transport

Volley’s cache can respect standard HTTP caching headers, but developers must still decide which responses are safe to retain. Avoid placing authentication tokens or sensitive personal information in shared storage, and clear user-specific cached data when an account signs out.

Test the data layer with an empty array, a missing field, a changed property name, malformed JSON, and different HTTP status codes. This separation keeps transport concerns in Volley, mapping concerns in Gson, and rendering decisions in the Activity or Fragment. It also makes each component easier to understand, maintain, and verify across Android devices used throughout Australia.