matheusleite
5/31/2017 - 2:05 PM

PhotoUpload.java

private void saveUserWithPhoto(final User user ) {
        String url;
        if( user.getId() > 0 ){
            url = ApiReference.User.getUpdateUrl(user.getId());
        } else {
            url = ApiReference.User.getCreateUrl();
        }

        CustomVolleyMultipartRequest multipartRequest = new CustomVolleyMultipartRequest(url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                handleSaveUserResponse(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if( mOnSaveListener != null ) {
                    mOnSaveListener.onUserSaveFailure(error);
                }
            }
        }){
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();

                params.put("firstname", user.getFirstName());
                params.put("lastname", user.getLastName());
                params.put("email", user.getEmail());

                if( user.getPassword() != null ) {
                    params.put("password", user.getPassword());
                }

                if( user.getId() > 0 ) {
                    SharedPreferences preferences = mContext.getSharedPreferences(SharedPreferencesReference.SHARED_PREFERENCES_IDENTIFIER, Context.MODE_PRIVATE);
                    String token = preferences.getString(SharedPreferencesReference.Auth.TOKEN_IDENTIFIER, "");
                    params.put("token", token);
                }
                params.put( "pushDeviceToken", getDeviceToken() );

                return params;
            }

            @Override
            protected Map<String, DataPart> getFiles() {
                Map<String, DataPart> params = new HashMap<>();

                try {
                    Bitmap image = BitmapFromUri.getCorrectlyOrientedImageFromFilePath(user.getImage());
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                    byte[] byteArray = stream.toByteArray();

                    params.put("photo", new DataPart(byteArray, ContentType.create("image/jpeg"), "photo.jpg")  );
                    image.recycle();
                } catch (IOException e) {
                    System.out.print(e.getMessage());
                }

                return params;
            }
        };

        multipartRequest.setRetryPolicy(new DefaultRetryPolicy(
                120000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
        ));

        multipartRequest.setTag(CREATE_USER_TAG);
        mRequestQueue.add(multipartRequest);
    }