Retrofit Tutorial Step-by-step : How to use Retrofit to send and receive data from Server ? - SpartaCode

SpartaCode

Make your development faster and easier !

Retrofit Tutorial Step-by-step : How to use Retrofit to send and receive data from Server ?

Retrofit Technology

Retrofit is a rest client for Android and Java by square.

It is a technology used to send a request request to server and receive data from server.

Lets move to tutorial Right now.


How to setup retrofit in Android Studio ?


Step 1: Simply add this this dependency to your App build.gradle


   // Retrofit
   compile 'com.squareup.retrofit2:retrofit:2.2.0'
   compile 'com.squareup.retrofit2:converter-gson:2.2.0'
   compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'









   

Step 2: Download this zip file and extract folder and then place it into your project.



Download zip file



         


Step 3 : Now expand services folder you will find RestClient.java file Open it.





Change value of BASE_URL = Your Project URL

For Example :
http://localhost/YourProjectName/

Note : Dont touch any other part of this file.



Step 4 : Copy paste following code into your MainActivity.java file.


 public static RestClient restClient;

    public static RestClient getRestClient() {
        if (restClient == null) {
            restClient = new RestClient();
        }
        return restClient;
    }

Thats it, You are done with Retrofit setup.


How to use retrofit ?

Step 1 : Creating PHP services
        Easy and fast method to code is going to this link.






    Note : Enter your table name and all column names except ID column eg. UserId.
   
    Click on Submit Button and quickly get the PHP code to get data or insert data from and to Server    
    respectively.

    PHP code to get data from table.

 

   Copy paste code and save file as getData.php


   PHP code to insert data into table.



   Copy paste code and save file as insertData.php


   Step 2 : Creating model class

     Copy following JSON object :
   


    Now,  Go to this link :


      Model Class Generator

 
     Paste Copied JSON object into this Box.

   



Provide a name to your Model Class and Press Submit you will get your model class created.

Create new class into "models" folder in services package.






Now copy complete model class and paste it into this class.

Note : Name of class should be same as name of model class.


Step 3 : Declaring method in rest interface


Declaring method to get data from Server.
Go to RestInterface.java file in "services" package.

Now declare the method as follows :




Now,  finally we will send request to server using Retrofit Call in step 4.



Step 4 : Defining method where ever you you want to use.



Copy following code and paste it into your java file where you will send request to server.


public void insertData(String mobilenumber) {
        MainActivity.getRestClient().getRestInterface().insertNumber("").enqueue(new Callback<List<ModelClass>>() {
            @Override
            public void onResponse(Call<List<ModelClass>> call, Response<List<ModelClass>> response) {
                if (response.isSuccessful()) {
                    //Code after successful json response
                 }
            }

            @Override
            public void onFailure(Call<List<ModelClass>> call, Throwable t) {
                //Log.e("Upload error:", t.getMessage());
            }
        });
    }


Another Good Way of Sending Request is using JSON as Follows:

First Step would be including Dependency:
Include following code in build.gradle of Project:
   
 compile 'com.squareup.okhttp3:logging-interceptor:3.6.0'

1. Declaring Request :

             @POST("getdata.php")
             Call<JsonObject> getData(@Body JsonObject jsonObject);

2. Usage in Code

              
        
            JsonObject jsonObject=new JsonObject();
            jsonObject.addProperty("key","value");
             MainActivity.getRestClient().getRestInterface().getData(jsonObject).enqueue(new Callback<jsonobject>() {
                @Override
                public void onResponse(Call<jsonobject> call, Response<jsonobject> response) {
                    if (response.isSuccessful()) {

                    }
                }
                @Override
                public void onFailure(Call<jsonobject> call, Throwable t) {
                    Log.e("Upload error:", t.getMessage());
                }
            });


Thank you 
Hope you like tutorial
+1 Post and Comment.

4 comments:

  1. Can you please upload the xml file for the MainActivity, in order to make the form for the info to be displayed and sended...
    Greetings

    ReplyDelete
    Replies
    1. Thank you for your comment.
      You can now download services file uploaded on my drive using link in post.
      Now you can see data sent and recieved from server using intercepters.

      Delete
  2. I'm going to learn this tool

    ReplyDelete
  3. Great David ...
    Have a great day.

    ReplyDelete

Get Amazing Traffic to your Site

Traffic Exchange

Post Bottom Ad

Responsive Ads Here