Thursday 5 December 2019

Retrofit Android



use same method with every interface method Client ...
public class ApiClient {
public static final String Base_URL = " http://XXXXXXXXX/XXXXXXX/";

public static RetrofitApi getClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
    
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Base_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    
    return retrofit.create(RetrofitApi.class);
}

public static <T> void callRetrofit(Call<T> call, final int i) {
    
    call.enqueue(new Callback<T>() {
        @Override
        public void onResponse(Call<T> call, Response<T> response) {
            if(i==1){
                User user = (User) response.body(); // use the user object for the other fields
            }else if (i==2){
                Patient user = (Patient) response.body();
            }
            
            
        }
        
        @Override
        public void onFailure(Call<T> call, Throwable t) {
            
        }
    });
    
}
Create your interface and it's all methods.
    public interface RetrofitApi{

    @FormUrlEncoded
    @POST("login")
    Call<Result> login(@Field("mobile") String mobile, @Field("password") String password);


    }
use like this in your Activity or Fragment.
 Call<User> call = ApiClient.getClient().login("sam","123456");
 ApiClient.callRetrofit(call,1);
Gradle dependencies are
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
Sample Retrofit for every call.
    final ProgressDialog mProgress = Utility.showProgressDialog(activity);
    ApiClient.getClient().create(RetrofitApi.class).getSimpleData().enqueue(new Callback<Result>() {
        @Override
        public void onResponse(Call<Result> call, Response<Result> response) {
            mProgress.dismiss();
            if (response.isSuccessful()) {
                    if(response.body().getSuccess()){
                        
                    }else
                        Toast.makeText(activity, response.message(), Toast.LENGTH_SHORT).show();
            } else
                Toast.makeText(activity, response.message(), Toast.LENGTH_SHORT).show();
        }
        
        @Override
        public void onFailure(Call<Result> call, Throwable t) {
            mProgress.dismiss();
            if (!Utility.checkconnection(activity))
                Utility.showconnectiondialog(activity, MyFragment.this);
            else
                Toast.makeText(activity, "Server doesn't working.", Toast.LENGTH_SHORT).show();
        }
    });
If you want to get whole response in JSON format, try this:
I have tried a new way to get whole response from server in JSON format without creating any model class. I am not using any model class to get data from server because I don't know what response I will get or it may change according to requirements.
this is JSON response:
{"contacts": [
    {
     "id": "c200",
     "name": "sunil",
     "email": "email@gmail.com",
     "address": "xx-xx-xxxx,x - street, x - country",
     "gender" : "male",
     "phone": {
      "mobile": "+91 0000000000",
      "home": "00 000000",
      "office": "00 000000"
     }
    },
    {
     "id": "c201",
     "name": "Johnny Depp",
     "email": "johnny_depp@gmail.com",
     "address": "xx-xx-xxxx,x - street, x - country",
     "gender" : "male",
     "phone": {
      "mobile": "+91 0000000000",
      "home": "00 000000",
      "office": "00 000000"
     }
    },
    .
    .
    .
]}
  1. In your API interface change the parameter
    public interface ApiInterface {
    @POST("/index.php/User/login")//your api link 
    @FormUrlEncoded
    Call<Object> getmovies(@Field("user_email_address") String title,
                    @Field("user_password") String body);
    }
    
  2. in your main activity where you are calling this
    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);
    
    Call call = apiService.getmovies("a@gmail.com","123456");
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            Log.e("TAG", "response 33: "+new Gson().toJson(response.body()) );
        }
    
        @Override
        public void onFailure(Call call, Throwable t) {
            Log.e("TAG", "onFailure: "+t.toString() );
            // Log error here since request failed
        }
    });
    
  3. after that you can normally get parameter using JSON object and JSON array
Example
 getNotification.enqueue(new Callback<Object>() {
            @Override
            public void onResponse(Call<Object> call, Response<Object> response) {
                if (response.isSuccessful()) {
                    String data = new Gson().toJson(response.body());
                    try {
                        useData(data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(activity, response.message(), Toast.LENGTH_SHORT).show();
                }
            }
            
            @Override
            public void onFailure(Call<Object> call, Throwable t) {
                Log.d("sushildlh", "error " + t.getMessage());
            }
        });


 private void useData(String data) throws JSONException {
        JSONObject jsonObject = new JSONObject(data);
        if (jsonObject.has("success")) {
            if (jsonObject.getBoolean("success")) {
                JSONArray array = jsonObject.getJSONArray("notification");
                isRead = new ArrayList<>();
                messages = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    JSONObject json = array.getJSONObject(i);
                    isRead.add(json.getString("readAt"));
                    String msgData = json.getString("data");
                    JSONObject userData = new JSONObject(msgData);
                    if (userData.has("friend_request")) {
                        JSONObject user = userData.getJSONObject("friend_request");
                        String msg;
                        if(user.getString("status").equals("send_request"))
                            msg = "send friend request.";
                        else
                            msg = "accepted friend request.";
                        messages.add(user.getString("pet_name")+" "+msg);
                    }else if(userData.has("vaccination")) {
                        JSONObject vacc = userData.getJSONObject("vaccination");
                        messages.add(vacc.getString("vaccination_name")+" for "+vacc.getString("pet_name"));
                    }
    
                    mList.setAdapter(new RemindersAndUpdateAdapter(messages));
                    
                }
            } else {
                Toast.makeText(activity, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(activity, "Json Exception", Toast.LENGTH_SHORT).show();
        }
        
    }
Output enter image description here
Convert String to Object...
    String data = getArguments().getString("bill");

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    Bills bills = gson.fromJson(data, Bills.class);

That is all. If any help related to this post please comment.

Thank you, guys.

Enjoy coding.

No comments:

Post a Comment

Upload File Using Retrofit Android

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