Camposha
  • Android
    • Introduction
    • Components
    • Communication
    • DateTime
    • FileSystem
    • HTTP
    • Local Database
    • Permissions
    • Scheduler
    • System
    • Widgets
    • Threading
    • Animation and Motion
    • Hardware and Sensors
  • C#
  • Flutter
  • Java
  • Javascript
  • Python
Friday, January 15, 2021
No Result
View All Result
  • Login
  • Register
Buy Projects
  • Android
    • Introduction
    • Components
    • Communication
    • DateTime
    • FileSystem
    • HTTP
    • Local Database
    • Permissions
    • Scheduler
    • System
    • Widgets
    • Threading
    • Animation and Motion
    • Hardware and Sensors
  • C#
  • Flutter
  • Java
  • Javascript
  • Python
No Result
View All Result
Camposha
No Result
View All Result
Home Android Android HTTP

Retrofit

Oclemy by Oclemy
1 month ago
in Android HTTP
A A
4k
VIEWS
Share on FacebookShare on Twitter

Android Retrofit Tutorial and Examples.

What is Retrofit? Well Retrofit is a Typesafe HTTP Client first created by Square Inc.

Retrofit’s role is to turn your HTTP API into a Java interface:

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

In this class we will look at Retrofit and Retrofit Examples with respect to android development. We will see how we can use it to talk to webservices via HTTP in an easy manner.

What are the Requirements for Retrofit?

Retrofit has very generous requirements:

  1. Java 7 and above.
  2. Android 2.3 and above.

How do I Install Retrofit?

Retrofit is a third party HTTP Client library android and java. Hence it needs to be installed into your project.

If you were looking for a networking class that is standard and included in android framework then check HttpURLConnection.

Otherwise Retrofit can be installed in three ways:

1. As a jar.

Basically you download the Retrofit jar and add it to your android studio as a jar library.

For example I used retrofit 2.4.0 which can be downloaded from here.

Otherwise you can check the latest version here.

2. Via maven

Maven, also known as, Apache Maven is a build automation tool used primarily for Java projects.

This gives it two main roles:

  1. Describing how a project is built.
  2. Describing the project’s dependencies.

Well we can describe Retrofit as our dependency in a java project.

<dependency>
  <groupId>com.squareup.retrofit2</groupId>
  <artifactId>retrofit</artifactId>
  <version>2.4.0</version>
</dependency>

3. Via Gradle

Gradle is a build system used by android studio.

If you are creating an android project, chances are that you will use this method to install retrofit. This is because you are likely to use Android Studio as it is the official development IDE for android. And android studio utilizes the gradle build system.

In that case you will need to go over to your app level build.gradle and add the following statement in your dependencies DSL:

implementation 'com.squareup.retrofit2:retrofit:2.4.0'

Common Retrofit Interfaces,Classes and Methods.

1. Call

This is a Retrofit interface that represents an invocation of a Retrofit method that sends a request to a webserver and returns a response. As the name suggests it basically represents a HTTP Call you make.

Each call will then yield its own HTTP request and response pair. You able to make multiple calls with the same parameters. However you use clone to achieve that. You can use this to implement polling or to retry a failed call.

When making you HTTP calls, you may make them synchronously or asynchronously. To make synchronous calls you use the execute() method. However to make asynchronous calls you use the enqueue() method.

If you want to cancel any call you use the cancel() method.

Here’s it’s definition:

public interface Call<T> extends Cloneable

Take note that in this case T represents the type of a successful response body.

2. enqueue()

This is a method that belongs to the Call<T> interface. We talked about that interface representing a HTTP Call you make.

And normally you can make either synchronous or asynchronous call or request. If you want to make an asynchronous call you use this method.

Here’s it’s definition:

public abstract void enqueue(retrofit2.Callback<T> callback)

This method will then asynchronously send your request and notify callback of its response in case an error occurred talking to the server, creating the request, or processing the response.

Here’s a simple usage example:

        Call<List<Spacecraft>> call = myAPIService.getSpacecrafts();
        call.enqueue(new Callback<List<Spacecraft>>() {

            @Override
            public void onResponse(Call<List<Spacecraft>> call, Response<List<Spacecraft>> response) {
                myProgressBar.setVisibility(View.GONE);
                populateRecyclerView(response.body());
            }
            @Override
            public void onFailure(Call<List<Spacecraft>> call, Throwable throwable) {
                myProgressBar.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

3. Callback

This is an interface defining methods responsible for communicating responses from a server or offline requests.

Here’s its definition:

public interface Callback<T>

T in the above represents a successful response body type.

Normally one a single method gets called in response to a given request. That method will be executed using the Retrofit callback executor. If you don’t specify any then the following defaults are used:

  1. Android: Callbacks are executed on the application’s main (UI) thread.
  2. JVM: Callbacks are executed on the background thread which performed the request.

Here’s example usage:

new Callback<List<Spacecraft>>() {

            @Override
            public void onResponse(Call<List<Spacecraft>> call, Response<List<Spacecraft>> response) {
                myProgressBar.setVisibility(View.GONE);
                populateRecyclerView(response.body());
            }
            @Override
            public void onFailure(Call<List<Spacecraft>> call, Throwable throwable) {
                myProgressBar.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

4. Retrofit

This is a class that is responsible for adapting a Java interface to HTTP calls by using annotations on the declared methods to define how requests are made.

Here’s its definition

public final class Retrofit extends Object

To use it you will need to create it’s instance. However you do that using the builder and pass your interface to create to generate an implementation.
For example:

   Retrofit retrofit = new Retrofit.Builder()
       .baseUrl("https://api.example.com/")
       .addConverterFactory(GsonConverterFactory.create())
       .build();

   MyApi api = retrofit.create(MyApi.class);
   Response<User> user = api.getUser().execute();

Or I can create a simple factory class to return me it’s instances:

    static class RetrofitClientInstance {

        private static Retrofit retrofit;
        private static final String BASE_URL = "https://raw.githubusercontent.com/";

        public static Retrofit getRetrofitInstance() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }

Then I use that class this way:

        MyAPIService myAPIService = RetrofitClientInstance.getRetrofitInstance().create(MyAPIService.class);
Tags: Android Retrofit Examples
Share16Tweet10Send
Oclemy

Oclemy

When I was a 2nd year Software Engineering student, I buillt a now defunct online tool called Camposha(from Campus Share) using my then favorite language C#(ASP.NET) to compete OLX in my country(Kenya). The idea was to target campus students in Kenya. I got a few hundred signups but competing OLX proved too daunting. I decided to focus on my studies, learning other languages like Java,Python,Kotlin etc while meanwhile publishing tutorials at my YouTube Channel ProgrammingWizards TV which led to this site(camposha.info). Say hello or post me a suggestion: oclemmi@gmail.com . Follow me below; Github , and on my channel: ProgrammingWizards TV

Get Free Projects

Featured Projects

  • Become a Premium Member $30.00
  • CoronaVirus News App - Kotlin+MVVM+Firebase+Cloud Storage+Authentication+PageViews $12.00 $4.99
  • Largest Stars App - Kotlin+MySQL+MVVM+Retrofit2 Multipart+Data Binding+Disk Caching(2 Apps-Kotlin,Java) $12.00 $4.99
  • Alien Planets App - MVVM+Firebase+Cloud Storage(2 Apps-Kotlin,Java) $10.00 $4.99
  • Retrofit MySQL Multipart Images CRUD - UPLOAD DOWNLOAD UPDATE DELETE Full $10.00 $3.99

My Udemy Courses

Android MySQL Retrofit2 Multipart CRUD,Search,Pagination€19.99€12.99
Beginner Friendly Full Offline Android Apps Creation(Room)€19.99€12.99
Android Firebase MVVM Jetpack - Many Offline-First CRUD Apps€19.99€12.99
Kotlin Firebase CRUD,Cloud Storage,MVVM (Works even Offline)€19.99€12.99

Popular

  • Flutter PHP MySQL – Fill ListView with Images and Text

    45 shares
    Share 18 Tweet 11
  • Kotlin Android SQLite Simple CRUD – INSERT SELECT UPDATE DELETE

    45 shares
    Share 18 Tweet 11
  • Flutter SearchView Examples – ListView Search/Filter

    45 shares
    Share 18 Tweet 11
  • Kotlin Android Capture From Camera or Pick Image

    44 shares
    Share 18 Tweet 11
  • Android MySQL – Insert From EditText,CheckBox,Spinner – Part 4 [PHP Code]

    43 shares
    Share 17 Tweet 11
  • Trending
  • Comments
  • Latest

Flutter PHP MySQL – Fill ListView with Images and Text

December 19, 2020

Kotlin Android SQLite Simple CRUD – INSERT SELECT UPDATE DELETE

December 19, 2020
Flutter AppBar SearchView

Flutter SearchView Examples – ListView Search/Filter

December 19, 2020
Kotlin Android Capture From Camera or Pick Image

Kotlin Android Capture From Camera or Pick Image

December 19, 2020
CoronaVirus News App – Kotlin + MVVM + Firebase + Cloud Storage + Authentication+PageViews Count(Works even Offline)

CoronaVirus News App – Kotlin + MVVM + Firebase + Cloud Storage + Authentication+PageViews Count(Works even Offline)

10

Android Firebase RecyclerView MasterDetail CRUD Images Text – Upload, READ, DELETE

5

Android Retrofit – JSON ListView Images and Text

3

Framework7 Cordova – Compile App to APK and Install in Android Device/Emulator

3

Android Shared Element Transition Examples

December 27, 2020

Best Android Swipe Cards Libraries and Examples

December 27, 2020
Retrofit

Retrofit

December 19, 2020
Fast Networking Library

Fast Networking Library

December 19, 2020
  • Android
  • C#
  • Flutter
  • Java
  • Javascript
  • Python

Copyright © 2020 Camposha All Rights Reserved.

No Result
View All Result
  • Account
  • Activate
  • Activity
  • Become a Teacher
  • Become a Teacher
  • Become a Teacher
  • Become instructor
  • Blog
  • Blog
  • Cancel Payment
  • Cancel Payment
  • Cart
  • Change Password
  • Change Password
  • Checkout
  • Checkout
  • Checkout
  • Contact
  • Contact
  • Contact Us
  • Content restricted
  • Course Checkout
  • Dashboard
  • Edit Profile
  • Edit Profile
  • FAQs
  • Forgot Password
  • Forgot Password
  • Guest
  • Guest
  • Home
  • Home
  • Home Light
  • Instructor Dashboard
  • Instructor Registration
  • IUMP – Account Page
  • IUMP – Default Redirect Page
  • IUMP – Login
  • IUMP – LogOut
  • IUMP – Register
  • IUMP – Reset Password
  • IUMP – TOS Page
  • IUMP – Visitor Inside User Page
  • List courses
  • List wish list
  • Login
  • Login
  • Maintenance
  • Members
  • Membership Account
    • Membership Billing
    • Membership Cancel
    • Membership Checkout
    • Membership Confirmation
    • Membership Invoice
    • Membership Levels
  • Membership Account
    • Membership Billing
    • Membership Cancel
    • Membership Checkout
    • Membership Confirmation
    • Membership Invoice
    • Membership Levels
  • Membership Plans
  • My Account
  • OnePage Documentation
  • Portfolio Grid
  • Portfolio Masonry
  • Portfolio Multigrid
  • Privacy Policy
  • Products
  • Profile
  • Profile
  • Profile
  • Projects
  • Register
  • Register
  • Register
  • Register
  • Sample Page
  • Shop
  • Sign in
  • Sign up
  • Student profile
  • Student Registration
  • Thank You
  • Thank You

Copyright © 2020 Camposha All Rights Reserved.

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms below to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Login

Forgot Password?

Create a new account

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.