Retrofit android example github
This tutorial/lab aims to provide hands-on experience of building an Android app that retrieves and displays data with REST API. We will first introduce how to:
- Use Retrofit to retrieve data of single movie from The Movie DB and display the data in an Activity.
- Use RecyclerView to display a list of textual data
You will then be asked to modify the provided classes to show a list of top-rated movies, as illustrated below.
This tutorial assumes that you know some Android basics such as Activities and layouts, and able to create a simple Android app with Android Studio.
Running the Source Code
To run the tutorial code, you need an API key from The Movie DB. Follow this instruction to create an account on The Movie DB and get your API key.
git clone this project, and import it with Android Studio. Replace «YOUR_API_KEY» in MainActivity.java with your API key. Run the app on an emulator (it is tested on Android 8.1 (API Level 27), but should work fine with API 23+)
Once the app is running, you will see movie data displayed on the main screen. The «Program List» button leads you to ProgramListActivity that displays a list of strings using RecyclerView . The «Movie List» button leads you to MovieListActivity that you are asked to finish in this lab.
Using Retrofit to Retrieve and Display Data with REST API
The required data of single movie can be retrieved by the following REST API:
The fields we need in this tutorial are: title , release_date , vote_average , overview , and poster_path .
First, create a Movie class to hold the data returned by the API:
Next, create an interface class, MovieApiService , to bridge HTTP API:
Now you can generate a Retrofit object that creates the implementation of MovieApiService in MainActivity . Each Call from the created MovieApiService makes an HTTP request to the remote webserver.
Call can be executed synchronously or asynchronously. However, a synchronous call means that the main/UI thread will be completely blocked until the operation completes—this is not recommended and not allowed in Android. Therefore, we make an asynchronous request with call.enqueue() as follows:
This way, Android executes the request in a separate thread and does not block the main/UI thread.
Using RecyclerView to Display a List of Strings
The RecyclerView widget is a more advanced and flexible version of ListView . It has several advantages such as the ability to dynamically create list items and to cache and reuse the scrolled-out items (check here for details). However, it is a little bit complex to use. Here are the required steps to use RecyclerView :
Add a RecyclerView widget to the layout file of the Activity ( activity_program_list.xml )
Create an additional layout file ( program_row.xml ) to display single item in the list
Create an Adapter class ( ProgramListAdapter.java ) that extends RecyclerView.Adapter to feed your data to the list. In the Adapter class, we need to:
- Declare a ViewHolder class that extends RecyclerView.ViewHolder , responsible for displaying single item with a view.
- Overwrite three built-in methods:
- onCreateViewHolder() (for creating a new ViewHolder with its corresponding layout)
- onBindViewHolder() (for binding the data of single item to a view)
- getItemCount() (for reporting the size of your dataset).
- In ProgramListActivity , obtain a handle to the RecyclerView object, connect it to a layout manager, and attach an adapter for the data to be displayed.
You have learned how to use Retrofit and RecyclerView. Now it is your turn to finish the following lab.
Lab: Complete the Provided Classes to Display Top-rated Movies
This lab asks you to display top-rated movies in MovieListActivity . The data can be retrieved from here:
You have to display the 20 movies in the results returned by the above REST API.
All required class and layout files are provided in the project. Specifically, you have to modify the following four files:
- MovieApiService.java : add one more method for the above API
- TopRatedResponse.java : implement it as the Movie class
- MovieListAdapter.java : implement it as the ProgramListAdadpter class
- MovieListActivity.java : implement it as the ProgramListActivity class
Besides, you need to check movie_row.xml to know where to place the data when you modify MovieListAdapter . Note that, movie_row.xml contains a ImageView field for displaying the poster of a movie. The poster image can be retrieved with the following URL (refer to here):
You also need to use Picasso to download the poster image from the above URL and put it into the ImageView in your MovieListAdapter .
Источник
Retrofit android example github
A type-safe HTTP client for Android and Java
Retrofit turns your HTTP API into a Java interface.
The Retrofit class generates an implementation of the GitHubService interface.
Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.
Use annotations to describe the HTTP request:
- URL parameter replacement and query parameter support
- Object conversion to request body (e.g., JSON, protocol buffers)
- Multipart request body and file upload
Annotations on the interface methods and its parameters indicate how a request will be handled.
Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: GET , POST , PUT , DELETE , and HEAD . The relative URL of the resource is specified in the annotation.
You can also specify query parameters in the URL.
A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by < and >. A corresponding parameter must be annotated with @Path using the same string.
Query parameters can also be added.
For complex query parameter combinations a Map can be used.
An object can be specified for use as an HTTP request body with the @Body annotation.
The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBody can be used.
FORM ENCODED AND MULTIPART
Methods can also be declared to send form-encoded and multipart data.
Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with @Field containing the name and the object providing the value.
Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation.
Multipart parts use one of Retrofit’s converters or they can implement RequestBody to handle their own serialization.
You can set static headers for a method using the @Headers annotation.
Note that headers do not overwrite each other. All headers with the same name will be included in the request.
A request Header can be updated dynamically using the @Header annotation. A corresponding parameter must be provided to the @Header . If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.
Similar to query parameters, for complex header combinations, a Map can be used.
Headers that need to be added to every request can be specified using an OkHttp interceptor .
SYNCHRONOUS VS. ASYNCHRONOUS
Call instances can be executed either synchronously or asynchronously. Each instance can only be used once, but calling clone() will create a new instance that can be used.
On Android, callbacks will be executed on the main thread. On the JVM, callbacks will happen on the same thread that executed the HTTP request.
Retrofit is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.
By default, Retrofit can only deserialize HTTP bodies into OkHttp’s ResponseBody type and it can only accept its RequestBody type for @Body .
Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.
- Gson: com.squareup.retrofit2:converter-gson
- Jackson: com.squareup.retrofit2:converter-jackson
- Moshi: com.squareup.retrofit2:converter-moshi
- Protobuf: com.squareup.retrofit2:converter-protobuf
- Wire: com.squareup.retrofit2:converter-wire
- Simple XML: com.squareup.retrofit2:converter-simplexml
- Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
Here’s an example of using the GsonConverterFactory class to generate an implementation of the GitHubService interface which uses Gson for its deserialization.
If you need to communicate with an API that uses a content-format that Retrofit does not support out of the box (e.g. YAML, txt, custom format) or you wish to use a different library to implement an existing format, you can easily create your own converter. Create a class that extends the Converter.Factory class and pass in an instance when building your adapter.
The source code to the Retrofit, its samples, and this website is available on GitHub.
Retrofit requires at minimum Java 7 or Android 2.3.
Download the latest JAR or grab from Maven central at the coordinates com.squareup.retrofit2:retrofit:2.6.2 .
Snapshots of the development version are available in Sonatype’s snapshots repository.
Retrofit requires at minimum Java 8+ or Android API 21+.
If you are using R8 the shrinking and obfuscation rules are included automatically.
ProGuard users must manually add the options from this file. (Note: You might also need rules for OkHttp and Okio which are dependencies of this library)
About
Android application using retrofit library for making http requests
Источник
Retrofit android example github
Android’s MVVM Architecture in Kotlin ft. Retrofit
This is an example to demonstrate MVVM Architecture in Kotlin with Retrofit in Android.
This example will demonstrate the working of MVVM using Live data and Retrofit in Kotlin. Just follow the steps and you will be able to try out the same in your Android Studio as well.
So Let’s Get Started:
- What is MVVM, LiveData, ViewModel, Model, Repository?
- Implementation Step-by-Step
- Conclusion
1. What is MVVM, LiveData, ViewModel, Model, Repository?
Answer: Let’s see what are the important concepts in MVVM.
MVVM: Model-View-ViewModel (i.e MVVM) is a template of a client application architecture, proposed by John Gossman as an alternative to MVC and MVP patterns when using Data Binding technology. Its concept is to separate data presentation logic from business logic by moving it into particular class for a clear distinction.
LiveData: LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
Advantages of Using LiveData:
Ensures your UI matches your data state: LiveData follows the observer pattern. LiveData notifies Observer objects when the lifecycle state changes. You can consolidate your code to update the UI in these Observer objects. Instead of updating the UI every time the app data changes, your observer can update the UI every time there’s a change.
No memory leaks: Observers are bound to Lifecycle objects and clean up after themselves when their associated lifecycle is destroyed.
No crashes due to stopped activities: If the observer’s lifecycle is inactive, such as in the case of an activity in the back stack, then it doesn’t receive any LiveData events.
No more manual lifecycle handling: UI components just observe relevant data and don’t stop or resume observation. LiveData automatically manages all of this since it’s aware of the relevant lifecycle status changes while observing.
Always up to date data: If a lifecycle becomes inactive, it receives the latest data upon becoming active again. For example, an activity that was in the background receives the latest data right after it returns to the foreground.
Proper configuration changes: If an activity or fragment is recreated due to a configuration change, like device rotation, it immediately receives the latest available data.
Sharing resources: You can extend a LiveData object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveData object connects to the system service once, and then any observer that needs the resource can just watch the LiveData object. For more information, see Extend LiveData.
ViewModel: The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.
Model: Model can be applied to a class which represents your application’s data model, and will cause instances of the class to become observable, such that a read of a property of an instance of this class during the invocation of a composable function will cause that component to be «subscribed» to mutations of that instance. Composable functions which directly or indirectly read properties of the model class, the composables will be recomposed whenever any properties of the the model are written to.
Repository: Repository modules handle data operations. They provide a clean API so that the rest of the app can retrieve this data easily. They know where to get the data from and what API calls to make when data is updated. You can consider repositories to be mediators between different data sources, such as persistent models, web services, and caches.
2. Implementation Step-by-Step?
As said before, this example uses MVVM with Retrofit using Kotlin. Let’s dive into the steps of doing it.
Step1: Add dependencies to your project:
Step2: Create different folders that relate to MVVM:
Step3: Design your MainActivity which should look like this:
Step4: Now let’s create few singleton classes:
In Kotlin, Singletons are very easy to create they just use a keyword called object before the class name. Check the code below
a. Retrofit Singleton
b. Repository Singleton
Step5: Next step is to create the Model class:
Step6: Next we create ApiInterface for the APIs:
Step7: Next and very important step is to have a ViewModel in the project:
Step8: Finally, we code the MainActivity kotlin file:
For any clarifications please refer to the repository.
Conclusion
The goal of the MVVM using Kotlin and Retrofit is to acheive the best possible solution and save development time by using the best architectural pattern suggested by Google.
I hope it will help you too.
About
Android’s MVVM Architecture in Kotlin ft. Retrofit
Источник