Android Development

Android Updates Home Contact

Android WebServices

Webservices allow Android applications to communicate with remote servers to send and receive data. They are essential for accessing cloud storage, backend databases, or integrating with external services. Common webservice types include REST APIs, GraphQL, SOAP, Firebase APIs, and WebSockets.

Why Use WebServices in Android?

Mobile apps often need to exchange data with servers — whether for user authentication, data syncing, or retrieving live content. Webservices provide a platform-agnostic way to achieve this, usually over HTTP or HTTPS protocols.

Popular Webservice Options
  • REST APIs (JSON/XML over HTTP)
  • GraphQL APIs (Structured queries over HTTP)
  • SOAP (XML-based protocol, rarely used in modern mobile)
  • WebSockets (for real-time two-way communication)
  • Firebase or Google Cloud APIs

JSON and XML Comparison

  • Both JSON and XML are used for structured data exchange between client and server.
  • JSON supports nested objects and arrays and is easier to parse and more lightweight.
  • XML is verbose and supports attributes, namespaces, and schemas, but is slower to process.

REST WebService

HTTP Methods in REST
  • GET – Retrieve data
  • POST – Submit or create data
  • PUT – Update an existing resource
  • DELETE – Remove a resource
Data Formats

REST APIs typically use JSON for data exchange due to its simplicity and performance. XML is also supported by some services.

Steps to Receive Data Using REST

  1. Determine the API endpoint URL.
  2. Initiate an HTTP request using GET or POST with optional parameters.
  3. Receive the server response in JSON or XML format.
  4. Parse the data and update the UI accordingly.

Steps to Send Data to Server

  1. Convert data into JSON or XML format.
  2. Make a POST, PUT, or DELETE request with the data as payload.
  3. Read and handle the server's response (e.g., success message, error).

GraphQL WebService

GraphQL is a query language for APIs and a runtime for executing those queries. Unlike REST, which exposes multiple endpoints, GraphQL exposes a single endpoint and allows requesting exactly the data needed.

Key Features
  • Single endpoint for all data queries and mutations
  • Client controls the structure of the response
  • Reduces over-fetching and under-fetching
GraphQL Query Example
{
  user(id: 5) {
    name
    email
    profilePicture
  }
}
  
Where GraphQL is Suitable
  • Mobile apps with dynamic data requirements
  • Multiple views or components needing different data shapes
  • When reducing payload size is critical

REST vs GraphQL for Android

Aspect REST GraphQL
Endpoint Structure Multiple endpoints for each resource Single endpoint for all queries
Response Size Often contains unnecessary data Returns only requested fields
Flexibility Fixed data structure per endpoint Custom structure per request
Caching Simpler HTTP-level caching More complex; requires custom logic
Learning Curve Simpler to start Requires learning GraphQL syntax

WebService Example Using HttpURLConnection

This example demonstrates how to make a basic HTTP GET request using HttpURLConnection on a background thread to fetch data from a web service. The result is then displayed in a TextView on the main thread.


public class MainActivity extends AppCompatActivity {

    private TextView textViewResult;
    private final Handler handler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textViewResult = findViewById(R.id.text_view_result);

        new Thread(() -> {
            String result = fetchData();
            handler.post(() -> {
                if (result != null) {
                    textViewResult.setText(result);
                } else {
                    textViewResult.setText("Error occurred");
                }
            });
        }).start();
    }

    private String fetchData() {
        String result = null;
        try {
            URL url = new URL("https://www.zyasin.com/jsonexample2.json");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                reader.close();
                inputStream.close();
                result = stringBuilder.toString();
            }
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}