Retrofit GET Example

I’m going to show an basic example on usage of Retrofit. Retrofit lets you amazing simple and clean GET and POST methods. You do not need long and complex asynchronous task in Android anymore :O

1. ApiInterface



First we need to create an interface which names it as ApiInterface.


public interface ApiInterface {

    @GET("user/{Id}")
    Call<List<User>> userData(@Path("Id") String Id);

    
}

2. ApiClient

Second, we need to create an ApiClient class to determine our BASE URL.

public class ApiClient {

    public final static String BASE_URL = "https://api.github.com/";
    private static Retrofit retrofit = null;

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


3. Get Data from Server

Now, we will send the specific user id from the server to get its data.
Firstly, we use our ApiInterface to create an ApiClient service. After that, we have to use “Call” class to receive data from server and we will enqueue its call to use that data. in “onResponse” part. There is also an onFailure method to check your server and link works totally correct.
   
    public void getData(){
        // sends the user id 
        String user_id = "69";
        ApiInterface apiService =
                ApiClient.getClient().create(ApiInterface.class);

        Call<List<User> > call =
                apiService.userData(user_id);

        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                List<User> userInfo = response.body();
                for(int i = 0; i<userInfo.size(); i++){
                    // Magic here
                }
            }

            @Override
            public void onFailure(Call<List<Junction>> call, Throwable t) {
                Log.e("MyApp", "getData ERROR :" + t.toString());
            }
        });
    }

After using asynchronous task to use @GET and @POST methods, Retrofit is the new cure for me :) I’m a bit late to learn Retrofit but better than never :P
If you have any question, ask me :)

FreakyCoder Software Blog

Software Annotations

How to extract filename from Uri?

Now, we can extract filename with and without extension :) You will convert your bitmap to uri and get the real path of your file. Now w...