Android tutorial

Android Kotlin GraphQL Tutorial – apollo graphql 2022

Android Kotlin GraphQL Tutorial - apollo graphql
376views

We have all been using REST APIs since the very beginning of development. However, as data queries become more complicated as data grows larger, it’s turning out to be expensive in terms of computation time and processing.

What is GraphQL?

GraphQL is a query language used by the APIs that allow you to access your information. It’s a substitute for those REST APIs. It’s not limited to any one platform and can be used with any type of clients , such as Android, iOS or web. It acts as a buffer between the server and the client and allows you to query your data in an optimized manner. For more information regarding GraphQL History, watch this documentary:

Why is apollo graphql?

Some time ago, I attended an interview for a job and they asked me if I know anything about GraphQL and my response was no , as i had ever require it however, I spent the next two weeks researching and learning to integrate it into an Android application. Finally, I wanted to document what I learned in a simple article as well as open-source code available here GraphQL (github.com)

Prerequisites

You’re probably acquainted of Kotlin, Data Binding, View Binding, ViewModel, LiveData, Kotllin Coroutines and MVVM.

It is necessary to Install GraphQL — IntelliJ Marketplace (jetbrains.com) from Android Studio Marketplace for Plugins.

To gather the data, we’re using GraphiQL Explorer (spacex.land) in this instance.

Dependecies

begin by implementing dependencies into build.gradle

//apollo 
implementation "com.apollographql.apollo3:apollo-runtime:3.0.0" 
implementation 'com.apollographql.apollo:apollo-android-support:1.0.0' 
// lifecycle 
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0' 
//okhttp3 
implementation 'com.squareup.okhttp3:okhttp:4.9.3' 
implementation "com.squareup.okhttp3:logging-interceptor:4.8.1"

add Apollo plugin to build.gradle (must be added before kotlin plugin)

plugins { 
id 'com.android.application' 
id("com.apollographql.apollo3").version("3.0.0") 
id 'kotlin-android' 
}

 

at the last line of build.gradle at the end of build.gradle, you must specify the program that Kotlin file will be created.

apollo { 
packageName.set("com.aymen.graphql") 
}

.graphqlconfig

begin making graphql configurations by creating an .graphqlconfig file inside the your app’s directory app\src\main\graphql

include the graphql configuration and then put the graphql server URL in the default GraphQL Endpoint

{
    "name": "Untitled GraphQL Schema",
    "schemaPath": "schema.graphqls",
    "extensions": {
    "endpoints": {
    "Default GraphQL Endpoint": {
    "url": "http://api.spacex.land/graphql/",
    "headers": {
    "user-agent": "JS GraphQL"
},
    "introspect": true
}
}
}
}

schema.graphqls

Each GraphQL service has a list of data types that define the range of data that you can access through the service. After that, whenever queries come in, they are checked and interpreted in accordance with the schema.

Find out More regarding GraphQL Schemas by clicking here The Types of Schemas and Schemas | GraphQL

Make use of the Android Studio terminal to import schema.graphqls by following this command:

GraphQL operations

GraphQL includes three main operations:

  1. query to read data
  2. Modification to write data
  3. A subscription to automatically receive real-time information in real-time.

The most frequently used operations are those of queries and mutations You can imagine queries as a resemblance to an GET request, and mutations as POST, PUT and DELETE .

Subscription uses WebSocket to keep an open connection to the GraphQL server . This allows your server to add updates to the subscription’s results as time passes

Android Kotlin GraphQL Tutorial - apollo graphql

Apollo Client Instance

To use GraphQL in an Android application we’ll need to make use of an application called the Apollo Library which is an extremely typed client that creates Java as well as Kotlin model from GraphQL queries. To begin, we will need to obtain access to an ApolloClient instance.

private var BASE_URL = "http://api.spacex.land/graphql/"

private val httpClient : OkHttpClient by lazy {
    val httpLoggingInterceptor = HttpLoggingInterceptor()
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
    OkHttpClient.Builder()
        .callTimeout(60, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .addInterceptor(httpLoggingInterceptor).build()
}

fun get(): ApolloClient {
    return ApolloClient.Builder()
        .serverUrl(BASE_URL)
        .okHttpClient(httpClient)
        .build()
}

get exceptions

to stay away from bugs and cruchs, let’s catch apollo exceptions

val response = try {
    client.query(UsersListQuery(10)).execute()
}catch (e : ApolloException){
    return@launchWhenResumed
}

use mutations

use apollo client mutation to insert, update or delete data:

val result = try {
    client.mutation(InsertUserMutation(
        binding.etName.text.toString(),
        binding.etRocket.text.toString(),
        binding.etTwitter.text.toString()
    )).execute()
}catch (e: ApolloException){
    return@launchWhenResumed
}
...............
val result = try {
    client.mutation(UpdateUserMutation(
        id,
        binding.etName.text.toString(),
        binding.etRocket.text.toString(),
        binding.etTwitter.text.toString()
    )).execute()
}catch (e: ApolloException){
    return@launchWhenResumed
}
...............
val result = try {
    client.mutation(DeleteUserMutation(id)).execute()
}catch (e: ApolloException){
    return@launchWhenResumed
}

Example Result

when running the application, we get:

  • MainActivity with a RecyclerView with list of users
  • FabActionButton to insert new user
  • when clic on RecyclerView item, get user profile to update or delete on UserTreatmentActivity

Source Code on GitHub ClickHere

 

Read More Tutorial