com.mobantica.DriverItRide.activities.ActivityProfile.java Source code

Java tutorial

Introduction

Here is the source code for com.mobantica.DriverItRide.activities.ActivityProfile.java

Source

package com.mobantica.DriverItRide.activities;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mobantica.DriverItRide.BuildConfig;
import com.mobantica.DriverItRide.MainActivity;
import com.mobantica.DriverItRide.R;
import com.mobantica.DriverItRide.comman.AppUtils;
import com.mobantica.DriverItRide.comman.Generic;
import com.mobantica.DriverItRide.comman.Networking;
import com.mobantica.DriverItRide.comman.SharedPreferencesUtil;
import com.mobantica.DriverItRide.comman.UtilsConstants;
import com.mobantica.DriverItRide.comman.Web;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.mobantica.DriverItRide.activities.ActivityRegistrationThird.MEDIA_TYPE_IMAGE;
import static com.mobantica.DriverItRide.activities.ActivitySelectPaymentType.REQUEST_TIME;
import static com.mobantica.DriverItRide.comman.AppUtils.createProgressDialog;
import static com.mobantica.DriverItRide.comman.AppUtils.dismissProgressDialog;
import static com.mobantica.DriverItRide.comman.AppUtils.resizeAndCropCenter;
import static com.mobantica.DriverItRide.comman.AppUtils.rotateImage;
import static com.mobantica.DriverItRide.comman.AppUtils.setLangunageType;
import static com.mobantica.DriverItRide.comman.Generic.GetFormatedMonthDateText;
import static com.mobantica.DriverItRide.comman.UtilFunctions.isNetworkAvailable;
import static com.mobantica.DriverItRide.comman.UtilFunctions.myToast;
import static com.mobantica.DriverItRide.comman.UtilsConstants.LANGUAGE_TYPE;
import static com.mobantica.DriverItRide.comman.Web.API_KEY_VALUE;
import static com.mobantica.DriverItRide.comman.Web.DRIVER_ID;
import static com.mobantica.DriverItRide.comman.Web.GET_PROFILE_DETAIL;
import static com.mobantica.DriverItRide.comman.Web.MAIN_URL;
import static com.mobantica.DriverItRide.comman.Web.POST_MOTHOD_TYPE;
import static com.mobantica.DriverItRide.comman.Web.TOKEN_KEY;
import static com.mobantica.DriverItRide.comman.Web.X_API_KEY;

public class ActivityProfile extends AppCompatActivity
        implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private String TAG = "ActivityProfile";
    private CollapsingToolbarLayout collapsingToolbar;
    private TextView txtGender;
    private TextView txtBirthDate;
    private TextView txtMobile;
    private TextView txtEmail;
    private TextView txtStreetAddress;
    private TextView txtArea;
    private TextView txtPincode;
    private TextView txtAadharNumber;
    private TextView txtPanNumber;
    private TextView txtDrivingLicenseId;
    private TextView txtLicenseExpDate;
    private TextView txtVehicleType;
    private TextView txtVehicleModel;
    private TextView txtVehicleColor;
    private TextView txtVehicleRegistrationNumber;
    private TextView txtBankName;
    private TextView txtBranchName;
    private TextView txtAccountNumber;
    private TextView txtIfsc;
    private TextView txtSelectLanguange;

    public String FirstName, LastName, Gender, DoB, Mobile, Email, StreetAddress, Area, Pincode, State;
    public String City, DrivingLicenseId, LicenseExpDate, PanNumber, AadharNumber, BankAccountNumber, BankIFSC,
            BankName, BranchName, VehicleRegistrationNumber, VehicleColor, VehicleModel, VehicleType;

    //Dialog
    private Dialog dialogSelectLangunage;
    private Button btnCancel, btnSave;
    private EditText edtEnterAmount;
    private String ProfileImgPath = "", DriverWalletId = "", WalletAmount = "", WalletCreatedOn = "",
            WalletCreatedBy = "", LastTransactionId = "";
    private TextView txtWalletBalance;
    private String token = "", drievr_id = "";
    private ArrayList<HashMap<String, String>> walletTransactions;
    private String langunageType = "";
    private Configuration config;
    private Locale locale;
    private RadioButton rdoEnglish;
    private RadioButton rdoHindi;
    private RadioButton rdoMarathi;
    private CircleImageView img_profile;
    private ImageView img_profile_square;
    private Uri fileUri;
    private Uri ChnagedUri = null;
    private static final String IMAGE_DIRECTORY_NAME = "ProfilePic";
    private String imagebaseProfilephoto;
    private ProgressDialog progress;
    private RequestBody requestBody;
    private String message = "";

    private UpdateProfilePhotoTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        initToolbar();
        initTextview();
        initImage();
        collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);

        setCollapsedTitleTextColor();

        if (isNetworkAvailable(this)) {
            getProfileDetails();
        } else {
            setOfflineText();
            myToast(this, "" + getResources().getText(R.string.ISAVAILABLE));
        }

    }

    private void initImage() {

        img_profile = (CircleImageView) findViewById(R.id.img_profile);
        img_profile_square = (ImageView) findViewById(R.id.img_profile_square);
        img_profile_square.setOnClickListener(this);
    }

    private void setOfflineText() {

        collapsingToolbar.setTitle(getResources().getString(R.string.no_internet_connection));

        //Gender
        txtGender.setText(getResources().getString(R.string.not_available));

        //txtBirthDate
        txtBirthDate.setText(getResources().getString(R.string.not_available));

        //txtMobile
        txtMobile.setText(getResources().getString(R.string.not_available));

        //txtEmail
        txtEmail.setText(getResources().getString(R.string.not_available));

        //StreetAddress
        txtStreetAddress.setText(getResources().getString(R.string.not_available));

        //Area
        txtArea.setText(getResources().getString(R.string.not_available));

        //Pincode
        txtPincode.setText(getResources().getString(R.string.not_available));

        //DrivingLicenseId

        txtDrivingLicenseId.setText(getResources().getString(R.string.not_available));

        //LicenseExpDate

        txtLicenseExpDate.setText(getResources().getString(R.string.not_available));

        //PanNumber
        txtPanNumber.setText(getResources().getString(R.string.not_available));

        //AadharNumber

        txtAadharNumber.setText(getResources().getString(R.string.not_available));

        //BankAccountNumber

        txtAccountNumber.setText(getResources().getString(R.string.not_available));

        //BankIFSC

        txtIfsc.setText(getResources().getString(R.string.not_available));

        //BankName
        txtBankName.setText(getResources().getString(R.string.not_available));

        //BranchName
        txtBranchName.setText(getResources().getString(R.string.not_available));

        //VehicleRegistrationNumber
        txtVehicleRegistrationNumber.setText(getResources().getString(R.string.not_available));

        //VehicleColor
        txtVehicleColor.setText(getResources().getString(R.string.not_available));

        //VehicleModel
        txtVehicleModel.setText(getResources().getString(R.string.not_available));

        //VehicleType
        txtVehicleType.setText(getResources().getString(R.string.not_available));

    }

    private void getProfileDetails() {
        createProgressDialog(this);
        final String token = SharedPreferencesUtil.getInstance(ActivityProfile.this)
                .getData(SharedPreferencesUtil.TOKEN_KEY);
        final String driver_id = SharedPreferencesUtil.getInstance(ActivityProfile.this)
                .getData(SharedPreferencesUtil.DRIVER_ID);

        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest sr = new StringRequest(POST_MOTHOD_TYPE, MAIN_URL + GET_PROFILE_DETAIL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        dismissProgressDialog();
                        try {
                            Log.d("TAG", response.toString());

                            if (response != null) {
                                JSONObject jsonResponse = new JSONObject(response);
                                String status = jsonResponse.getString("status");
                                String message = jsonResponse.getString("message");
                                String strJsonResponse = jsonResponse.getString("data");
                                JSONObject objResponse = new JSONObject(strJsonResponse);

                                if (status.equals("200")) {
                                    FirstName = objResponse.getString("FirstName");
                                    LastName = objResponse.getString("LastName");
                                    Gender = objResponse.getString("Gender");
                                    DoB = objResponse.getString("DoB");
                                    Mobile = objResponse.getString("Mobile");
                                    Email = objResponse.getString("Email");
                                    StreetAddress = objResponse.getString("StreetAddress");
                                    Area = objResponse.getString("Area");
                                    Pincode = objResponse.getString("Pincode");
                                    State = objResponse.getString("State");
                                    City = objResponse.getString("City");
                                    DrivingLicenseId = objResponse.getString("DrivingLicenseId");
                                    LicenseExpDate = objResponse.getString("LicenseExpDate");
                                    PanNumber = objResponse.getString("PanNumber");
                                    AadharNumber = objResponse.getString("AadharNumber");
                                    BankAccountNumber = objResponse.getString("BankAccountNumber");
                                    BankIFSC = objResponse.getString("BankIFSC");
                                    BankName = objResponse.getString("BankName");
                                    BranchName = objResponse.getString("BranchName");
                                    VehicleRegistrationNumber = objResponse.getString("VehicleRegistrationNumber");
                                    VehicleColor = objResponse.getString("VehicleColor");
                                    VehicleModel = objResponse.getString("VehicleModel");
                                    VehicleType = objResponse.getString("VehicleType");
                                    String ProfileImgPath = objResponse.getString("ProfileImgPath");

                                    setText();
                                    setImage(ProfileImgPath);

                                }

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            myToast(ActivityProfile.this, getResources().getString(R.string.ERROR));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dismissProgressDialog();
                        myToast(ActivityProfile.this, getResources().getString(R.string.ERROR));
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put(DRIVER_ID, driver_id);

                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put(X_API_KEY, API_KEY_VALUE);
                params.put(TOKEN_KEY, token);

                return params;
            }
        };

        sr.setRetryPolicy(new DefaultRetryPolicy(REQUEST_TIME, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(sr);
    }

    private void setImage(String profileImgPath) {
        try {

            Picasso.with(ActivityProfile.this).load(profileImgPath).placeholder(R.drawable.user_place_holder)
                    .resize(250, 250).into(img_profile);
            Picasso.with(ActivityProfile.this).load(profileImgPath).placeholder(R.drawable.user_place_holder)
                    .resize(250, 250).into(img_profile_square);
            //                img_profile.setImageBitmap(Bitmap.createScaledBitmap(resizeAndCropCenter(bitmap, 250, true), 250, 250, false));
            //                img_profile_square.setImageBitmap(Bitmap.createScaledBitmap(resizeAndCropCenter(bitmap, 250, true), 250, 250, false));

        } catch (Exception e) {
            e.printStackTrace();
            Picasso.with(ActivityProfile.this).load(profileImgPath).placeholder(R.drawable.user_place_holder)
                    .resize(250, 250).networkPolicy(NetworkPolicy.OFFLINE).into(img_profile);
            Picasso.with(ActivityProfile.this).load(profileImgPath).placeholder(R.drawable.user_place_holder)
                    .resize(250, 250).networkPolicy(NetworkPolicy.OFFLINE).into(img_profile_square);
        }
    }

    private void setText() {

        collapsingToolbar.setTitle(FirstName + " " + LastName);
        //Gender
        if (Gender.equals("null")) {
            txtGender.setText(getResources().getString(R.string.not_available));
        } else {
            txtGender.setText(Gender);
        }

        //Gender
        if (DoB.equals("null")) {
            txtBirthDate.setText(getResources().getString(R.string.not_available));
        } else {

            txtBirthDate.setText(GetFormatedMonthDateText(DoB));
        }
        //Gender

        if (Mobile.equals("null")) {
            txtMobile.setText(getResources().getString(R.string.not_available));
        } else {
            txtMobile.setText(Mobile);
        }
        //Gender

        if (Email.equals("null")) {
            txtEmail.setText(getResources().getString(R.string.not_available));
        } else {
            txtEmail.setText(Email);
        }
        //StreetAddress
        if (StreetAddress.equals("null")) {
            txtStreetAddress.setText(getResources().getString(R.string.not_available));
        } else {
            txtStreetAddress.setText(StreetAddress + " " + City + " " + State);
        }
        //Area
        if (Area.equals("null")) {
            txtArea.setText(getResources().getString(R.string.not_available));
        } else {
            txtArea.setText(Area);
        }

        //Pincode
        if (Pincode.equals("null")) {
            txtPincode.setText(getResources().getString(R.string.not_available));
        } else {
            txtPincode.setText(Pincode);
        }

        //DrivingLicenseId

        if (DrivingLicenseId.equals("null")) {
            txtDrivingLicenseId.setText(getResources().getString(R.string.not_available));
        } else {
            txtDrivingLicenseId.setText(DrivingLicenseId);
        }

        //LicenseExpDate

        if (LicenseExpDate.equals("null")) {
            txtLicenseExpDate.setText(getResources().getString(R.string.not_available));
        } else {
            txtLicenseExpDate.setText(GetFormatedMonthDateText(LicenseExpDate));
        }

        //PanNumber

        if (PanNumber.equals("null")) {
            txtPanNumber.setText(getResources().getString(R.string.not_available));
        } else {
            txtPanNumber.setText(PanNumber);
        }

        //AadharNumber

        if (AadharNumber.equals("null")) {
            txtAadharNumber.setText(getResources().getString(R.string.not_available));
        } else {
            txtAadharNumber.setText(AadharNumber);
        }

        //BankAccountNumber

        if (BankAccountNumber.equals("null")) {
            txtAccountNumber.setText(getResources().getString(R.string.not_available));
        } else {
            txtAccountNumber.setText(BankAccountNumber);
        }

        //BankIFSC

        if (BankIFSC.equals("null")) {
            txtIfsc.setText(getResources().getString(R.string.not_available));
        } else {
            txtIfsc.setText(BankIFSC);
        }

        //BankName

        if (BankName.equals("null")) {
            txtBankName.setText(getResources().getString(R.string.not_available));
        } else {
            txtBankName.setText(BankName);
        }
        //BranchName

        if (BranchName.equals("null")) {
            txtBranchName.setText(getResources().getString(R.string.not_available));
        } else {
            txtBranchName.setText(BranchName);
        }
        //VehicleRegistrationNumber

        if (VehicleRegistrationNumber.equals("null")) {
            txtVehicleRegistrationNumber.setText(getResources().getString(R.string.not_available));
        } else {
            txtVehicleRegistrationNumber.setText(VehicleRegistrationNumber);
        }

        //VehicleColor

        if (VehicleColor.equals("null")) {
            txtVehicleColor.setText(getResources().getString(R.string.not_available));
        } else {
            txtVehicleColor.setText(VehicleColor);
        }

        //VehicleModel

        if (VehicleModel.equals("null")) {
            txtVehicleModel.setText(getResources().getString(R.string.not_available));
        } else {
            txtVehicleModel.setText(VehicleModel);
        }

        //VehicleType

        if (VehicleType.equals("null")) {
            txtVehicleType.setText(getResources().getString(R.string.not_available));
        } else {
            txtVehicleType.setText(VehicleType);
        }

    }

    private void initTextview() {
        txtGender = (TextView) findViewById(R.id.txtGender);
        txtBirthDate = (TextView) findViewById(R.id.txtBirthDate);
        txtMobile = (TextView) findViewById(R.id.txtMobile);
        txtEmail = (TextView) findViewById(R.id.txtEmail);
        txtStreetAddress = (TextView) findViewById(R.id.txtStreetAddress);
        txtArea = (TextView) findViewById(R.id.txtArea);
        txtPincode = (TextView) findViewById(R.id.txtPincode);
        txtAadharNumber = (TextView) findViewById(R.id.txtAadharNumber);
        txtPanNumber = (TextView) findViewById(R.id.txtPanNumber);
        txtDrivingLicenseId = (TextView) findViewById(R.id.txtDrivingLicenseId);
        txtLicenseExpDate = (TextView) findViewById(R.id.txtLicenseExpDate);
        txtVehicleType = (TextView) findViewById(R.id.txtVehicleType);
        txtVehicleModel = (TextView) findViewById(R.id.txtVehicleModel);
        txtVehicleColor = (TextView) findViewById(R.id.txtVehicleColor);
        txtVehicleRegistrationNumber = (TextView) findViewById(R.id.txtVehicleRegistrationNumber);
        txtBankName = (TextView) findViewById(R.id.txtBankName);
        txtBranchName = (TextView) findViewById(R.id.txtBranchName);
        txtAccountNumber = (TextView) findViewById(R.id.txtAccountNumber);
        txtIfsc = (TextView) findViewById(R.id.txtIfsc);
        txtSelectLanguange = (TextView) findViewById(R.id.txtSelectLanguange);
        txtSelectLanguange.setOnClickListener(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);

    }

    private void setCollapsedTitleTextColor() {
        int currentApi = Integer.valueOf(android.os.Build.VERSION.SDK);
        if (currentApi >= 23) {
            collapsingToolbar
                    .setCollapsedTitleTextColor(ContextCompat.getColor(ActivityProfile.this, R.color.white));
            collapsingToolbar
                    .setExpandedTitleColor(ContextCompat.getColor(ActivityProfile.this, R.color.colorPrimary));
        } else {
            collapsingToolbar.setCollapsedTitleTextColor(getResources().getColor(R.color.white));
            collapsingToolbar.setExpandedTitleColor(getResources().getColor(R.color.colorPrimary));
        }
    }

    private void initToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    private void openDialogSelectLanguange() {
        View lstGroupView = getLayoutInflater().inflate(R.layout.dailog_select_language, null);
        dialogSelectLangunage = new Dialog(this, R.style.MaterialDialogSheet);
        dialogSelectLangunage.setContentView(lstGroupView);
        dialogSelectLangunage.setCancelable(true);
        dialogSelectLangunage.getWindow().setGravity(Gravity.CENTER);
        dialogSelectLangunage.getWindow()
                .setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        btnSave = (Button) dialogSelectLangunage.findViewById(R.id.btnSave);
        btnSave.setOnClickListener(this);

        rdoEnglish = (RadioButton) dialogSelectLangunage.findViewById(R.id.rdoEnglish);
        rdoHindi = (RadioButton) dialogSelectLangunage.findViewById(R.id.rdoHindi);
        rdoMarathi = (RadioButton) dialogSelectLangunage.findViewById(R.id.rdoMarathi);
        getPreviousLanguageSelected();
        rdoEnglish.setOnCheckedChangeListener(this);
        rdoHindi.setOnCheckedChangeListener(this);
        rdoMarathi.setOnCheckedChangeListener(this);
        dialogSelectLangunage.show();
    }

    private void getPreviousLanguageSelected() {

        String langunageType = SharedPreferencesUtil.getInstance(ActivityProfile.this).getData(LANGUAGE_TYPE);
        if (langunageType.equals("") || langunageType.equals("en")) {
            rdoEnglish.setChecked(true);
        } else if (langunageType.equals("hi")) {
            rdoHindi.setChecked(true);
        } else if (langunageType.equals("mr")) {
            rdoMarathi.setChecked(true);

        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.txtSelectLanguange:
            openDialogSelectLanguange();
            break;
        case R.id.btnSave:
            SharedPreferencesUtil.getInstance(getApplicationContext()).putData(LANGUAGE_TYPE, langunageType);
            setLangunageType(ActivityProfile.this);
            recreate();
            dialogSelectLangunage.dismiss();
            break;
        case R.id.img_profile_square:
            selectImage();
            break;
        }
    }

    private void selectImage() {
        final CharSequence[] options = { getResources().getString(R.string.take_photo),
                getResources().getString(R.string.select_from_gallery), getResources().getString(R.string.cancel) };
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);

        builder.setTitle(getResources().getString(R.string.add_photo));

        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals(getResources().getString(R.string.take_photo))) {
                    Boolean isSDPresent = android.os.Environment.getExternalStorageState()
                            .equals(android.os.Environment.MEDIA_MOUNTED);
                    if (isSDPresent) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                        startActivityForResult(intent, 1);
                        //Log.d(TAG, "onClick: " + fileUri);
                        ChnagedUri = fileUri;
                    } else {
                        myToast(ActivityProfile.this,
                                getResources().getString(R.string.insert_an_sd_card_before_using_the_camera));
                    }
                } else if (options[item].equals(getResources().getString(R.string.select_from_gallery))) {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }

        });

        builder.show();
    }

    public Uri getOutputMediaFileUri(int type) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(ActivityProfile.this, BuildConfig.APPLICATION_ID + ".provider",
                    getOutputMediaFile(type));
        } else {
            return Uri.fromFile(getOutputMediaFile(type));
        }
    }

    private static File getOutputMediaFile(int type) {
        File mediaStorageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                IMAGE_DIRECTORY_NAME);
        try {
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create " + IMAGE_DIRECTORY_NAME + " directory");
                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + "/" + "IMG_" + timeStamp + ".jpg");
        } else {
            return null;
        }
        return mediaFile;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == -1) {
                previewCapturedImage();
            }

        } else if (requestCode == 2) {
            Uri selectedImage = data == null ? null : data.getData();
            if (selectedImage != null) {
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                ChnagedUri = Uri.parse("file://" + picturePath);
                previewCapturedImage();
            }
        }
    }

    private void previewCapturedImage() {
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), ChnagedUri);
            if (bitmap != null) {
                ExifInterface ei = null;
                try {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        InputStream in = getContentResolver().openInputStream(ChnagedUri);
                        ei = new ExifInterface(in);
                    } else {
                        ei = new ExifInterface(ChnagedUri.getPath());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (ei != null) {
                    int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                            ExifInterface.ORIENTATION_UNDEFINED);
                    switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        bitmap = rotateImage(bitmap, 90);
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        bitmap = rotateImage(bitmap, 180);
                        break;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        bitmap = rotateImage(bitmap, 270);
                        break;
                    }
                }

                Bitmap imageBitmap;
                imageBitmap = Bitmap.createScaledBitmap(AppUtils.resizeAndCropCenter(bitmap, 250, true), 250, 250,
                        false);
                img_profile_square.setImageBitmap(imageBitmap);

                imagebaseProfilephoto = Generic.convertBitmapToByteStrem(imageBitmap);
                task = new ActivityProfile.UpdateProfilePhotoTask();
                task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
            }
        } catch (IOException e) {
            e.printStackTrace();
            //Set default image here
        }
    }

    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;
    }

    private class UpdateProfilePhotoTask extends AsyncTask<Object, Object, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progress = new ProgressDialog(ActivityProfile.this);
            progress.setMessage(getResources().getString(R.string.uploading_profile_picture));
            progress.setCancelable(false);
            progress.show();
        }

        @Override
        protected String doInBackground(Object... voids) {

            Networking req = new Networking();
            String response = "";
            try {
                requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("DriverId",
                                SharedPreferencesUtil.getInstance(ActivityProfile.this)
                                        .getData(SharedPreferencesUtil.DRIVER_ID))
                        .addFormDataPart("ImageData", imagebaseProfilephoto).addFormDataPart("OldImageName", "")
                        .build();

            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "doInBackground: error");
                requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("DriverId",
                                SharedPreferencesUtil.getInstance(ActivityProfile.this)
                                        .getData(SharedPreferencesUtil.DRIVER_ID))
                        .addFormDataPart("ImageData", "").addFormDataPart("OldImageName", "").build();
            }
            try {
                response = req.doPostRequest(Web.UPDATE_PROFILE_PHOTO, requestBody, ActivityProfile.this);

                Log.d(TAG, "driver_id:" + SharedPreferencesUtil.getInstance(ActivityProfile.this)
                        .getData(SharedPreferencesUtil.DRIVER_ID));

            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (progress != null && progress.isShowing()) {
                progress.dismiss();
            }
            if (result != null && !result.isEmpty()) {
                try {
                    JSONObject jObjResult = new JSONObject(result);
                    message = jObjResult.getString("message");
                    ProfileImgPath = jObjResult.getString("profileImgPath");
                    if (jObjResult.getString("status").equals("200")) {
                        Toast.makeText(ActivityProfile.this, message, Toast.LENGTH_SHORT).show();
                        SharedPreferencesUtil.getInstance(getApplicationContext())
                                .putData(UtilsConstants.PROFILE_IMAGE, ProfileImgPath);
                    } else if (jObjResult.getString("status").equals("203")) {
                        Toast.makeText(ActivityProfile.this, message, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(ActivityProfile.this, getResources().getString(R.string.ERROR),
                            Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(ActivityProfile.this, getResources().getString(R.string.TRY_AGAIN),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
        case R.id.rdoEnglish:
            if (isChecked) {
                PreferenceManager.getDefaultSharedPreferences(ActivityProfile.this).edit().putString("LANG", "en")
                        .apply();
                langunageType = "en"; // english
            }
            break;
        case R.id.rdoHindi:
            if (isChecked) {
                PreferenceManager.getDefaultSharedPreferences(ActivityProfile.this).edit().putString("LANG", "hi")
                        .apply();
                langunageType = "hi"; // Hindi
            }
            break;
        case R.id.rdoMarathi:
            if (isChecked) {
                PreferenceManager.getDefaultSharedPreferences(ActivityProfile.this).edit().putString("LANG", "mr")
                        .apply();
                langunageType = "mr"; // Marathi
            }
            break;
        }
    }
}