Retrofit Android Tutorial – Using Retrofit 2.2 with PHP Restful API

Welcome to Retrofit Android Tutorial guys. Today we will learn to build a simple application in android using Retrofit Android Library and SLIM PHP Framework. Today, we will be covering a lot of things. We …

retrofit android tutorial

Welcome to Retrofit Android Tutorial guys. Today we will learn to build a simple application in android using Retrofit Android Library and SLIM PHP Framework.

Today, we will be covering a lot of things. We will see user registration, user login, session management and many more things. So keep reading carefully as this is going to be a long tutorial.

Retrofit Android Tutorial – Complete Video Series

  • If you want a complete explanation about building API with PHP and SLIM and using them in Android with Retrofit then you should watch this Play List. (Don’t forget to share with your friends). 

The App Overview

  • So lets first understand what we are going to build. The below diagram will explain you in detail.

application mockflow

  • As you can see in the above diagram we are going to build a very simple application. Where the registered user can send messages to each other.
  • Now the next step is designing the database. I am going to use MySQL for this.

Database Design

  • This is our database model.

retrofit android tutorial

  • It is very simple and to create the above database just go to phpmyadmin create a database and run the following SQL code.

  • Now lets create the REST API.

Building RESTful API using SLIM

Creating Project

  • First go to xampp/htdocs and open terminal here. (if you are using windows go to c:/xampp/htdocs in command prompt).
  • Now run the following command to create a new project. (Make sure you have composer installed).

  • In the above line RetrofitExample is the project name. You can change it with whatever you want.
  • After executing the above command your php project will be created. Now you can use any Text Editor to work on this project. I am using PHPStorm.
  • You will see the following directory structure in the project you just created.

directory structure

  • Open index.php and delete everything that is inside.
  • Now inside RetrofitExample (Your project directory) create one more directory named includes.

Defining Constants

  • Inside includes create a new php file named Constants.php it will store all the required constants. Make sure to change the database name according to your database in the below script.

Connecting with Database

  • Now in the same directory create one more php file named DbConnect.php.

  • The above script will connect with the MySQL database.

Performing Database Operation

  • Now create one more php script named DbOperation.php that will perform all the required database operations.

Handling API Calls

  • Now come inside index.php that is inside the public folder and write the following code.

  • The API Building is finished. I haven’t explain this part too much as we already did it in one of the previous tutorials about PHP Restful API using SLIM.

Testing the APIs

  • Now lets test the APIs. For testing I am using Postman you can use any REST Client. So the URLs we have are.
URL Method Parameters
http://localhost/RetrofitExample/public/register POST name, email, password, gender
http://localhost/RetrofitExample/public/login POST email, password
http://localhost/RetrofitExample/public/messages/{id} GET
http://localhost/RetrofitExample/public/update/{id} POST name, email, password, gender
http://localhost/RetrofitExample/public/sendmessage POST from, to, title, message
http://localhost/RetrofitExample/public/users GET

http://localhost/RetrofitExample/public/register

postman rest client

  • The same way you can test all the URLs and then we can start developing the Android Application.

Building Android Application using Retrofit

Creating Project

  • Create a new Android Studio Project. I created a project named RetrofitExample.
  • Once your project is loaded go to app level build.gradle file and add the following dependencies.

  • Now sync your project with gradle and Retrofit and Gson is added.

Designing Screens

First Screen

  • So our first screen is having two buttons for Sign In or Sign Up. So inside activity_main.xml paste the following code.

  • The above code will generate the following layout.
Sign In Sign Up Screen
Sign In Sign Up Screen
  • This is screen is very simple, having only two buttons that will take us to the respective screens.

Sign In Screen

  • Now create a new Empty Activity named SignInActivity and inside the layout file of this activity write the following xml code.

  • This screen will look like as below.
Sign In Screen
Sign In Screen

Sign Up Screen

  • Now again create a new Empty Activity for Sign Up Screen and write the following xml code in the layout file.

  • This screen will look like as below.
Sign Up Screen
Sign Up Screen

Home Screen

  • User will come to this screen after Signing In. This will be a Navigation Drawer Activity. So create a Navigation Drawer Activity for the Home Screen.
  • Creating a Navigation drawer activity will create a number of layout files inside the layout directory. First come to nav_header_home.xml and modify it as below.

  • Now open app_bar_home.xml and remove the floating action button.

  • Now go to menu folder and you will see activity_home_drawer.xml change it to the following.

  • Now we will display all the remaining screen inside this home screen using fragments. So lets quickly design the layout for all other screens.

Designing Home Fragment

  • As we decided in the app that in the home screen we will display all users. For this we will use RecyclerView and CardView. So first you need to add RecyclerView and CardView in your project. For this go to project structure->app->dependencies and add library dependency with CardView and RecyclerView. For details you can check this RecyclerView tutorial.
  • Create a new layout file named fragment_home.xml and write the following code.

  • As you can see we have a RecyclerView in fragment_home, so we need to create one more layout for the RecyclerView. So create a new layout file named list_users.xml and we will display all the users of the application in the list.

  • Now in this screen we will also have an alert dialog to send messages to the users. We will also design this dialog.

Designing Alert Message Dialog

  • Create a file named dialog_send_message.xml and write the following code.

  • Now lets design the profile fragment screen.

Designing Profile Fragment

  • Again create a new layout file named fragment_profile.xml and write the following code.

  • It will look like this.
Profile Screen
Profile Screen
  • Now the last fragment is Messages fragment.

Designing Messages Fragment

  • Again create a new file named fragment_messages.xml and write the following code. Here we are again using RecyclerView to display the messages received by the user in a list.

  • Again we will define a list layout for the recycler view. So create a file named list_messages.xml and write the following code.

  • So we have designed all the screen needed in the application. Now lets start coding the application.

Coding Screens

  • First create 4 packages inside your main package to make everything organized. I have created activities, api, fragments, model. 

packages

  • As you can see I have moved all the activities inside activities package. This is only to keep the things organized. Now come to MainActivity.java.

Defining Base URL

  • Inside api package create a class named APIUrl.java and inside this class we will define the base url of our API. Remember you are not allowed to use localhost here, you need to find the ip of your system if you are using localhost (I am using xampp). For windows use ipconfig and for Mac or Linux use ifconfig to find the ip.

Adding Internet Permission

  • Go to AndroidManifest.xml and add internet permission.

Coding MainActivity

  • MainActivity is very simple we only need to navigate to the respective screen on button press.

  • Now lets move to coding SignUpActivity.java.

Coding SignUpActivity

Creating Retrofit API

  • Now first create a java interface inside api package and name it APIService.java. Here we will define all the API calls.

  • So our API is ready. After @Field(“parameter”) we have the parameter value of our API that we created. So it should match with the parameter that is to be passed.

Creating Model

  • Retrofit will automatically convert the response to our java object. For this we need to define the Model class. We will define the models inside the package named model that we created.
  • Now first analyse the response that we are getting on register.

On Success

On Failure

  • As you can see we have error, message and user in the response JSON. So we will create two class for this one will be the Result and other will be User.
  • So create two classes inside your model package named Result.java and User.java and write the following codes.
  • Result.java

  • User.java

Getting User Values

  • Now come back go SignUpActivity.java and define the view objects and listeners.

  • Now we will perform the SignUp using Retrofit.

Performing POST Request using Retrofit

  • Inside the method userSignUp() write the following code.

Testing Sign Up Screen

  • Run your application now and go to Sign Up Screen and try Signing Up as a new user.

Sign Up Screen Working

  • As you can see we got the success message. Check the MySQL database for the new user.

mysql database

  • See the last row. Bingo! it is working absolutely fine.

Making User Login after Successful Registration

  • On the successful registration we will make the user automatically logged in. For this we will use the SharedPreferences to store user data.
  • So we will create a new class for managing SharedPreferences.
  • Create a new package named helper and inside the package create a class named SharedPrefManager.java.

  • Now we need to modify the userSignUp() method of SignUpActivity.java as below.

  • Now again test by registering as a new User and you should automatically log in on success.

user auto login

  • Now come to MainActivity.java and here we will also check if the user is already logged in then we will directly open the profile activity.

  • Now run your application again and you will be directly navigated to the Home Activity. Now we will code the User Sign In Activity.

Coding Sign In Activity

Creating Retrofit API

  • Again we will create a new API call inside APIService interface for the Sign In.

Making User Sign In

  • Now inside SignInActivity.java write the following code. We are doing almost the same we did in SignUpActivity.java.

  • Now we will code the home fragment where we will display a list of all users.

Coding Home Activity

  • Every other screen is inside this activity using fragments so first we will define a FrameLayout where we will switch the fragments.
  • So come inside content_home.xml and modify it as below.

Building Home Fragment

  • In the Home Fragment we will display list of all the users from the database. For this we already have the API http://localhost/RetrofitExample/public/users. The response of this GET call is.

  • To store it we will define one more model inside models package. So create a class named Users and write the following code.

  • Now we will build our Custom RecyclerView Adapter to display User List. So create a class named UserAdapter.java inside helper package and write the following code. If you need more detail about RecyclerView you can go through this RecyclerView Tutorial. 

  • Now inside the fragments package create a new class named HomeFragment.java and write the following code.

  • Now come inside HomeActivity.java and modify the method displaySelectedScreen() as below.

  • Now try running the application.

home screen listing users

  • So its working fine. Now we will code the functionality for the message icon, it should open an alert dialog to send message to the selected user. We already have the layout for the custom alert dialog.
Making Custom Alert Input for Sending Message
  • Again come inside the UserAdapter.java class and modify it as below.

  • Now try running the application and on the message icon click you will see an alert dialog asking for message inputs.

message alert dialog

  • Now we will code for sending the message. We already have API for this.
Sending Message to The User
  • We are not using any FCM so the user will not be notified for the message, the recipient can only see the received message when he opens the app.
  • First we will define a model for the send message api response. The response is.

  • So inside models create a new java class named MessageResponse.java.

  • So first we will define a new API Call in APIService.java file.

  • Now inside UserAdapter.java define the sendMessage() method as below.

  • Now test your application.

message sent

  • Yes it is working fine. So the HomeFragment is finished. Now we will build the next profile fragment.

Building Profile Fragment

  • Inside Profile Fragment user can update the details. So for updating we have the API. So to make the api call we will again define a new API Call inside APIService.java.

  • Now create a new class named ProfileFragment.java inside fragments package and write the following code.

  • Now again inside HomeActivity.java we need to modify the method displaySelectedScreen() as below to show the Profile Fragment.

  • Now test the application and try updating the values.

profile updated

  • So it is working fine.

Building Messages Fragment

  • The API returning the messages in the following format.

  • So to model the above data we need to classes. So first create a class named Message.java inside models package.

  • Now create a class named Messages.java in models package.

  • Now we will make a new API call inside APIService.java.

  • To display all the message again we need an adapter so create a class inside helper package named MessageAdapter.java.

  • Now create a new class inside fragments package named MessageFragment.java and write the following code.

  • Now again we need to modify the displaySelectedScreen() method on HomeActivity.java file.

  • We also defined the logout this time to make logout work as well. So now everything has finished in the application.

messages fragment

  • Bingo! it is working absolutely fine.
  • If you are having confusions or troubles you can get my source code from the below given link.

Retrofit Android Tutorial Source Code Download

Android Studio Project

Retrofit Android Tutorial Source Code

So that’s all for this Retrofit Android Tutorial friends. It was the longest post I have written so far, so please follow it carefully. If you are having any confusions or queries regarding this Retrofit Android Tutorial, then let’s start a discussion on the comments section. Also if you found some errors about this Retrofit Android Tutorial then do let me know in the comments. And if you liked this post and found it useful you can SHARE it on your social networks. Thank You 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

Expand Your Knowledge: Next Tutorial Picks

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x