Sunday, 6 May 2018

How to Upload Image using Retrofit in Android

- First To add in ApiInterface class
- APIInterface.java
  public interface APIInterface {
    //For Edit Profile
    @Multipart
    @POST("editprofile")
    Call<GetSetData> getUpdateProfile(@Part("rollno") RequestBody rollno, @Part("address") RequestBody address,@Part("fullname") RequestBody fullname, @Part MultipartBody.Part image);
  }

- ApiClient.java
   public class ApiClient {
   public static final String BASE_URL = "http://test.com/api/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

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

- Give Permission in AndroidManifest.xml
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

- Add Following code in build.gradle
   compile 'com.squareup.retrofit2:retrofit:2.0.2'
   compile 'com.squareup.retrofit2:converter-gson:2.0.2'
   compile 'com.squareup.okhttp3:okhttp:3.4.1'
   compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

- To Call Following Method on Click of Select image Button
   private void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
        builder.setTitle("Add Photo!");
        builder.setCancelable(false);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, 100);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"), 200);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 100) {
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
                File destination = new File(Environment.getExternalStorageDirectory(),
                        System.currentTimeMillis() + ".jpg");
                selectedImagePath = destination.getAbsolutePath();
                FileOutputStream fo;
                try {
                    destination.createNewFile();
                    fo = new FileOutputStream(destination);
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image_profile.setImageBitmap(thumbnail);

            } else if (requestCode == 200) {
                Uri selectedImageUri = data.getData();
                String[] projection = {MediaStore.MediaColumns.DATA};
                CursorLoader cursorLoader = new CursorLoader(TestActivity.this, selectedImageUri, projection, null, null, null);
                Cursor cursor = cursorLoader.loadInBackground();
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                cursor.moveToFirst();
                selectedImagePath = cursor.getString(column_index);

                Bitmap bm;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(selectedImagePath, options);
                final int REQUIRED_SIZE = 200;
                int scale = 1;
                while (options.outWidth / scale / 2 >= REQUIRED_SIZE
                        && options.outHeight / scale / 2 >= REQUIRED_SIZE)
                    scale *= 2;
                options.inSampleSize = scale;
                options.inJustDecodeBounds = false;
                bm = BitmapFactory.decodeFile(selectedImagePath, options);

                try {
                    ExifInterface ei = new ExifInterface(selectedImagePath);
                    int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
                    switch (orientation) {
                        case ExifInterface.ORIENTATION_ROTATE_90:
                            bm = rotateImage(bm, 90);
                            break;
                        case ExifInterface.ORIENTATION_ROTATE_180:
                            bm = rotateImage(bm, 180);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                image_profile.setImageBitmap(bm);
            }
        }
    }

    public static Bitmap rotateImage(Bitmap source, float angle) {
        Bitmap retVal;

        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        retVal = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
        return retVal;
    }

- To Add following code in Java class
     private void updateProfileData(String full_name, String address) {
        // Showing progress dialog
        pDialog = new ProgressDialog(ProfileActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

        //creating a file
        File file = new File(selectedImagePath);

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part imagenPerfil = MultipartBody.Part.createFormData("image1", file.getName(), requestFile);

        // add another part within the multipart request
        RequestBody req_roll_no = RequestBody.create(MediaType.parse("text/plain"), roll_no);
        RequestBody req_address = RequestBody.create(MediaType.parse("text/plain"), address);
        RequestBody req_full_name = RequestBody.create(MediaType.parse("text/plain"), full_name);

        APIInterface apiService = ApiClient.getClient().create(APIInterface.class);
        Call<GetSetData> call = apiService.getUpdateProfile(req_roll_no, req_address, req_full_name, imagenPerfil);
        call.enqueue(new Callback<GetSetData>() {
            @Override
            public void onResponse(Call<GetSetData> call, Response<GetSetData> response) {
                String str_success = response.body().getSuccess();
                if (pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                if (str_success.equals("1")) {
                    Toast.makeText(TestActivity.this, "Profile Update Successfully", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<GetSetData> call, Throwable t) {
                // Log error here since request failed
                if (pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Toast.makeText(getApplicationContext(), "Some problem occure", Toast.LENGTH_SHORT).show();
            }
        });
    }

No comments:

Post a Comment