How to connect to internet using Retrofit, Moshi, Livedata in Android 11

How to connect to internet using Retrofit, Moshi, Livedata in Android 11

Here we are going to create a network connection using the Glide, Retrofit, Moshi custom library with LiveData and Coroutines. So to begin with create a project with name <Any Name> or download the starter library(InternetStarter) and change the name.

Step 1: Update the dependancies.

Better to avoid changing these dependencies. Your project might not work if any items are modified.

build.gradle(:project name)

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext{
multidex_version = "2.0.1"
kotlin_version = "1.4.32"
version_gradle = "4.1.2"
version_core = '1.6.0'
version_glide = '4.12.0'
version_kotlin_coroutines = "1.3.7"
version_lifecycle = '2.3.1'
version_moshi = '1.11.0'
version_navigation = "1.0.0"
version_retrofit = "2.9.0"
version_retrofit_coroutines_adapter = "0.9.2"
version_recyclerview = '1.2.1'
version_constraint_layout= "2.1.0-beta02"
}
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:$version_navigation"
}
}

allprojects {
repositories {
google()
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

build.gradle(:app)

plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'androidx.navigation.safeargs'
}

android {
compileSdkVersion 30


buildFeatures{
dataBinding true
}

defaultConfig {
applicationId "com.blogspot.howtouseinternet"
minSdkVersion 19
targetSdkVersion 30
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
}
defaultConfig{
multiDexEnabled = true
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

//Material Ui
implementation 'com.google.android.material:material:1.4.0'
// Kotlin
// implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$version_kotlin"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

// Constraint Layout
implementation "androidx.constraintlayout:constraintlayout:$version_constraint_layout"

// ViewModel and LiveData
// implementation "androidx.lifecycle:lifecycle-extensions:$version_lifecycle_extensions"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$version_lifecycle"

// Navigation
implementation "android.arch.navigation:navigation-fragment-ktx:$version_navigation"
implementation "android.arch.navigation:navigation-ui-ktx:$version_navigation"

// Core with Ktx
implementation "androidx.core:core-ktx:$version_core"

// Moshi
implementation "com.squareup.moshi:moshi:$version_moshi"
implementation "com.squareup.moshi:moshi-kotlin:$version_moshi"


// Retrofit
implementation "com.squareup.retrofit2:retrofit:$version_retrofit"
implementation "com.squareup.retrofit2:converter-scalars:$version_retrofit"

// Retrofit with Moshi Converter
implementation "com.squareup.retrofit2:converter-moshi:$version_retrofit"

// Coroutines - Deprecated - No more required
// implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$version_kotlin_coroutines"
// implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$version_kotlin_coroutines"

// Retrofit Coroutines Support - Deprecated - No more required
// implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:$version_retrofit_coroutines_adapter"

// Glide
implementation "com.github.bumptech.glide:glide:$version_glide"

// RecyclerView
implementation "androidx.recyclerview:recyclerview:$version_recyclerview"
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'

//Multidex
implementation "androidx.multidex:multidex:$multidex_version"
}

Step 2: Create a Fragment with ViewModel to test the dependancies 

  • Create a package inside main project with name home. (Right Click -> new -> package)
  • Right click the package and select New -> Fragment -> Fragment + View Model
  • Let the Fragment be created
    Now Fragment can't run on its own. It needs an activity and navigation host. 
  • Add the fragment in the activity_main.xml
  • Use the default navigation host. 
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
    Now this fragment needs a nav graph in order to switch between fragments. Create a navigation graph        by using the following steps.
  • Right click on the res folder in Project Tree.
  • Click new -> Android Resource File 
  • Select resource type : Navigation , name : nav_graph
  • Add the file 















    At the end of this step a nav_graph file will be created. Open the file. 
  • Click the Add a destination button and select the MainFragment
Now go back to the main_activity and add the navGraph

Complete Starter can be downloaded here : https://github.com/PijushManna/InternetStarter

Step 3: Manage network requests

Add a network project. Inside the project maintain the API requests.
NetworkApi.kt : 
package com.blogspot.howtouseinternet.network

import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.http.GET

private const val BASE_URL = "https://mars.udacity.com/"

private val retrofit = Retrofit.Builder()
.addConverterFactory(ScalarsConverterFactory.create())
.baseUrl(BASE_URL)
.build()

interface NetworkApis{
@GET("realestate")
fun getProperties():
Call<String>
}

object MarsApi{
val marsProperties : NetworkApis by lazy {
retrofit.create(NetworkApis::class.java)
}
}
 

Comments