Thursday 5 December 2019

Upload File Using Retrofit Android



For updating a file on the server using API.
    public void uploadProfilePic(File file) {
    ApiClient.getClient().create(RetrofitApi.class).uploadUserProfile(getbody("123"), createBody(file)).enqueue(new Callback<Result>() {
        @Override
        public void onResponse(Call<Result> call, Response<Result> response) {
            if(response.isSuccessful()) {
                if (response.body().getSuccess()) {
                    Toast.makeText(activity, response.body().getMessage(), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(activity, response.body().getMessage(), Toast.LENGTH_LONG).show();
                }
            }else{
                Toast.makeText(activity, response.raw().message(), Toast.LENGTH_LONG).show();
            }
        }
        
        @Override
        public void onFailure(Call<Result> call, Throwable t) {
          Toast.makeText(activity, t.getMessage(), Toast.LENGTH_LONG).show();
        }
    });
    }
Other Methods.
public MultipartBody.Part createBody(File file) {
    RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
    MultipartBody.Part body = MultipartBody.Part.createFormData("profile", file.getName(), requestBody);
    return body;
}

public RequestBody getbody(String descriptionString) {
    return RequestBody.create(
            okhttp3.MultipartBody.FORM, descriptionString);
}
Interface method ......
@Multipart
@POST("changePic")
Call<Result> uploadUserProfile(@Part("id") RequestBody id,@Part MultipartBody.Part image);

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

Thank you, guys.

Enjoy coding.

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.

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...