Friday 20 May 2016

Retrofit + Firebase

Retrofit + Firebase
I am posting this Retrofit + Firebase post because it helps the Android developer to do REST API calls without any BECK-END knowledge. This is a help to the beginner to understated the REST API and practice more.
Data store in JSON file in the Firebase.
We can change JSON data direct also like create JSON file and import to the Firebase directly or we export it to the disk and create a static JSON file.
It is an easy way to implement REST API without ANY BECK-END knowledge. That is helpful for the beginner.
We need a Firebase account and some basic knowledge of REST API.
Step 1: First go to Firebase and create your account.
Step 2: After creating your account go to AppCreation and create your App. Enter your app name and other settings and continue.

Step 3: If you want to add some options then check the checkboxes or create a project.


Step 4: Now your project is created. Just open your created project. There is an option on the left menu called Database


Step 5: Select Database and there is a drop-down arrow on Cloud Firestore. Select Realtime Database from drop down.





Step 6: Go to Rules Tab and make read: true if you want to read the REST API and write: true if you want to write from the REST API.



After the creation of App, it automatically creates a URL like this https://my-app-5d36b.firebaseio.com/, which we can use in the RESTApi Calls.
We have to add these dependencies in GRADLE.
compile 'com.squareup.retrofit2:retrofit:2.0.2'//this for the retrofit 
compile 'com.squareup.retrofit2:converter-gson:2.0.0'// this for the JSON converter

Know About the code ............
We have to create an API interface which has all RESTApi methods
public interface Api {
    @POST("/upload/{new}.json")
    Call<User> setData(@Path("new") String s1, @Body User user);

    @GET("/upload/sushil.json")
    Call<User> getData();

    @PUT("/upload/{new}.json")
    Call<User> setDataWithoutRandomness(@Path("new") String s1, @Body User user);

}
POJO for the JSON data which is used for converting data into JSON or OBJECT or Vice-Versa ..... like that
public class User {

    String name;
    String address;

    public User(String name, String address) {
        this.address = address;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}
Know the RESTApi calls and uses.....
Know we create the Retrofit Object like this.....
 Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://my-app-5d36b.firebaseio.com")//url of firebase app
                .addConverterFactory(GsonConverterFactory.create())//use for convert JSON file into object
                .build(); 
Know we create API Object like this...
 Api api = retrofit.create(Api.class);//use of interface 
there is a call for PUT method...
Call<User> call1=api.setDataWithoutRandomness("sushil", new User("sushil", "mumbai"));
        call1.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                t1.setText("Success "+response.body().getName());
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                t1.setText("fail");
            }
        });
there is a call for POST method...
Call<User> call = api.setData("mahesh", new User("mahesh", "delhi"));
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            t1.setText("Success");
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Log.d("sam", "fail");
            t1.setText("fail");
        }
    });
there is a call for GET method...
 Call<User> call2=api.getData();
        call2.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                t1.setText("success "+response.body().getName()+" "+response.body().getAddress());
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                t1.setText("fail");
            }
        });
and finally, JSON file which is created on the Firebase.
{
  "upload" : {
    "mahesh" : {
      "-KIBTSbkyEGFgX_VqWJQ" : {
        "address" : "delhi",
        "name" : "mahesh"
      }
    },
    "sushil" : {
      "address" : "mumbai",
      "name" : "sushil"
    }
  }
}
And JSON file looks like this in FIREBASE account.

In the JSON file "-KIBTSbkyEGFgX_VqWJQ" this is Anonymously Name which is generated when we use the POST method.
Guys this is my first Retrofit + Firebase blog.
That is all. If any help related to this post please contact me at sushildlh@gmail.com.
Thank you, guys. 
Enjoy coding.......

Upload File Using Retrofit Android

For updating a file on the server using API. public void uploadProfilePic(File file) { ApiClient.getClient().create(Retrofit...