Sunday 12 February 2017

My application with sliding menu

1)activity
package com.credencys.myapplication.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;

import com.credencys.myapplication.MyApplication;
import com.credencys.myapplication.R;
import com.credencys.myapplication.api.ApiResponseListener;
import com.credencys.myapplication.api.RestClient;
import com.credencys.myapplication.database.DbHelper;
import com.credencys.myapplication.interfaces.LocationUpdateListener;
import com.credencys.myapplication.utility.CustomDialog;
import com.credencys.myapplication.utility.MyLog;
import com.credencys.myapplication.utility.PermissionUtil;
import com.credencys.myapplication.utility.PrefHelper;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;

import retrofit2.Call;
import retrofit2.Response;

/** * Created by manisha on 24/1/17. */
public class BaseActivity extends AppCompatActivity implements ApiResponseListener, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    //Location get Related variables    private static final int REQUEST_CODE_RECOVER_PLAY_SERVICES = 2000;
    private static final int REQUEST_CHECK_SETTINGS = 2001;
    private static final int REQ_PERMISSION_LOCATION = 1001;
    private GoogleApiClient mGoogleApiClient;
    //private Location mLastLocation;    private LocationRequest mLocationRequest;
    LocationUpdateListener locationUpdateListener;
    public RestClient restClient;
    public MyApplication appInstance;
    public DbHelper dbHelper;
    private LocationSettingsRequest.Builder builder;

    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        appInstance = (MyApplication) getApplication();
        restClient = appInstance.getRestClient();

        dbHelper = appInstance.getDbInstance();
    }

    /**     * Get current location using FusedLocationProviderApi.     * on location found it will called onLocationChanged() of current activity     *     * @param locationUpdateListener     */    public void getCurrentLocation(LocationUpdateListener locationUpdateListener) {
        this.locationUpdateListener = locationUpdateListener;
        if (checkLocationPermission()) {
            //Connect Google API client            if (checkGooglePlayServices()) {
                /**Note: This dialog is hide at onLocationChanged() and onAcitvityResult(When user cancel request of enable GPS)*/                //customDialog.show(getActivity(),getString(R.string.txtLoadingFindingLocation),false);                CustomDialog.getInstance().show(this, getString(R.string.msgGettingLocation), false);
                buildGoogleApiClient();
                //prepare connection request                createLocationRequest();
            }
        }
    }

    /**     * Initialize Google API Client     */    protected synchronized void buildGoogleApiClient() {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            onConnected(new Bundle());
        } else {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
        }
    }

    /*Maker location update request*/    protected void startLocationUpdates() {
        if (checkLocationPermission()) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    /**     * Initialize location request     */    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(20000);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        settingsRequest();
    }

    private boolean checkLocationPermission() {
        // Check if the Location permission is already available.        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // Location permission has not been granted.            requestLocationPermission();
        } else {
            // Location permissions is already available, show the camera preview.            return true;
        }
        return false;
    }

    /**     * Requests the Location permission.     * If the permission has been denied previously, a SnackBar will prompt the user to grant the     * permission, otherwise it is requested directly.     */    private void requestLocationPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                REQ_PERMISSION_LOCATION);
    }

    /**     * GPS is disable show setting dialog to enabled     */    private void settingsRequest() {
        builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient
        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location                        // requests here.                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user                        // a dialog.                        try {
                            // Show the dialog by calling startResolutionForResult(),                            // and check the result in onActivityResult().                            status.startResolutionForResult(BaseActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the                        // settings so we won't show the dialog.                        break;
                }
            }
        });
    }

    /**     * Stop Location update listener     */    private void stopLocationUpdates() {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override    public void onConnected(@Nullable Bundle bundle) {
        if(checkLocationPermission())
        {
            startLocationUpdates();
        }
    }

    @Override    public void onConnectionSuspended(int i) {

    }

    @Override    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override    public void onLocationChanged(Location location) {
        MyLog.v("LocationManager", "onLocationChanged(): Latitude:" + location.getLatitude() + "Longitude: " + location.getLongitude());

        // TODO Temporary store lat-lng into preference        double latitude = PrefHelper.getDouble(getString(R.string.prefUserLatitude), 0);
        double longitude = PrefHelper.getDouble(getString(R.string.prefUserLongitude), 0);
        if (latitude > 0 && longitude > 0) {
            Location endPoint = new Location("locationA");
            endPoint.setLatitude(latitude);
            endPoint.setLongitude(longitude);

            double distance = location.distanceTo(endPoint);
            MyLog.v("LocationManager", "Prev lat-lng and current Distance(In Meter): " + distance);
        }

        PrefHelper.setDouble(getString(R.string.prefUserLatitude), location.getLatitude());
        PrefHelper.setDouble(getString(R.string.prefUserLongitude), location.getLongitude());

        updateLocation(location);
        stopLocationUpdates();
    }

    @Override    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            // Check for the integer request code originally supplied to startResolutionForResult().            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        startLocationUpdates();
                        break;

                    case Activity.RESULT_CANCELED:
                        // User cancel enable GPS                        CustomDialog.getInstance().hide();
                        if (locationUpdateListener != null)
                            locationUpdateListener.onGPSRequestDeny();
                        break;
                }
                break;
        }
    }

    /**     * Callback received when a permissions request has been completed.     */    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQ_PERMISSION_LOCATION) {
            if (PermissionUtil.verifyPermissions(grantResults)) {
                //Connect Google API client                if (checkGooglePlayServices()) {
                    buildGoogleApiClient();
                    //prepare connection request                    createLocationRequest();
                }
            } else {
                // Permission deny                if (locationUpdateListener != null)
                    locationUpdateListener.onLocationPermissionDeny();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private boolean checkGooglePlayServices() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int result = googleAPI.isGooglePlayServicesAvailable(this);
        if (result != ConnectionResult.SUCCESS) {
            if (googleAPI.isUserResolvableError(result)) {
                googleAPI.getErrorDialog(this, result,
                        REQUEST_CODE_RECOVER_PLAY_SERVICES).show();
            }
            return false;
        }
        return true;
    }

    private void updateLocation(Location location) {
        // Hide Dialog which is show on getCurrentLocation()        CustomDialog.getInstance().hide();

        if (locationUpdateListener != null)
            locationUpdateListener.onLocationUpdate(location);
    }

    @Override    public void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    @Override    public void onStop() {
        super.onStop();

        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override    public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) {

    }

    @Override    public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position) {

    }

    @Override    public void onApiError(Call<Object> call, Object object, int reqCode) {

    }
}

2)Home activity.java
====================
package com.credencys.myapplication.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.credencys.myapplication.MyApplication;
import com.credencys.myapplication.R;
import com.credencys.myapplication.adapter.SlidingMenuAdapter;
import com.credencys.myapplication.fragment.DashBoardFragment;
import com.credencys.myapplication.fragment.ExpandViewFragment;
import com.credencys.myapplication.fragment.LatestUpdateFragment;
import com.credencys.myapplication.fragment.LoginFragment;
import com.credencys.myapplication.fragment.MyGalleryFragment;
import com.credencys.myapplication.fragment.NearByLocationFragment;
import com.credencys.myapplication.fragment.ProfileFragment;
import com.credencys.myapplication.interfaces.BackPressedEventListener;
import com.credencys.myapplication.interfaces.ClickEventListener;
import com.credencys.myapplication.interfaces.RecyclerViewItemClickListener;
import com.credencys.myapplication.models.LoginModel;
import com.credencys.myapplication.utility.PrefHelper;
import com.credencys.myapplication.utility.Utils;
import com.credencys.myapplication.widgets.ShapedImageView;

/** * Created by manisha on 24/1/17. */
public class HomeActivity extends BaseActivity {
    DrawerLayout drawerLayout;
    public FragmentManager fragmentManager;
    public Fragment currentFragment;
    BackPressedEventListener backPressedEventListener;
    ClickEventListener clickEventListener;
    public LoginModel loginModel;
    RecyclerView recyclerViewSlidingMenu;
    SlidingMenuAdapter slidingMenuAdapter;

    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        init();
    }

    private void init() {
        try {
            fragmentManager = getSupportFragmentManager();
            initSlidingMenu();
            setupSlidingMenuData(loginModel);
            pushFragments(new LoginFragment(), false, false, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initSlidingMenu() {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
            public void onDrawerClosed(View view) {
                supportInvalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                supportInvalidateOptionsMenu();
            }

            @Override            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);

                if (drawerLayout.isDrawerVisible(GravityCompat.START) || drawerLayout.isDrawerVisible(Gravity.LEFT)) {
                    drawerLayout.bringChildToFront(drawerView);
                    drawerLayout.requestLayout();
                }
            }
        };
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        toggle.setDrawerIndicatorEnabled(true);
    }

    public void setupSlidingMenuData(final LoginModel loginModel) {
        //Set Logged in user data        if (loginModel != null) {
            ShapedImageView imageUser = (ShapedImageView) findViewById(R.id.sliding_menu_image_user);
            TextView txtUserName = (TextView) findViewById(R.id.sliding_menu_txt_user_name);
            txtUserName.setText(Utils.getInstance().unescapeJava(loginModel.getFirstName() + " " + loginModel.getLastName()));

            Glide.with(this)
                    .load(loginModel.getUserImage())
                    .placeholder(R.mipmap.ic_default_profile)
                    .into(imageUser);
        }

        recyclerViewSlidingMenu = (RecyclerView) findViewById(R.id.sliding_menu_recycler_view_sliding_menu);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerViewSlidingMenu.setLayoutManager(layoutManager);

        String arrayMenuItems[] = getResources().getStringArray(R.array.menu_items);
        TypedArray arrayIcons = getResources().obtainTypedArray(R.array.menu_icons);

        slidingMenuAdapter = new SlidingMenuAdapter(this, arrayMenuItems, arrayIcons, 0);
        recyclerViewSlidingMenu.setAdapter(slidingMenuAdapter);

        recyclerViewSlidingMenu.addOnItemTouchListener(
                new RecyclerViewItemClickListener(HomeActivity.this, new RecyclerViewItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, final int position) {
                        setSelectedPositionInSlidingMenu(position);

                        switch (position) {
                            case 0: // Dashboard                                toggleSlidingMenu();

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        removeAllFragment();

                                        DashBoardFragment mDashBoardFragment = new DashBoardFragment();
                                        Bundle bundle = new Bundle();
                                        bundle.putString(getResources().getString(R.string.extraFromScreen),getResources().getString(R.string.extraMenu));
                                        mDashBoardFragment.setArguments(bundle);
                                        pushFragments(mDashBoardFragment, false, false, true);
                                    }
                                }, getResources().getInteger(R.integer.drawerAnimationDuration));
                                break;

                            case 1: //Latest Update                                toggleSlidingMenu();

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        removeAllFragment();

                                        LatestUpdateFragment mLatestUpdateFragment = new LatestUpdateFragment();
                                        Bundle bundle = new Bundle();
                                        bundle.putString(getResources().getString(R.string.extraFromScreen),getResources().getString(R.string.extraMenu));
                                        mLatestUpdateFragment.setArguments(bundle);
                                        pushFragments(mLatestUpdateFragment, false, false, true);
                                    }
                                }, getResources().getInteger(R.integer.drawerAnimationDuration));
                                break;

                            case 2: // Near by location                                toggleSlidingMenu();

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        removeAllFragment();

                                        NearByLocationFragment mNearByLocationFragment = new NearByLocationFragment();
                                        Bundle bundle = new Bundle();
                                        bundle.putString(getResources().getString(R.string.extraFromScreen),getResources().getString(R.string.extraMenu));
                                        mNearByLocationFragment.setArguments(bundle);
                                        pushFragments(mNearByLocationFragment, false, false, true);
                                    }
                                }, getResources().getInteger(R.integer.drawerAnimationDuration));

                                break;

                            case 3: //ExpandView                                toggleSlidingMenu();

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        removeAllFragment();

                                        ExpandViewFragment mCategoryThreeFragment = new ExpandViewFragment();
                                        Bundle bundle = new Bundle();
                                        bundle.putString(getResources().getString(R.string.extraFromScreen),getResources().getString(R.string.extraMenu));
                                        mCategoryThreeFragment.setArguments(bundle);
                                        pushFragments(mCategoryThreeFragment, false, false, true);
                                    }
                                }, getResources().getInteger(R.integer.drawerAnimationDuration));
                                break;

                            case 4: //My Gallery                                toggleSlidingMenu();

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        removeAllFragment();

                                        MyGalleryFragment mCategoryFourFragment = new MyGalleryFragment();
                                        Bundle bundle = new Bundle();
                                        bundle.putString(getResources().getString(R.string.extraFromScreen),getResources().getString(R.string.extraMenu));
                                        mCategoryFourFragment.setArguments(bundle);
                                        pushFragments(mCategoryFourFragment, false, false, true);
                                    }
                                }, getResources().getInteger(R.integer.drawerAnimationDuration));

                                break;

                            case 5: // logout                                toggleSlidingMenu();

                                showLogoutAlert();
                                break;
                        }
                    }
                })
        );
    }

    public void setSelectedPositionInSlidingMenu(int position) {
        if (slidingMenuAdapter != null)
            slidingMenuAdapter.setItemSelected(position);
    }

    /**     * Toggle sliding menu     */    public void toggleSlidingMenu() {
        if (isSlidingMenuOpen()) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            drawerLayout.openDrawer(GravityCompat.START);
        }
    }

    public void setSlidingMenuEnable(boolean enable) {
        if (enable)
            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        else            drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    /**     * Return true if sliding menu is open otherwise return false     */    public boolean isSlidingMenuOpen() {
        if (drawerLayout != null && drawerLayout.isDrawerOpen(GravityCompat.START))
            return true;
        return false;
    }

    /**     * Replace fragment     */    public void pushFragments(Fragment fragment, boolean shouldAnimate, boolean isReverse, boolean shouldAddBackStack) {
        try {
            clickEventListener = (ClickEventListener) fragment;
            backPressedEventListener = (BackPressedEventListener) fragment;
            FragmentTransaction ft = fragmentManager.beginTransaction();
            currentFragment = fragment;

            if (shouldAnimate) {
                if (!isReverse) {
                    ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);
                } else                    ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_left, R.anim.slide_out_right);
            }

            // Create Unique Fragment tag name            String fragmentTag = fragment.getClass().getName() + System.currentTimeMillis();
            ft.replace(R.id.activity_home_container, fragment, fragmentTag);
            if (shouldAddBackStack)
                ft.addToBackStack(fragmentTag);
            ft.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void popFragment() {
        try {
            int backStackCount = fragmentManager.getBackStackEntryCount();
            if (backStackCount > 1) {
                FragmentManager.BackStackEntry backEntry = fragmentManager.getBackStackEntryAt(backStackCount - 2);
                String str = backEntry.getName();
                Fragment fragment = fragmentManager.findFragmentByTag(str);

                backPressedEventListener = (BackPressedEventListener) fragment;
                clickEventListener = (ClickEventListener) fragment;
                currentFragment = fragment;
                fragmentManager.popBackStack();

            } else {
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*Remove all fragments from back stack*/    public void removeAllFragment() {
        int fragmentsCount = fragmentManager.getBackStackEntryCount();

        if (fragmentsCount > 0) {
            MyApplication.DISABLE_FRAGMENT_ANIMATION = true;
            FragmentTransaction ft = fragmentManager.beginTransaction();

            fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            ft.commit();

            MyApplication.DISABLE_FRAGMENT_ANIMATION = false;
        }
    }

    public void clickEvent(View view) {
        switch (view.getId()) {
            case R.id.sliding_menu_lyt_profile:
                toggleSlidingMenu();

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ProfileFragment myProfileFragment = new ProfileFragment();
                        pushFragments(myProfileFragment, false, false, true);
                    }
                }, getResources().getInteger(R.integer.drawerAnimationDuration));
                break;

            default:
                if (clickEventListener != null)
                    clickEventListener.clickEvent(view);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (backPressedEventListener != null)
            backPressedEventListener.onBackPressed();
    }

    // Show Logout alert dialog    public void showLogoutAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
        builder.setCancelable(true);
        builder.setMessage(getString(R.string.msgLogoutAlert));
        builder.setPositiveButton(getString(R.string.btnYes),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                        PrefHelper.setBoolean(getResources().getString(R.string.is_login),false);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                removeAllFragment();
                                pushFragments(new LoginFragment(), false, false, true);
                            }
                        }, getResources().getInteger(R.integer.drawerAnimationDuration));
                    }
                });
        builder.setNegativeButton(getString(R.string.btnNo),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                    }
                });

        // create alert dialog        AlertDialog alertDialog = builder.create();
        // show it        alertDialog.show();
    }
}

3)ImageCropActivity.java
=========================
package com.credencys.myapplication.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.credencys.myapplication.R;
import com.credencys.myapplication.utility.MyLog;
import com.credencys.myapplication.utility.ToastHelper;
import com.credencys.myapplication.widgets.CropImageView;

/** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */public class ImageCropActivity extends AppCompatActivity implements CropImageView.OnSetImageUriCompleteListener, CropImageView.OnGetCroppedImageCompleteListener {
    private int mAspectRatioX;//DEFAULT_ASPECT_RATIO_VALUES;    private int mAspectRatioY;//DEFAULT_ASPECT_RATIO_VALUES;    private static final String ASPECT_RATIO_X = "ASPECT_RATIO_X";
    private static final String ASPECT_RATIO_Y = "ASPECT_RATIO_Y";
    private CropImageView mIvCropView;
    private Uri imageUri;
    public static String EXTRA_IMAGE_URI="imageURI",EXTRA_X_RATIO="xratio",EXTRA_Y_RATIO="yratio";

    @Override    protected void onSaveInstanceState(@SuppressWarnings("NullableProblems") Bundle bundle) {
        super.onSaveInstanceState(bundle);
        bundle.putInt(ASPECT_RATIO_X, mAspectRatioX);
        bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY);
    }

    // Restores the state upon rotating the screen/restarting the activity    @Override    protected void onRestoreInstanceState(@SuppressWarnings("NullableProblems") Bundle bundle) {
        super.onRestoreInstanceState(bundle);
        mAspectRatioX = bundle.getInt(ASPECT_RATIO_X);
        mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y);
    }

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_image_crop);

        Intent i = getIntent();
        Bundle bundle=i.getExtras();
        if(bundle!=null)
        {
            mAspectRatioX = bundle.getInt(EXTRA_X_RATIO, 16);
            mAspectRatioY = bundle.getInt(EXTRA_Y_RATIO, 26);

            if(bundle.containsKey(EXTRA_IMAGE_URI))
                imageUri= bundle.getParcelable(EXTRA_IMAGE_URI);
        }

        mIvCropView = (CropImageView) findViewById(R.id.activity_image_crop_crop_imageview);
        mIvCropView.setCropShape(CropImageView.CropShape.RECTANGLE);
        mIvCropView.setFixedAspectRatio(true);
        mIvCropView.setAspectRatio(mAspectRatioX, mAspectRatioY);//(DEFAULT_ASPECT_RATIO_VALUES, DEFAULT_ASPECT_RATIO_VALUES);        mIvCropView.setGuidelines(2);
        mIvCropView.setScaleType(ImageView.ScaleType.FIT_CENTER);

        if (imageUri != null)
            mIvCropView.setImageUriAsync(imageUri);

        TextView btnCancel = (TextView) findViewById(R.id.activity_image_crop_btn_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                onBackPressed();
            }
        });
        TextView btnDone = (TextView) findViewById(R.id.activity_image_crop_btn_ok);

        btnDone.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                mIvCropView.getCroppedImageAsync(mIvCropView.getCropShape(), 0, 0);
            }
        });
    }

    @Override    protected void onStart() {
        super.onStart();
        mIvCropView.setOnSetImageUriCompleteListener(this);
        mIvCropView.setOnGetCroppedImageCompleteListener(this);
    }

    @Override    protected void onStop() {
        super.onStop();
        mIvCropView.setOnSetImageUriCompleteListener(null);
        mIvCropView.setOnGetCroppedImageCompleteListener(null);
    }

    @Override    public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) {
        if (error == null) {
            MyLog.e("IMAGE CROP", "IMAGE uri: : " + uri + " PATH : " + uri.getPath());
        } else {
            ToastHelper.getInstance().showToast(this,getString(R.string.msgFailedToLoadImage));
        }
    }

    @Override    public void onGetCroppedImageComplete(CropImageView view, Bitmap bitmap, Exception error) {
        if (error == null) {
            Intent intent=new Intent();
            intent.putExtra(EXTRA_IMAGE_URI,imageUri);
            setResult(RESULT_OK,intent);
            finish();

        } else {
            ToastHelper.getInstance().showToast(this,getString(R.string.msgImageCropFailed));
        }
    }

    @Override    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override    public void onBackPressed() {
        ImageCropActivity.this.finish();
    }
}

* Adapters
==========
1)ExpandViewAdapter.java
========================
package com.credencys.myapplication.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.credencys.myapplication.R;
import com.credencys.myapplication.models.ExpandViewModel;

import java.util.ArrayList;

/** * Created by manisha on 2/2/17. */
public class ExpandViewAdapter extends RecyclerView.Adapter<ExpandViewAdapter.CustomViewHolder> {
    private Context mContext;
    private ArrayList<ExpandViewModel> alstExpand;

    public ExpandViewAdapter(Context mContext, ArrayList<ExpandViewModel> alstExpand) {
        this.alstExpand = alstExpand;
        this.mContext = mContext;
    }

    @Override    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_expand_view, null);

        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
    }
    
    @Override    public void onBindViewHolder(final CustomViewHolder holder, int position) {

       holder.txtTitle.setText(alstExpand.get(position).getTitle());
        holder.lytExapandView.setTag(alstExpand.get(position));
        Glide.with(mContext)
                .load(alstExpand.get(position).getImgId())
                .placeholder(R.mipmap.expandview_default_image)
                .error(R.mipmap.expandview_default_image)
                .into(holder.imgExpand);

        if(alstExpand.get(position).isChecked){
            holder.txtDescription.setText(alstExpand.get(position).getDescription());
                holder.txtDescription.setMaxLines(Integer.MAX_VALUE);
                holder.txtDescription.setVisibility(View.VISIBLE);
        }else{
            holder.txtDescription.setText(alstExpand.get(position).getDescription());
            holder.txtDescription.setMaxLines(2);
        }
    }

    @Override    public int getItemCount() {
          return alstExpand.size();
    }

    public class CustomViewHolder extends RecyclerView.ViewHolder {
        private ImageView imgExpand;
        private LinearLayout lytExapandView;
        private TextView txtTitle,txtDescription;

        public CustomViewHolder(View itemView) {
            super(itemView);

            imgExpand = (ImageView)itemView.findViewById(R.id.list_item_expand_view_imageview);
            txtTitle = (TextView) itemView.findViewById(R.id.list_item_expand_view_title);
            txtDescription = (TextView)itemView.findViewById(R.id.list_item_expand_view_description);
            lytExapandView = (LinearLayout)itemView.findViewById(R.id.list_item_expand_view_lytmain);
        }
    }
}

2) LatestUpdateCategoryAdapter.java
===================================
package com.credencys.myapplication.adapter;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.credencys.myapplication.R;
import com.credencys.myapplication.models.LatestUpdateCategoryModel;
import com.credencys.myapplication.utility.ToastHelper;
import com.credencys.myapplication.utility.Utils;

import java.util.ArrayList;

/** * Created by manisha on 14/12/16. */
public class LatestUpdateCategoryAdapter extends RecyclerView.Adapter<LatestUpdateCategoryAdapter.CustomViewHolder> {
    private Context mContext;
    private ArrayList<LatestUpdateCategoryModel.Items> alstLatestUpdate;

    public LatestUpdateCategoryAdapter(Context mContext, ArrayList<LatestUpdateCategoryModel.Items> alstLatestUpdate) {
        this.alstLatestUpdate = alstLatestUpdate;
        this.mContext = mContext;
    }

    @Override    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_latest_update, parent, false);

        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
    }

    @Override    public void onBindViewHolder(CustomViewHolder holder, int position) {
        String strDesc = alstLatestUpdate.get(position).getDescription();

        /* remove a href tag from description*/        if (Utils.getInstance().validateString(strDesc)) {
            strDesc = strDesc.replaceAll("<a.*?>.*?<\\/a>", "");
        } else {
            strDesc = "";
        }

        if (Build.VERSION.SDK_INT >= 24) {
            if (Utils.getInstance().validateString(alstLatestUpdate.get(position).getTitle())) {
                holder.txtTitlle.setText(Html.fromHtml(alstLatestUpdate.get(position).getTitle(), Html.FROM_HTML_MODE_LEGACY));
            } else {
                holder.txtTitlle.setText("");
            }
            holder.txtDescription.setText(Html.fromHtml(strDesc, Html.FROM_HTML_MODE_LEGACY));
        } else {
            if (Utils.getInstance().validateString(alstLatestUpdate.get(position).getTitle())) {
                holder.txtTitlle.setText(Html.fromHtml(alstLatestUpdate.get(position).getTitle()));
            } else {
                holder.txtTitlle.setText("");
            }
            holder.txtDescription.setText(Html.fromHtml(strDesc));
        }
        holder.lytMain.setTag(alstLatestUpdate.get(position));
        holder.lytMain.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                if(Utils.getInstance().checkInternetConnection(mContext)) {
                    LatestUpdateCategoryModel.Items categoryOneModel = (LatestUpdateCategoryModel.Items) v.getTag();
                    if (Utils.getInstance().validateString(categoryOneModel.getLink())) {
                        dialogLoadWebView(categoryOneModel.getLink());
                    }
                }else{
                    ToastHelper.getInstance().showToast(mContext,mContext.getResources().getString(R.string.msgInternetConnectionNotAvailable));
                }
            }
        });
    }

    public void setListItems(ArrayList<LatestUpdateCategoryModel.Items> alstLatestUpdate) {
        this.alstLatestUpdate = alstLatestUpdate;
        notifyDataSetChanged();
    }

    @Override    public int getItemCount() {
        return alstLatestUpdate.size();
    }

    public class CustomViewHolder extends RecyclerView.ViewHolder {
        private TextView txtTitlle, txtDescription;
        private LinearLayout lytMain;
        private CardView cardView;

        public CustomViewHolder(View itemView) {
            super(itemView);

            txtTitlle = (TextView) itemView.findViewById(R.id.list_item_latest_update_txt_title);
            txtDescription = (TextView) itemView.findViewById(R.id.list_item_latest_update_txt_description);
            lytMain = (LinearLayout) itemView.findViewById(R.id.list_item_latest_update_layout_main);
            cardView = (CardView)itemView.findViewById(R.id.card_view);
        }
    }

    public void dialogLoadWebView(String webUrl) {
        final Dialog dialog = new Dialog(mContext, R.style.DialogTheme);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.dialog_load_web_view);

        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        final ProgressBar progressBar = (ProgressBar)dialog.findViewById(R.id.dialog_load_web_view_progressbar);
        progressBar.setVisibility(View.VISIBLE);
        ImageView imgClose = (ImageView) dialog.findViewById(R.id.dialog_load_web_view_img_close);
        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        WebView webView = (WebView) dialog.findViewById(R.id.dialog_load_web_view);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.loadUrl(webUrl);
        webView.setWebViewClient(new WebViewClient() {
            @Override            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

            }

            @Override            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);

                return true;
            }

            @Override            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.GONE);

            }

            @Override            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                progressBar.setVisibility(View.GONE);
                dialog.dismiss();
                ToastHelper.getInstance().showToast(mContext,mContext.getResources().getString(R.string.msgProblemWithWeview));
            }
        });
        dialog.show();
    }
}

3)MyGalleryAdapter.java
=======================
package com.credencys.myapplication.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.credencys.myapplication.R;
import com.credencys.myapplication.utility.Utils;

import java.util.ArrayList;

/** * Created by manisha on 4/2/17. */
public class MyGalleryAdapter extends RecyclerView.Adapter<MyGalleryAdapter.CustomViewHolder> {
    private Context mContext;
    private ArrayList<String> alstGalleryImages;
    private int[] arrayScreenWH;

    public MyGalleryAdapter(Context mContext, ArrayList<String> alstGalleryImages) {
        this.alstGalleryImages = alstGalleryImages;
        this.mContext = mContext;
        arrayScreenWH=Utils.getInstance().getScreenWidthHeight(mContext);
    }

    @Override    public void onBindViewHolder(final CustomViewHolder holder, int position) {
        LinearLayout.LayoutParams params= (LinearLayout.LayoutParams)holder.rlytGlaleryImage.getLayoutParams();
        int height=arrayScreenWH[0]/3;
        height-=mContext.getResources().getDimensionPixelSize(R.dimen.dp3);
        params.height=height;
        holder.rlytGlaleryImage.setLayoutParams(params);

        holder.imgCapturedImages.setVisibility(View.VISIBLE);
        if (Utils.getInstance().validateString(alstGalleryImages.get(position).toString())) {
            Glide.with(mContext)
                    .load(alstGalleryImages.get(position).toString())
                    .error(R.mipmap.gallery_default_image)
                    .placeholder(R.mipmap.gallery_default_image)
                    .into(holder.imgCapturedImages);
        }

        holder.rlytGlaleryImage.setTag(alstGalleryImages.get(position));
    }

    @Override    public int getItemCount() {
            return alstGalleryImages.size();
    }

    public class CustomViewHolder extends RecyclerView.ViewHolder {
        private ImageView imgCapturedImages;
        private RelativeLayout rlytGlaleryImage;

        public CustomViewHolder(View itemView) {
            super(itemView);

            rlytGlaleryImage = (RelativeLayout)itemView.findViewById(R.id.list_item_my_gallery_rlyt_gallery);
            imgCapturedImages = (ImageView)itemView.findViewById(R.id.list_item_my_gallery_img_gallery);
        }
    }

    @Override    public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_my_gallery, null);

        CustomViewHolder viewHolder = new CustomViewHolder(view);
        return viewHolder;
    }
}

4)PagerAdapterLatestUpdate.java
===============================
package com.credencys.myapplication.adapter;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.credencys.myapplication.R;
import com.credencys.myapplication.fragment.LatestUpdateCategoryFragment;

/** * Created by Manisha on 27-1-17 */
public class PagerAdapterLatestUpdate extends FragmentPagerAdapter {
    Context context;
    String tabNames[];
    LatestUpdateCategoryFragment mLatestUpdateCategoryOneItemFragmentOne, mLatestUpdateCategoryFragmentTwo, mLatestUpdateCategoryFragmentThree, mLatestUpdateCategoryFragmentFour, mLatestUpdateCategoryFragmentFive;

    public PagerAdapterLatestUpdate(Context context, FragmentManager fm) {
        super(fm);
        this.context = context;
        tabNames = context.getResources().getStringArray(R.array.categoryTabNames);
    }

    @Override    public Fragment getItem(int position) {
        switch (position) {

            case 0:
                if (mLatestUpdateCategoryOneItemFragmentOne == null) {
                    mLatestUpdateCategoryOneItemFragmentOne = new LatestUpdateCategoryFragment();
                    Bundle bundle = new Bundle();
                    bundle.putInt(context.getResources().getString(R.string.fragment_position), position);
                    mLatestUpdateCategoryOneItemFragmentOne.setArguments(bundle);
                }
                return mLatestUpdateCategoryOneItemFragmentOne;

            case 1:
                if (mLatestUpdateCategoryFragmentTwo == null) {
                    mLatestUpdateCategoryFragmentTwo = new LatestUpdateCategoryFragment();
                    Bundle bundle = new Bundle();
                    bundle.putInt(context.getResources().getString(R.string.fragment_position), position);
                    mLatestUpdateCategoryFragmentTwo.setArguments(bundle);
                }
                return mLatestUpdateCategoryFragmentTwo;

            case 2:
                if (mLatestUpdateCategoryFragmentThree == null) {
                    mLatestUpdateCategoryFragmentThree = new LatestUpdateCategoryFragment();
                    Bundle bundle = new Bundle();
                    bundle.putInt(context.getResources().getString(R.string.fragment_position), position);
                    mLatestUpdateCategoryFragmentThree.setArguments(bundle);
                }
                return mLatestUpdateCategoryFragmentThree;

            case 3:
                if (mLatestUpdateCategoryFragmentFour == null) {
                    mLatestUpdateCategoryFragmentFour = new LatestUpdateCategoryFragment();
                    Bundle bundle = new Bundle();
                    bundle.putInt(context.getResources().getString(R.string.fragment_position), position);
                    mLatestUpdateCategoryFragmentFour.setArguments(bundle);
                }
                return mLatestUpdateCategoryFragmentFour;

            case 4:
                if (mLatestUpdateCategoryFragmentFive == null) {
                    mLatestUpdateCategoryFragmentFive = new LatestUpdateCategoryFragment();
                    Bundle bundle = new Bundle();
                    bundle.putInt(context.getResources().getString(R.string.fragment_position), position);
                    mLatestUpdateCategoryFragmentFive.setArguments(bundle);
                }
                return mLatestUpdateCategoryFragmentFive;

            default:
                if (mLatestUpdateCategoryOneItemFragmentOne == null) {
                    mLatestUpdateCategoryOneItemFragmentOne = new LatestUpdateCategoryFragment();
                    Bundle bundle = new Bundle();
                    bundle.putInt(context.getResources().getString(R.string.fragment_position), position);
                    mLatestUpdateCategoryOneItemFragmentOne.setArguments(bundle);
                }
                return mLatestUpdateCategoryOneItemFragmentOne;
        }
    }

    @Override    public int getCount() {
        return tabNames.length;
    }

    @Override    public CharSequence getPageTitle(int position) {
        return tabNames[position];
    }
}

5)SlidingMenuAdapter.java
=========================
package com.credencys.myapplication.adapter;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.credencys.myapplication.R;
import com.credencys.myapplication.models.SlidingMenuModel;

/** * Created by Manisha on 27-1-17 */public class SlidingMenuAdapter extends RecyclerView.Adapter<SlidingMenuAdapter.ViewHolder> {
    private TypedArray arrayIcons,arrayIconsSelected;
    private String arrayItems[];
    private int selectedPosition;
    private Context mContext;

    public SlidingMenuAdapter(Context context, String arrayItems[], TypedArray arrayImages, int selectedPosition) {
        this.mContext = context;
        this.arrayItems = arrayItems;
        this.arrayIcons = arrayImages;
        this.selectedPosition=selectedPosition;
        this.arrayIconsSelected=context.getResources().obtainTypedArray(R.array.menu_icons_selected);
    }

    public void setItemSelected(int pos)
    {
        selectedPosition = pos;
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder
    {
        public SlidingMenuModel mBoundString;
        ImageView imgMenuIcon;
        TextView txtMenuItem;
        View dividerMenu;

        public ViewHolder(View view)
        {
            super(view);
            txtMenuItem = (TextView) view.findViewById(R.id.menu_list_icon_txt_item);
            imgMenuIcon = (ImageView) view.findViewById(R.id.menu_list_icon_img_icon);
            dividerMenu = view.findViewById(R.id.menu_list_icon_devider_menu);
        }

        @Override        public String toString() {
            return super.toString() + " '" + txtMenuItem.getText();
        }
    }

    @Override    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_list_item, parent, false);
        return new ViewHolder(view);
    }

    @Override    public void onBindViewHolder(final ViewHolder holder, int position)
    {
        holder.txtMenuItem.setText(arrayItems[position]);
        if(position == selectedPosition)
        {
            holder.txtMenuItem.setTextColor(ContextCompat.getColor(mContext,R.color.menu_selected_color));
            Glide.with(mContext)
                    .load(arrayIconsSelected.getResourceId(position, -1))
                    .into(holder.imgMenuIcon);
        }
        else        {
            holder.txtMenuItem.setTextColor(ContextCompat.getColor(mContext,R.color.white));
            Glide.with(mContext)
                    .load(arrayIcons.getResourceId(position, -1))
                    .into(holder.imgMenuIcon);
        }

        if(position!=arrayItems.length-1)
            holder.dividerMenu.setVisibility(View.VISIBLE);
        else            holder.dividerMenu.setVisibility(View.GONE);
    }

    @Override    public int getItemCount() {
        return arrayItems.length;
    }
}

*api

1)ApiResponseListener.java
=========================
package com.credencys.myapplication.api;

import retrofit2.Call;
import retrofit2.Response;

public interface ApiResponseListener {
    /**Call on success API response with request code*/    void onApiResponse(Call<Object> call, Response<Object> response, int reqCode);
    /**Call on success API response with request code and passed position*/    void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position);
    /**Call on error of API with request code */    void onApiError(Call<Object> call, Object object, int reqCode);
}

2)ErrorUtils.java
=================
package com.credencys.myapplication.api;

import java.lang.annotation.Annotation;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Response;

public class ErrorUtils {
    public static APIError parseError(Response<?> response) {
        Converter<ResponseBody, APIError> converter = RestClient.retrofit().responseBodyConverter(APIError.class, new Annotation[0]);

        APIError error=null;
        try {
            error = converter.convert(response.errorBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return error;
    }
}

3)MyAppAPI.java
package com.credencys.myapplication.api;

import com.credencys.myapplication.models.LatestUpdateCategoryModel;
import com.credencys.myapplication.models.NearByLocationModel;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface MyAppAPI {

    @GET("api.json?rss_url=http%3A%2F%2Ftimesofindia.indiatimes.com%2Frssfeedstopstories.cms")
    Call<LatestUpdateCategoryModel> getTopStory();

    @GET("api.json?rss_url=http%3A%2F%2Ftimesofindia.indiatimes.com%2Frssfeeds%2F4719161.cms")
    Call<LatestUpdateCategoryModel> getCricketData();

    @GET("api.json?rss_url=http%3A%2F%2Ftimesofindia.indiatimes.com%2Frssfeeds%2F1898055.cms")
    Call<LatestUpdateCategoryModel> getBusinessData();

    @GET("api.json?rss_url=http%3A%2F%2Ftimesofindia.indiatimes.com%2Frssfeeds%2F5880659.cms")
    Call<LatestUpdateCategoryModel> getTechnology();

    @GET("api.json?rss_url=http%3A%2F%2Ftimesofindia.indiatimes.com%2Frssfeeds%2F2886704.cms")
    Call<LatestUpdateCategoryModel> getLifestyleData();

    @GET("nearbysearch/json")
    Call<NearByLocationModel> getNearByLocation(@Query("location") String location, @Query("rankby") String rankby, @Query("types") String types, @Query("key") String key);

}

4)RestClient.java
=================
package com.credencys.myapplication.api;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;

import com.credencys.myapplication.BuildConfig;
import com.credencys.myapplication.R;
import com.credencys.myapplication.utility.CustomDialog;
import com.credencys.myapplication.utility.MyLog;
import com.credencys.myapplication.utility.ToastHelper;
import com.credencys.myapplication.utility.Utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RestClient {
    private static String TAG = RestClient.class.getName();
    private static MyAppAPI API_CLIENT;
    static Retrofit retrofit;
    Context context;
    private static int TIME_OUT_DURATION = 60; // Seconds
    public RestClient(Context context) {
        this.context = context;
    }

    public static MyAppAPI getApiClient() {
        return API_CLIENT;
    }

    public void setupRestClient(final Context context) {
        OkHttpClient.Builder builderOkHttp = new OkHttpClient.Builder();
        builderOkHttp.connectTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS);
        builderOkHttp.readTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS);
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builderOkHttp.networkInterceptors().add(httpLoggingInterceptor);

        builderOkHttp.networkInterceptors().add(new Interceptor() {
            @Override            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder()
                        .addHeader("Content-Type", "application/json")
                        .build();
                return chain.proceed(request);
            }
        });

        OkHttpClient client = builderOkHttp.build();
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .create();

        retrofit = new Retrofit.Builder()
                .baseUrl(context.getString(R.string.baseURL))
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();
        API_CLIENT = retrofit.create(MyAppAPI.class);
    }

    public void setupMapRestClient(final Context context) {
        OkHttpClient.Builder builderOkHttp = new OkHttpClient.Builder();
        builderOkHttp.connectTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS);
        builderOkHttp.readTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS);
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builderOkHttp.networkInterceptors().add(httpLoggingInterceptor);

        builderOkHttp.networkInterceptors().add(new Interceptor() {
            @Override            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder()
                        .addHeader("Content-Type", "application/json")
                        .build();
                return chain.proceed(request);
            }
        });

        OkHttpClient client = builderOkHttp.build();
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .create();

        retrofit = new Retrofit.Builder()
                .baseUrl(context.getString(R.string.baseMapURL))
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();
        API_CLIENT = retrofit.create(MyAppAPI.class);
    }

    public static Retrofit retrofit() {
        return retrofit;
    }

    @SuppressWarnings("unchecked")
    public void makeApiRequest(final Activity activity, Object call, final ApiResponseListener apiResponseListener, final int reqCode,String msg, boolean showProgressDialog) {
        try {
            if (Utils.getInstance().checkInternetConnection(activity)) {
                if (showProgressDialog)
                    CustomDialog.getInstance().show(activity,msg,false);

                final Call<Object> objectCall = (Call<Object>) call;
                objectCall.enqueue(new Callback<Object>() {
                    @Override                    public void onResponse(Call<Object> call, retrofit2.Response<Object> response) {
                        CustomDialog.getInstance().hide();

                        /** Returns true if code() is in the range [200..300). */                        if (response.isSuccessful()) {
                            MyLog.v(TAG, "onResponse - Success : " + response.body());

                            if (shouldCallCallback(apiResponseListener))
                                apiResponseListener.onApiResponse(call, response, reqCode);

                        } else {
                            if (response.message() != null && shouldCallCallback(apiResponseListener))
                                apiResponseListener.onApiError(call, response.message(), reqCode);

                            /*Note: This error log is only for developer. Where developer identify exact API error*/                            if (BuildConfig.DEBUG) {
                                APIError error = ErrorUtils.parseError(response);
                                if (error != null)
                                    MyLog.e(TAG, "error message: " + error.message());
                            }
                        }
                    }

                    @Override                    public void onFailure(Call<Object> call, Throwable t) {
                        //there is more than just a failing request (like: no internet connection)                        MyLog.e(TAG, "onFailure - Fail : " + t.getMessage());
                        CustomDialog.getInstance().hide();

                        if (t instanceof ConnectException || t instanceof SocketTimeoutException) {
                            //Displaying no network connection error                            if (shouldCallCallback(apiResponseListener))
                                apiResponseListener.onApiError(call, activity.getString(R.string.msgInternetConnectionNotAvailable), reqCode);
                        } else {
                            if (shouldCallCallback(apiResponseListener))
                                apiResponseListener.onApiError(call, activity.getString(R.string.msgProblemWithRequest), reqCode);
                        }
                    }
                });
            } else {
                ToastHelper.getInstance().showToast(activity, activity.getString(R.string.msgInternetConnectionNotAvailable));
            }
        } catch (Exception e) {
            CustomDialog.getInstance().hide();
            e.printStackTrace();
            ToastHelper.getInstance().showToast(activity, activity.getString(R.string.msgProblemWithRequest));
        }
    }

    @SuppressWarnings("unchecked")
    public void makeApiRequest(final Activity activity, Object call, final ApiResponseListener apiResponseListener, final int reqCode, final int position, boolean showProgressDialog) {
        try {
            if (Utils.getInstance().checkInternetConnection(activity)) {
                if (showProgressDialog)
                    CustomDialog.getInstance().show(activity, false);

                final Call<Object> objectCall = (Call<Object>) call;
                objectCall.enqueue(new Callback<Object>() {

                    @Override                    public void onResponse(Call<Object> call, retrofit2.Response<Object> response) {
                        CustomDialog.getInstance().hide();
                        /** Returns true if code() is in the range [200..300).*/                        if (response.isSuccessful()) {
                            MyLog.v(TAG, "onResponse - Success : " + response.body());
                            if (shouldCallCallback(apiResponseListener))
                                apiResponseListener.onApiResponse(call, response, reqCode, position);
                        } else {
                            if (response.message() != null && shouldCallCallback(apiResponseListener))
                                apiResponseListener.onApiError(call, response.message(), reqCode);
                            /*Note: This error log is only for developer. Where developer identify exact API error*/                            if (BuildConfig.DEBUG) {
                                APIError error = ErrorUtils.parseError(response);
                                if (error != null)
                                    MyLog.e(TAG, "error message: " + error.message());
                            }
                        }
                    }

                    @Override                    public void onFailure(Call<Object> call, Throwable t) {
                        //there is more than just a failing request (like: no internet connection)
                        MyLog.e(TAG, "onFailure - Fail : " + t.getMessage());
                        CustomDialog.getInstance().hide();

                        if (t instanceof ConnectException) {
                            //Displaying no network connection error                            if (shouldCallCallback(apiResponseListener))
                                apiResponseListener.onApiError(call, activity.getString(R.string.msgInternetConnectionNotAvailable), reqCode);
                        } else {
                            if (shouldCallCallback(apiResponseListener))
                                apiResponseListener.onApiError(call, activity.getString(R.string.msgProblemWithRequest), reqCode);
                        }
                    }
                });
            } else {
                ToastHelper.getInstance().showToast(activity, activity.getString(R.string.msgInternetConnectionNotAvailable));
            }
        } catch (Exception e) {
            CustomDialog.getInstance().hide();
            e.printStackTrace();
            ToastHelper.getInstance().showToast(activity, activity.getString(R.string.msgProblemWithRequest));
        }
    }

    private boolean shouldCallCallback(ApiResponseListener apiResponseListener) {
        if (apiResponseListener instanceof Fragment) {
            Fragment fragment = (Fragment) apiResponseListener;
            if (fragment.isAdded())
                return true;
        } else if (apiResponseListener instanceof Activity) {
            Activity activity = (Activity) apiResponseListener;
            if (!activity.isFinishing())
                return true;
        }
        return false;
    }
}

5)APIError.java
==================
package com.eppico.api;
public class APIError {
    private int statusCode;
    private String message;
    private String title;

    public APIError() {

    }

    public int status() {
        return statusCode;
    }
    public String message() {
        return message;
    }
    public String getTitle() {
        return title;
    }
}

* database
1)DBConstants.java
==================
package com.credencys.myapplication.database;

public class DbConstant {
   public static final class DB{
       public static final String DATABASENAME = "DBMyApp";
       public static final int DB_VERSION = 1;
   }

   public static final class USER{
      public static final String USER_TABLE = "user_table";
      public static final String USER_ID = "user_id";
      public static final String FIRST_NAME = "first_name";
      public static final String LAST_NAME = "last_name";
      public static final String EMAIL = "email";
      public static final String PASSWORD = "password";
      public static final String BIRTH_DATE = "birth_date";
      public static final String PHONE_NUMBER = "phone_number";
      public static final String GENDER = "gender";
      public static final String USER_IMAGE = "user_image";
   }

   public static final class TOPSTORY{
      public static final String TOPSTORY_TABLE = "topstory_table";
      public static final String TOPSTORY_ID = "topstory_id";
      public static final String TOPSTORY_TITLE = "topstory_title";
      public static final String TOPSTORY_PUB_DATE = "topstory_pub_date";
      public static final String TOPSTORY_LINK = "topstory_link";
      public static final String TOPSTORY_GUIDE = "topstory_guide";
      public static final String TOPSTORY_AUTHER = "topstory_auther";
      public static final String TOPSTORY_THUMBNAIL = "topstory_thumbnail";
      public static final String TOPSTORY_DESC = "topstory_desc";
      public static final String TOPSTORY_CONTENT= "topstory_content";
   }

   public static final class TECHNOLOGY{
      public static final String TECHNOLOGY_TABLE = "technology_table";
      public static final String TECHNOLOGY_ID = "technology_id";
      public static final String TECHNOLOGY_TITLE = "technology_title";
      public static final String TECHNOLOGY_PUB_DATE = "technology_pub_date";
      public static final String TECHNOLOGY_LINK = "technology_link";
      public static final String TECHNOLOGY_GUIDE = "technology_guide";
      public static final String TECHNOLOGY_AUTHER = "technology_auther";
      public static final String TECHNOLOGY_THUMBNAIL = "technology_thumbnail";
      public static final String TECHNOLOGY_DESC = "technology_desc";
      public static final String TECHNOLOGY_CONTENT= "technology_content";
   }

   public static final class CRICKET{
      public static final String CRICKET_TABLE = "cricket_table";
      public static final String CRICKET_ID = "cricket_id";
      public static final String CRICKET_TITLE = "cricket_title";
      public static final String CRICKET_PUB_DATE = "cricket_pub_date";
      public static final String CRICKET_LINK = "cricket_link";
      public static final String CRICKET_GUIDE = "cricket_guide";
      public static final String CRICKET_AUTHER = "cricket_auther";
      public static final String CRICKET_THUMBNAIL = "cricket_thumbnail";
      public static final String CRICKET_DESC = "cricket_desc";
      public static final String CRICKET_CONTENT= "cricket_content";
   }

   public static final class BUSINESS{
      public static final String BUSINESS_TABLE = "business_table";
      public static final String BUSINESS_ID = "business_id";
      public static final String BUSINESS_TITLE = "business_title";
      public static final String BUSINESS_PUB_DATE = "business_pub_date";
      public static final String BUSINESS_LINK = "business_link";
      public static final String BUSINESS_GUIDE = "business_guide";
      public static final String BUSINESS_AUTHER = "business_auther";
      public static final String BUSINESS_THUMBNAIL = "business_thumbnail";
      public static final String BUSINESS_DESC = "business_desc";
      public static final String BUSINESS_CONTENT= "business_content";
   }

   public static final class LIFE_STYLE{
      public static final String LIFE_STYLE_TABLE = "life_style_table";
      public static final String LIFE_STYLE_ID = "life_style_id";
      public static final String LIFE_STYLE_TITLE = "life_style_title";
      public static final String LIFE_STYLE_PUB_DATE = "life_style_pub_date";
      public static final String LIFE_STYLE_LINK = "life_style_link";
      public static final String LIFE_STYLE_GUIDE = "life_style_guide";
      public static final String LIFE_STYLE_AUTHER = "life_style_auther";
      public static final String LIFE_STYLE_THUMBNAIL = "life_style_thumbnail";
      public static final String LIFE_STYLE_DESC = "life_style_desc";
      public static final String LIFE_STYLE_CONTENT= "life_style_content";
   }
}

2)DbHelper.java
===============
package com.credencys.myapplication.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.credencys.myapplication.R;
import com.credencys.myapplication.models.LatestUpdateCategoryModel;
import com.credencys.myapplication.models.LoginModel;
import com.credencys.myapplication.utility.PrefHelper;
import com.google.gson.Gson;

import java.util.ArrayList;

public class DbHelper extends SQLiteOpenHelper {
    private Context context;
    private SQLiteDatabase sqLiteDatabase;

    //This Is For Make Database    public DbHelper(Context context) {
        super(context, DbConstant.DB.DATABASENAME, null, DbConstant.DB.DB_VERSION);
        this.context = context;
    }

    @Override    public void onCreate(SQLiteDatabase db) {
        //This Is For Make Database Table        String TABLE_USER = String.format("CREATE TABLE %s (" +
                        "%s INTEGER PRIMARY KEY AUTOINCREMENT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s INTEGER)", DbConstant.USER.USER_TABLE,

                DbConstant.USER.USER_ID,
                DbConstant.USER.FIRST_NAME,
                DbConstant.USER.LAST_NAME,
                DbConstant.USER.EMAIL,
                DbConstant.USER.PASSWORD,
                DbConstant.USER.BIRTH_DATE,
                DbConstant.USER.PHONE_NUMBER,
                DbConstant.USER.USER_IMAGE,
                DbConstant.USER.GENDER);
        db.execSQL(TABLE_USER);

        //Top story table        String TABLE_TOP_STORY = String.format("CREATE TABLE %s (" +
                        "%s INTEGER PRIMARY KEY AUTOINCREMENT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT)", DbConstant.TOPSTORY.TOPSTORY_TABLE,

                DbConstant.TOPSTORY.TOPSTORY_ID,
                DbConstant.TOPSTORY.TOPSTORY_TITLE,
                DbConstant.TOPSTORY.TOPSTORY_PUB_DATE,
                DbConstant.TOPSTORY.TOPSTORY_LINK,
                DbConstant.TOPSTORY.TOPSTORY_GUIDE,
                DbConstant.TOPSTORY.TOPSTORY_AUTHER,
                DbConstant.TOPSTORY.TOPSTORY_THUMBNAIL,
                DbConstant.TOPSTORY.TOPSTORY_DESC,
                DbConstant.TOPSTORY.TOPSTORY_CONTENT);
        db.execSQL(TABLE_TOP_STORY);

        //CRICKETtable        String TABLE_CRICKET = String.format("CREATE TABLE %s (" +
                        "%s INTEGER PRIMARY KEY AUTOINCREMENT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT)", DbConstant.CRICKET.CRICKET_TABLE,

                DbConstant.CRICKET.CRICKET_ID,
                DbConstant.CRICKET.CRICKET_TITLE,
                DbConstant.CRICKET.CRICKET_PUB_DATE,
                DbConstant.CRICKET.CRICKET_LINK,
                DbConstant.CRICKET.CRICKET_GUIDE,
                DbConstant.CRICKET.CRICKET_AUTHER,
                DbConstant.CRICKET.CRICKET_THUMBNAIL,
                DbConstant.CRICKET.CRICKET_DESC,
                DbConstant.CRICKET.CRICKET_CONTENT);
        db.execSQL(TABLE_CRICKET);

        // BUSINESS table        String TABLE_BUSINESS = String.format("CREATE TABLE %s (" +
                        "%s INTEGER PRIMARY KEY AUTOINCREMENT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT)", DbConstant.BUSINESS.BUSINESS_TABLE,

                DbConstant.BUSINESS.BUSINESS_ID,
                DbConstant.BUSINESS.BUSINESS_TITLE,
                DbConstant.BUSINESS.BUSINESS_PUB_DATE,
                DbConstant.BUSINESS.BUSINESS_LINK,
                DbConstant.BUSINESS.BUSINESS_GUIDE,
                DbConstant.BUSINESS.BUSINESS_AUTHER,
                DbConstant.BUSINESS.BUSINESS_THUMBNAIL,
                DbConstant.BUSINESS.BUSINESS_DESC,
                DbConstant.BUSINESS.BUSINESS_CONTENT);
        db.execSQL(TABLE_BUSINESS);

        //Technology table        String TABLE_TECHNOLOGY = String.format("CREATE TABLE %s (" +
                        "%s INTEGER PRIMARY KEY AUTOINCREMENT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT)", DbConstant.TECHNOLOGY.TECHNOLOGY_TABLE,

                DbConstant.TECHNOLOGY.TECHNOLOGY_ID,
                DbConstant.TECHNOLOGY.TECHNOLOGY_TITLE,
                DbConstant.TECHNOLOGY.TECHNOLOGY_PUB_DATE,
                DbConstant.TECHNOLOGY.TECHNOLOGY_LINK,
                DbConstant.TECHNOLOGY.TECHNOLOGY_GUIDE,
                DbConstant.TECHNOLOGY.TECHNOLOGY_AUTHER,
                DbConstant.TECHNOLOGY.TECHNOLOGY_THUMBNAIL,
                DbConstant.TECHNOLOGY.TECHNOLOGY_DESC,
                DbConstant.TECHNOLOGY.TECHNOLOGY_CONTENT);
        db.execSQL(TABLE_TECHNOLOGY);

        //Technology table        String TABLE_LIFE_STYLE = String.format("CREATE TABLE %s (" +
                        "%s INTEGER PRIMARY KEY AUTOINCREMENT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT," +
                        "%s TEXT)", DbConstant.LIFE_STYLE.LIFE_STYLE_TABLE,

                DbConstant.LIFE_STYLE.LIFE_STYLE_ID,
                DbConstant.LIFE_STYLE.LIFE_STYLE_TITLE,
                DbConstant.LIFE_STYLE.LIFE_STYLE_PUB_DATE,
                DbConstant.LIFE_STYLE.LIFE_STYLE_LINK,
                DbConstant.LIFE_STYLE.LIFE_STYLE_GUIDE,
                DbConstant.LIFE_STYLE.LIFE_STYLE_AUTHER,
                DbConstant.LIFE_STYLE.LIFE_STYLE_THUMBNAIL,
                DbConstant.LIFE_STYLE.LIFE_STYLE_DESC,
                DbConstant.LIFE_STYLE.LIFE_STYLE_CONTENT);
        db.execSQL(TABLE_LIFE_STYLE);
    }

    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + DbConstant.USER.USER_TABLE);
        onCreate(db);
    }

    //insert values in user table    public void insertUser(String first_name,String last_name,String email,String password,String birth_date,String phone_number,String user_image,int gender) {
        ContentValues cv = new ContentValues();
        cv.put(DbConstant.USER.FIRST_NAME, first_name);
        cv.put(DbConstant.USER.LAST_NAME, last_name);
        cv.put(DbConstant.USER.EMAIL, email);
        cv.put(DbConstant.USER.PASSWORD, password);
        cv.put(DbConstant.USER.BIRTH_DATE, birth_date);
        cv.put(DbConstant.USER.PHONE_NUMBER, phone_number);
        cv.put(DbConstant.USER.USER_IMAGE,user_image);
        cv.put(DbConstant.USER.GENDER, gender);
        int id = (int) sqLiteDatabase.insert(DbConstant.USER.USER_TABLE, null, cv);

        LoginModel loginModel = new LoginModel();
        loginModel.setUserId(id);
        loginModel.setFirstName(first_name);
        loginModel.setLastName(last_name);
        loginModel.setEmail(email);
        loginModel.setPassword(password);
        loginModel.setPhoneNumber(phone_number);
        loginModel.setUserImage(user_image);
        loginModel.setDob(birth_date);
        loginModel.setGender(gender);

        Gson gson = new Gson();
        PrefHelper.setString(context.getString(R.string.prefLoginUserData),  gson.toJson(loginModel));
    }

   /* function for check that email exist or not*/    public boolean isEmailExist(String email) {
        boolean isExist = false;
        String query = String.format("SELECT "+ DbConstant.USER.EMAIL +" From %s WHERE %s = '%s'", DbConstant.USER.USER_TABLE, DbConstant.USER.EMAIL, email);
        Log.e("","SQL:::"+query);
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);
        if (cursor != null) {
            if(cursor.getCount() > 0){
                isExist = true;
            }
            if (!cursor.isClosed()) {
                cursor.close();
            }
        }
        return isExist;
    }

    public boolean isUserExists(String email, String password) {
        boolean isLogin = false;
        String query = String.format("SELECT * From %s WHERE %s = '%s' and %s = '%s'", DbConstant.USER.USER_TABLE, DbConstant.USER.EMAIL, email,DbConstant.USER.PASSWORD,password);
        Log.e("","SQL:::"+query);
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);
        if (cursor != null) {
            if(cursor.getCount() > 0){
                cursor.moveToFirst();
                isLogin = true;

                LoginModel loginModel = new LoginModel();
                loginModel.setUserId(cursor.getInt(cursor.getColumnIndex(DbConstant.USER.USER_ID)));
                loginModel.setFirstName(cursor.getString(cursor.getColumnIndex(DbConstant.USER.FIRST_NAME)));
                loginModel.setLastName(cursor.getString(cursor.getColumnIndex(DbConstant.USER.LAST_NAME)));
                loginModel.setEmail(cursor.getString(cursor.getColumnIndex(DbConstant.USER.EMAIL)));
                loginModel.setPassword(cursor.getString(cursor.getColumnIndex(DbConstant.USER.PASSWORD)));
                loginModel.setPhoneNumber(cursor.getString(cursor.getColumnIndex(DbConstant.USER.PHONE_NUMBER)));
                loginModel.setUserImage(cursor.getString(cursor.getColumnIndex(DbConstant.USER.USER_IMAGE)));
                loginModel.setDob(cursor.getString(cursor.getColumnIndex(DbConstant.USER.BIRTH_DATE)));
                loginModel.setGender(cursor.getInt(cursor.getColumnIndex(DbConstant.USER.GENDER)));

                Gson gsonLogin = new Gson();
                PrefHelper.setString(context.getString(R.string.prefLoginUserData),  gsonLogin.toJson(loginModel));
            }

            if (!cursor.isClosed()) {
                cursor.close();
            }
        }
        return isLogin;
    }

    public void updateProfile(int id,String first_name, String last_name,String password,String email, String birth_date, String phone_number,String image_path, int gender) {
        LoginModel loginModel = new LoginModel();
        loginModel.setUserId(id);
        loginModel.setFirstName(first_name);
        loginModel.setLastName(last_name);
        loginModel.setPassword(password);
        loginModel.setEmail(email);
        loginModel.setPhoneNumber(phone_number);
        loginModel.setUserImage(image_path);
        loginModel.setDob(birth_date);
        loginModel.setGender(gender);

        Gson gsonLogin = new Gson();
        PrefHelper.setString(context.getString(R.string.prefLoginUserData),  gsonLogin.toJson(loginModel));

        String strWhere = String.format("%s = '%s'", DbConstant.USER.EMAIL, email);
        ContentValues cv = new ContentValues();
        cv.put(DbConstant.USER.FIRST_NAME, first_name);
        cv.put(DbConstant.USER.LAST_NAME, last_name);
        cv.put(DbConstant.USER.EMAIL, email);
        cv.put(DbConstant.USER.BIRTH_DATE, birth_date);
        cv.put(DbConstant.USER.PHONE_NUMBER, phone_number);
        cv.put(DbConstant.USER.USER_IMAGE,image_path);
        cv.put(DbConstant.USER.GENDER, gender);
        sqLiteDatabase.update(DbConstant.USER.USER_TABLE,cv, strWhere, null);
    }

    public void openDatabase() {
        sqLiteDatabase = this.getWritableDatabase();
    }

    public void closeDataBase() throws SQLException {
        if (sqLiteDatabase != null)
            sqLiteDatabase.close();
    }

    //insert values in topstory table    public void insertTopStoryData(LatestUpdateCategoryModel.Items topStoryItem) {
        ContentValues values = new ContentValues();

        values.put(DbConstant.TOPSTORY.TOPSTORY_TITLE, topStoryItem.getTitle());
        values.put(DbConstant.TOPSTORY.TOPSTORY_PUB_DATE, topStoryItem.getPubDate());
        values.put(DbConstant.TOPSTORY.TOPSTORY_LINK, topStoryItem.getLink());
        values.put(DbConstant.TOPSTORY.TOPSTORY_GUIDE, topStoryItem.getGuid());
        values.put(DbConstant.TOPSTORY.TOPSTORY_AUTHER, topStoryItem.getAuthor());
        values.put(DbConstant.TOPSTORY.TOPSTORY_THUMBNAIL, topStoryItem.getThumbnail());
        values.put(DbConstant.TOPSTORY.TOPSTORY_DESC, topStoryItem.getDescription());
        values.put(DbConstant.TOPSTORY.TOPSTORY_CONTENT, topStoryItem.getContent());

        sqLiteDatabase.insert(DbConstant.TOPSTORY.TOPSTORY_TABLE, null, values);
    }

    //get All TopStory data    public ArrayList<LatestUpdateCategoryModel.Items> GetTopStoryData() {
        ArrayList<LatestUpdateCategoryModel.Items> list = new ArrayList<LatestUpdateCategoryModel.Items>();

        String query = "select * from " + DbConstant.TOPSTORY.TOPSTORY_TABLE;
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);

        while (cursor.moveToNext()) {
            LatestUpdateCategoryModel.Items topStoryItem = new LatestUpdateCategoryModel.Items();
            topStoryItem.setTitle(cursor.getString(cursor.getColumnIndex(DbConstant.TOPSTORY.TOPSTORY_TITLE)));
            topStoryItem.setPubDate(cursor.getString(cursor.getColumnIndex(DbConstant.TOPSTORY.TOPSTORY_PUB_DATE)));
            topStoryItem.setLink(cursor.getString(cursor.getColumnIndex(DbConstant.TOPSTORY.TOPSTORY_LINK)));
            topStoryItem.setGuid(cursor.getString(cursor.getColumnIndex(DbConstant.TOPSTORY.TOPSTORY_GUIDE)));
            topStoryItem.setAuthor(cursor.getString(cursor.getColumnIndex(DbConstant.TOPSTORY.TOPSTORY_AUTHER)));
            topStoryItem.setThumbnail(cursor.getString(cursor.getColumnIndex(DbConstant.TOPSTORY.TOPSTORY_THUMBNAIL)));
            topStoryItem.setDescription(cursor.getString(cursor.getColumnIndex(DbConstant.TOPSTORY.TOPSTORY_DESC)));
            topStoryItem.setContent(cursor.getString(cursor.getColumnIndex(DbConstant.TOPSTORY.TOPSTORY_CONTENT)));
            list.add(topStoryItem);
        }

        return list;
    }

    //insert values in cricket table    public void insertCricketData(LatestUpdateCategoryModel.Items cricketItem) {
        ContentValues values = new ContentValues();

        values.put(DbConstant.CRICKET.CRICKET_TITLE, cricketItem.getTitle());
        values.put(DbConstant.CRICKET.CRICKET_PUB_DATE, cricketItem.getPubDate());
        values.put(DbConstant.CRICKET.CRICKET_LINK, cricketItem.getLink());
        values.put(DbConstant.CRICKET.CRICKET_GUIDE, cricketItem.getGuid());
        values.put(DbConstant.CRICKET.CRICKET_AUTHER, cricketItem.getAuthor());
        values.put(DbConstant.CRICKET.CRICKET_THUMBNAIL, cricketItem.getThumbnail());
        values.put(DbConstant.CRICKET.CRICKET_DESC, cricketItem.getDescription());
        values.put(DbConstant.CRICKET.CRICKET_CONTENT, cricketItem.getContent());

        sqLiteDatabase.insert(DbConstant.CRICKET.CRICKET_TABLE, null, values);
    }

    //get All Cricket data    public ArrayList<LatestUpdateCategoryModel.Items> GetCricketData() {
        ArrayList<LatestUpdateCategoryModel.Items> list = new ArrayList<LatestUpdateCategoryModel.Items>();

        String query = "select * from " + DbConstant.CRICKET.CRICKET_TABLE;
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);

        while (cursor.moveToNext()) {
            LatestUpdateCategoryModel.Items cricketItem = new LatestUpdateCategoryModel.Items();
            cricketItem.setTitle(cursor.getString(cursor.getColumnIndex(DbConstant.CRICKET.CRICKET_TITLE)));
            cricketItem.setPubDate(cursor.getString(cursor.getColumnIndex(DbConstant.CRICKET.CRICKET_PUB_DATE)));
            cricketItem.setLink(cursor.getString(cursor.getColumnIndex(DbConstant.CRICKET.CRICKET_LINK)));
            cricketItem.setGuid(cursor.getString(cursor.getColumnIndex(DbConstant.CRICKET.CRICKET_GUIDE)));
            cricketItem.setAuthor(cursor.getString(cursor.getColumnIndex(DbConstant.CRICKET.CRICKET_AUTHER)));
            cricketItem.setThumbnail(cursor.getString(cursor.getColumnIndex(DbConstant.CRICKET.CRICKET_THUMBNAIL)));
            cricketItem.setDescription(cursor.getString(cursor.getColumnIndex(DbConstant.CRICKET.CRICKET_DESC)));
            cricketItem.setContent(cursor.getString(cursor.getColumnIndex(DbConstant.CRICKET.CRICKET_CONTENT)));
            list.add(cricketItem);
        }

        return list;
    }

    //insert values in Business table    public void insertBusinessData(LatestUpdateCategoryModel.Items businessItem) {
        ContentValues values = new ContentValues();

        values.put(DbConstant.BUSINESS.BUSINESS_TITLE, businessItem.getTitle());
        values.put(DbConstant.BUSINESS.BUSINESS_PUB_DATE, businessItem.getPubDate());
        values.put(DbConstant.BUSINESS.BUSINESS_LINK, businessItem.getLink());
        values.put(DbConstant.BUSINESS.BUSINESS_GUIDE, businessItem.getGuid());
        values.put(DbConstant.BUSINESS.BUSINESS_AUTHER, businessItem.getAuthor());
        values.put(DbConstant.BUSINESS.BUSINESS_THUMBNAIL, businessItem.getThumbnail());
        values.put(DbConstant.BUSINESS.BUSINESS_DESC, businessItem.getDescription());
        values.put(DbConstant.BUSINESS.BUSINESS_CONTENT, businessItem.getContent());

        sqLiteDatabase.insert(DbConstant.BUSINESS.BUSINESS_TABLE, null, values);
    }

    //get All Business data    public ArrayList<LatestUpdateCategoryModel.Items> GetBusinessData() {
        ArrayList<LatestUpdateCategoryModel.Items> list = new ArrayList<LatestUpdateCategoryModel.Items>();

        String query = "select * from " + DbConstant.BUSINESS.BUSINESS_TABLE;
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);

        while (cursor.moveToNext()) {
            LatestUpdateCategoryModel.Items businessItem = new LatestUpdateCategoryModel.Items();
            businessItem.setTitle(cursor.getString(cursor.getColumnIndex(DbConstant.BUSINESS.BUSINESS_TITLE)));
            businessItem.setPubDate(cursor.getString(cursor.getColumnIndex(DbConstant.BUSINESS.BUSINESS_PUB_DATE)));
            businessItem.setLink(cursor.getString(cursor.getColumnIndex(DbConstant.BUSINESS.BUSINESS_LINK)));
            businessItem.setGuid(cursor.getString(cursor.getColumnIndex(DbConstant.BUSINESS.BUSINESS_GUIDE)));
            businessItem.setAuthor(cursor.getString(cursor.getColumnIndex(DbConstant.BUSINESS.BUSINESS_AUTHER)));
            businessItem.setThumbnail(cursor.getString(cursor.getColumnIndex(DbConstant.BUSINESS.BUSINESS_THUMBNAIL)));
            businessItem.setDescription(cursor.getString(cursor.getColumnIndex(DbConstant.BUSINESS.BUSINESS_DESC)));
            businessItem.setContent(cursor.getString(cursor.getColumnIndex(DbConstant.BUSINESS.BUSINESS_CONTENT)));
            list.add(businessItem);
        }

        return list;
    }

    //insert values in Technology table    public void insertTechnologyData(LatestUpdateCategoryModel.Items technologyItem) {
        ContentValues values = new ContentValues();

        values.put(DbConstant.TECHNOLOGY.TECHNOLOGY_TITLE, technologyItem.getTitle());
        values.put(DbConstant.TECHNOLOGY.TECHNOLOGY_PUB_DATE, technologyItem.getPubDate());
        values.put(DbConstant.TECHNOLOGY.TECHNOLOGY_LINK, technologyItem.getLink());
        values.put(DbConstant.TECHNOLOGY.TECHNOLOGY_GUIDE, technologyItem.getGuid());
        values.put(DbConstant.TECHNOLOGY.TECHNOLOGY_AUTHER, technologyItem.getAuthor());
        values.put(DbConstant.TECHNOLOGY.TECHNOLOGY_THUMBNAIL, technologyItem.getThumbnail());
        values.put(DbConstant.TECHNOLOGY.TECHNOLOGY_DESC, technologyItem.getDescription());
        values.put(DbConstant.TECHNOLOGY.TECHNOLOGY_CONTENT, technologyItem.getContent());

        sqLiteDatabase.insert(DbConstant.TECHNOLOGY.TECHNOLOGY_TABLE, null, values);
    }

    //get All Technology data    public ArrayList<LatestUpdateCategoryModel.Items> GetTechnologyData() {
        ArrayList<LatestUpdateCategoryModel.Items> list = new ArrayList<LatestUpdateCategoryModel.Items>();

        String query = "select * from " + DbConstant.TECHNOLOGY.TECHNOLOGY_TABLE;
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);

        while (cursor.moveToNext()) {
            LatestUpdateCategoryModel.Items technologyItem = new LatestUpdateCategoryModel.Items();
            technologyItem.setTitle(cursor.getString(cursor.getColumnIndex(DbConstant.TECHNOLOGY.TECHNOLOGY_TITLE)));
            technologyItem.setPubDate(cursor.getString(cursor.getColumnIndex(DbConstant.TECHNOLOGY.TECHNOLOGY_PUB_DATE)));
            technologyItem.setLink(cursor.getString(cursor.getColumnIndex(DbConstant.TECHNOLOGY.TECHNOLOGY_LINK)));
            technologyItem.setGuid(cursor.getString(cursor.getColumnIndex(DbConstant.TECHNOLOGY.TECHNOLOGY_GUIDE)));
            technologyItem.setAuthor(cursor.getString(cursor.getColumnIndex(DbConstant.TECHNOLOGY.TECHNOLOGY_AUTHER)));
            technologyItem.setThumbnail(cursor.getString(cursor.getColumnIndex(DbConstant.TECHNOLOGY.TECHNOLOGY_THUMBNAIL)));
            technologyItem.setDescription(cursor.getString(cursor.getColumnIndex(DbConstant.TECHNOLOGY.TECHNOLOGY_DESC)));
            technologyItem.setContent(cursor.getString(cursor.getColumnIndex(DbConstant.TECHNOLOGY.TECHNOLOGY_CONTENT)));
            list.add(technologyItem);
        }
        return list;
    }

    //insert values in Lifestyle table    public void insertLifeStyleData(LatestUpdateCategoryModel.Items liftStyleItem) {
        ContentValues values = new ContentValues();

        values.put(DbConstant.LIFE_STYLE.LIFE_STYLE_TITLE, liftStyleItem.getTitle());
        values.put(DbConstant.LIFE_STYLE.LIFE_STYLE_PUB_DATE, liftStyleItem.getPubDate());
        values.put(DbConstant.LIFE_STYLE.LIFE_STYLE_LINK, liftStyleItem.getLink());
        values.put(DbConstant.LIFE_STYLE.LIFE_STYLE_GUIDE, liftStyleItem.getGuid());
        values.put(DbConstant.LIFE_STYLE.LIFE_STYLE_AUTHER, liftStyleItem.getAuthor());
        values.put(DbConstant.LIFE_STYLE.LIFE_STYLE_THUMBNAIL, liftStyleItem.getThumbnail());
        values.put(DbConstant.LIFE_STYLE.LIFE_STYLE_DESC, liftStyleItem.getDescription());
        values.put(DbConstant.LIFE_STYLE.LIFE_STYLE_CONTENT, liftStyleItem.getContent());

        sqLiteDatabase.insert(DbConstant.LIFE_STYLE.LIFE_STYLE_TABLE, null, values);
    }

    //get All lifestyle data    public ArrayList<LatestUpdateCategoryModel.Items> GetLifeStyleData() {
        ArrayList<LatestUpdateCategoryModel.Items> list = new ArrayList<LatestUpdateCategoryModel.Items>();

        String query = "select * from " + DbConstant.LIFE_STYLE.LIFE_STYLE_TABLE;
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);

        while (cursor.moveToNext()) {
            LatestUpdateCategoryModel.Items liftStyleItem = new LatestUpdateCategoryModel.Items();
            liftStyleItem.setTitle(cursor.getString(cursor.getColumnIndex(DbConstant.LIFE_STYLE.LIFE_STYLE_TITLE)));
            liftStyleItem.setPubDate(cursor.getString(cursor.getColumnIndex(DbConstant.LIFE_STYLE.LIFE_STYLE_PUB_DATE)));
            liftStyleItem.setLink(cursor.getString(cursor.getColumnIndex(DbConstant.LIFE_STYLE.LIFE_STYLE_LINK)));
            liftStyleItem.setGuid(cursor.getString(cursor.getColumnIndex(DbConstant.LIFE_STYLE.LIFE_STYLE_GUIDE)));
            liftStyleItem.setAuthor(cursor.getString(cursor.getColumnIndex(DbConstant.LIFE_STYLE.LIFE_STYLE_AUTHER)));
            liftStyleItem.setThumbnail(cursor.getString(cursor.getColumnIndex(DbConstant.LIFE_STYLE.LIFE_STYLE_THUMBNAIL)));
            liftStyleItem.setDescription(cursor.getString(cursor.getColumnIndex(DbConstant.LIFE_STYLE.LIFE_STYLE_DESC)));
            liftStyleItem.setContent(cursor.getString(cursor.getColumnIndex(DbConstant.LIFE_STYLE.LIFE_STYLE_CONTENT)));
            list.add(liftStyleItem);
        }

        return list;
    }

    // Delete tables    public void deleteTopStory(){
        sqLiteDatabase.delete(DbConstant.TOPSTORY.TOPSTORY_TABLE, null, null);
    }
    public void deleteCricket(){
        sqLiteDatabase.delete(DbConstant.CRICKET.CRICKET_TABLE, null, null);
    }
    public void deleteBusiness(){
        sqLiteDatabase.delete(DbConstant.BUSINESS.BUSINESS_TABLE, null, null);
    }
    public void deleteTechnology(){
        sqLiteDatabase.delete(DbConstant.TECHNOLOGY.TECHNOLOGY_TABLE, null, null);
    }
    public void deleteLifeStyle(){
        sqLiteDatabase.delete(DbConstant.LIFE_STYLE.LIFE_STYLE_TABLE, null, null);
    }
}

* fragment
==========
1)BaseFragment.java
===================
package com.credencys.myapplication.fragment;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import com.credencys.myapplication.MyApplication;
import com.credencys.myapplication.R;
import com.credencys.myapplication.activity.HomeActivity;
import com.credencys.myapplication.api.ApiResponseListener;
import com.credencys.myapplication.interfaces.BackPressedEventListener;
import com.credencys.myapplication.interfaces.ClickEventListener;

import java.lang.reflect.Field;

import retrofit2.Call;
import retrofit2.Response;

/** * Created by manisha on 24/1/17. */
public class BaseFragment extends Fragment implements BackPressedEventListener, ClickEventListener, ApiResponseListener {
    HomeActivity homeActivity;

    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        homeActivity= (HomeActivity) getActivity();
    }

    // Arbitrary value; set it to some reasonable default    private static final int DEFAULT_CHILD_ANIMATION_DURATION = 250;

    @Override    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        final Fragment parent = getParentFragment();
        // Apply the workaround only if this is a child fragment, and the parent        // is being removed.        if (!enter && parent != null && parent.isRemoving()) {
             /*Note:This is a workaround for the bug where child fragments disappear when                    the parent is removed (as all children are first removed from the parent)                    See https://code.google.com/p/android/issues/detail?id=55228*/            Animation doNothingAnim = new AlphaAnimation(1, 1);
            doNothingAnim.setDuration(getNextAnimationDuration(parent, DEFAULT_CHILD_ANIMATION_DURATION));
            return doNothingAnim;
        } else {
            if (MyApplication.DISABLE_FRAGMENT_ANIMATION) {
                if(!enter)
                {
                    Animation  anim = null;
                    if(nextAnim!=0)
                    {
                   anim = AnimationUtils.loadAnimation(getActivity(), nextAnim);
                        anim.setDuration(0);
                    }
                    else                    {
                        /*Note: If next animation is not there then it will blink layout after remove all fragments.                        *       So to overcome this issue here load any animation and set duration 0*/                        anim = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_out_left);
                        anim.setDuration(0);
                    }
                    return anim;
                }
            }
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

    private static long getNextAnimationDuration(Fragment fragment, long defValue) {
        try {
            // Attempt to get the resource ID of the next animation that            // will be applied to the given fragment.            Field nextAnimField = Fragment.class.getDeclaredField("mNextAnim");
            nextAnimField.setAccessible(true);
            int nextAnimResource = nextAnimField.getInt(fragment);
            if(nextAnimResource>0)
            {
                Animation nextAnim = AnimationUtils.loadAnimation(fragment.getActivity(), nextAnimResource);
                // ...and if it can be loaded, return that animation's duration                return (nextAnim == null) ? defValue : nextAnim.getDuration();
            }
            else                return defValue;
        } catch (NoSuchFieldException|IllegalAccessException|Resources.NotFoundException ex) {
            //Log.w("getNextAnimationDuration", "Unable to load next animation from parent.", ex);            ex.printStackTrace();
            return defValue;
        }
    }

    @Override    public void onBackPressed() {

    }

    @Override    public void clickEvent(View v) {

    }

    @Override    public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) {

    }

    @Override    public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position) {

    }

    @Override    public void onApiError(Call<Object> call, Object object, int reqCode) {

    }
}

2)DashBoardFragment.java
=======================
package com.credencys.myapplication.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.credencys.myapplication.R;
import com.credencys.myapplication.models.LoginModel;
import com.credencys.myapplication.utility.PrefHelper;
import com.credencys.myapplication.utility.Utils;
import com.google.gson.Gson;

import static com.credencys.myapplication.R.id.txt_actionbar_title;

/** * Created by manisha on 25/1/17. */
public class DashBoardFragment extends BaseFragment {
    private View view;
    private String fromScreen="";

    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        homeActivity.setSlidingMenuEnable(true);
        Gson gson = new Gson();
        if(PrefHelper.getString(getActivity().getString(R.string.prefLoginUserData),"").length()>0) {
            homeActivity.loginModel = gson.fromJson(PrefHelper.getString(getActivity().getString(R.string.prefLoginUserData), ""), LoginModel.class);
        }
    }

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_dashboard, container, false);

        initData();

        return view;
    }

    public void initData() {
        Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.frag_dashboard_layout_parent));

        TextView txtActionBarTitle = (TextView)view.findViewById(txt_actionbar_title);
        txtActionBarTitle.setText(getResources().getString(R.string.dashboard));
        homeActivity.setupSlidingMenuData(homeActivity.loginModel);
        if(fromScreen.equalsIgnoreCase(getResources().getString(R.string.extraMenu))){
            homeActivity.setSelectedPositionInSlidingMenu(0);
        }
    }

    @Override    public void clickEvent(View v) {
        super.clickEvent(v);
        switch (v.getId())
        {
            case R.id.img_actionbar_menu:
                homeActivity.toggleSlidingMenu();
                break;

            case R.id.frag_dashboard_txt_latest_update:
                LatestUpdateFragment mLatestUpdateFragment = new LatestUpdateFragment();
                Bundle bundle = new Bundle();
                bundle.putString(getResources().getString(R.string.extraFromScreen),getResources().getString(R.string.extraDashBoard));
                mLatestUpdateFragment.setArguments(bundle);
                homeActivity.pushFragments(mLatestUpdateFragment, true, false, true);
                break;

            case R.id.frag_dashboard_txt_near_by_location:
                NearByLocationFragment mNearByLocationFragment = new NearByLocationFragment();
                Bundle bundleMap = new Bundle();
                bundleMap.putString(getResources().getString(R.string.extraFromScreen),getResources().getString(R.string.extraDashBoard));
                mNearByLocationFragment.setArguments(bundleMap);
                homeActivity.pushFragments(mNearByLocationFragment, true, false, true);

                break;

            case R.id.frag_dashboard_txt_expand_view:
                ExpandViewFragment mExpandViewFragment = new ExpandViewFragment();
                Bundle bundleExpand = new Bundle();
                bundleExpand.putString(getResources().getString(R.string.extraFromScreen),getResources().getString(R.string.extraDashBoard));
                mExpandViewFragment.setArguments(bundleExpand);
                homeActivity.pushFragments(mExpandViewFragment, true, false, true);

                break;

            case R.id.frag_dashboard_txt_my_gallery:
                MyGalleryFragment myGalleryFragment = new MyGalleryFragment();
                Bundle bundleGallery = new Bundle();
                bundleGallery.putString(getResources().getString(R.string.extraFromScreen),getResources().getString(R.string.extraDashBoard));
                myGalleryFragment.setArguments(bundleGallery);
                homeActivity.pushFragments(myGalleryFragment, true, false, true);

                break;
         }
    }

    /**     * Handle Activity click events     */    @Override    public void onBackPressed() {
        getActivity().finish();
    }
}

3)ExpandViewFragment.java
=========================
package com.credencys.myapplication.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.credencys.myapplication.R;
import com.credencys.myapplication.adapter.ExpandViewAdapter;
import com.credencys.myapplication.models.ExpandViewModel;

import java.util.ArrayList;

/** * Created by manisha on 4/1/17. */
public class ExpandViewFragment extends BaseFragment {
    private View mainView;
    private RecyclerView recyclerViewExpandView;
    private ArrayList<ExpandViewModel> alstExpandView;
    private ExpandViewAdapter mExpanViewAdapter;
    private String fromScreen="";

/*    String array for Recycler View title*/    public String[] arrayTitle = {"Banks set to keep rates low due to slow growth in credit"            ,"Mallya used IDBI loan for KFA to fly private jet: Chargesheet"            ,"Jio, Paytm get embroiled in an image problem"            ,"Govt to explore M&amp;As across state-run units"            ,"Jet Airways' Q3 net profit plunges 70% on higher cost"            ,"FMCG loses 30% of its business due to fake products"            ,"Sanjeev Sanyal appointed principal economic adviser in Finance Ministry"            ,"Market moves up ahead of RBI policy, logs smart weekly gain"            ,"Services sector contracts for 3rd month in January"            ,"Rupee's good run continues, gains 4 paise against dollar"            ,"Alibaba will hold 40% stake in Paytm's e-comm entity"            ,"Coal ministry to allow commercial mining by private companies"            ,"Mistry moves NCLAT against Tata Sons' shareholder meet"            ,"Sensex hovers at 4-month high on Budget rally"            ,"World shares slip as Trump's actions spur investor caution"            ,"Budget aims at fiscal improvement: S&amp;P"            ,"Sensex slips 51 points after a power-packed show"            ,"RBI to Kotak Bank: Cut promoter stake to 30% by June 30"            ,"Trai may not find issues with Jio's promotional tariff plans"            ,"Budget will strengthen economy from grass roots: India Inc"            ,"Apple iPhone 7, iPhone 7 Plus price details revealed, goes up to Rs 92,000"            ,"Apple slashes prices of iPhone 6s and iPhone 6s Plus by up to Rs 22,000"            ,"WhatsApp privacy policy challenged in Delhi High Court: 5 things to know"            ,"Apple iOS 10 surpasses iOS 9 in early adoption in just 24 hours"            ,"Fitbit Charge 2 review: Towards a healthier you"};


    /*String array for Recycler View description*/    public String[] arrayDesc = {"President hailed the demonetisation move and the surgical strikes across the LoC in his address to the joint sitting of Parliament. The President’s speech also indicated that the govt’s 3rd Budget may provide more funds for schemes focusing on the poor, farmers &amp; other vulnerable groups of society.",
            "Marking a huge shift from its known stance, Pakistan’s military said on Tuesday that the house arrest of Hafiz Muhammad Saeed, the founder of banned Lashkar-e-Taiba (LeT) accused of masterminding the 2008 Mumbai terror attack, was a policy decision in national interest.",
            "Tickets worth Rupees 52,36,000 were unsold. Why all the tickets were not sold-out? DDCA started online ticket sale quite late that too without proper advertisement,\" Khanna claimed in a media release.",
            "TOI Sports runs the rule over the performers for India during their 3-2 ODI series win over New Zealand. A report card on the players who featured in India's first ODI series win at home in two years, over NZ across five matches.",
            "Mishra didn't mince words when asked about the frustration of having to sit out, but added that coach Anil Kumble's tips had helped him tide over the low phase.",
            "India completed a 3-2 series win over New Zealand by beating them in the decider at Vizag by 190 runs. Here we look at the several passages of play that stood out during the match.",
            "Bank credit increased by nearly Rs 1.7 lakh crore during the current financial year up to January 20, 2017, as compared to a more than Rs 11-lakhcrore increase in deposits. This huge gap in growth of banks’ resources, even as demand remains tepid, points to further reduction in interest rates.",
            "Aviation profits, however, plunged from 2008 in kilter with a decelerating global economy and subsequent record prices of crude oil, pushing Kingfisher into bankruptcy. The company and Mallya are now under federal investigation for non-payment of about Rs 9,000 crore to Indian lenders.",
            "An official with the ministry of consumer affairs, food and public distribution confirmed the move, adding that the companies may also face penalties in the coming week. Two other ministry officials also confirmed the development.",
            "The government will explore mergers &amp; acquisitions (M&amp;As) in not just the oil sector but in all state-run enterprises, a senior finance ministry official said on Friday, while asserting that all efforts would be made to meet the disinvestment target of Rs 72,500 crore for the current financial year.",
            "Rising oil prices have started seriously denting the profitability of Indian carriers. Jet Airways on Friday reported a net profit of Rs 142.4 crore in the quarter ended December 2016, -- down 70% from Rs 467.1 crore in same period last fiscal.",
            "Fast-moving consumer goods (FMCG) packaging remains the worst affected industry due to counterfeiting which accounts for over 30% of business revenues, according to industry reports.",
            "In 2007, Sanyal was awarded the Eisenhower Fellowship for his work on urban issues and was also honoured by the Singapore government at the World Cities Summit 2014.",
            "he services sector contracted for the third consecutive month in January as the Nikkei India PMI survey suggested that input cost inflation slowed since December which may prompt the Reserve Bank to go in for an \"accommodative\" monetary policy.",
            "The Nikkei India Services Purchasing Managers' Index (PMI), which tracks services sector companies on a monthly basis, came in at 48.7 in January, from 46.8 in December 2016, signalling that the sector is heading towards stabilisation.",
            "The rupee's good run continued into the 8th straight session on Friday as it firmed up by another 4 paise in early trade to 67.33 against the dollar after the US currency saw higher selling by exporters and banks amid foreign fund inflows.",
            "Alibaba will hold a substantial stake in Paytm's newly spun off online marketplace business, setting the stage for a three-way battle between Amazon, Flipkart and Alibaba in India. It will hold almost 40% in Paytm e-commerce, according to regulatory filings sourced from business research platfom Tofler.",
            "Forty-four years after nationalising coal mines, the government will allow commercial mining by private companies this year, a top coal ministry official said on Thursday.",
            "With four days to go before Tata Sons holds it's extraordinary general meeting for the removal of its recently ousted chairman Cyrus Mistry as a director too, Mistry's family-held firms moved the National Company Law Appellate Tribunal in Delhi on Thursday seeking stay on the meeting called on February 6.",
            "The Budget rally entered the second day on Thursday after the sensex closed at nearly a 4-month high of 28,227, driven by healthcare, IT and auto stocks amid mixed global shares.",
            "Sensex fell about 51 points in initial trading on Thursday due to a rush to take profit amid weak Asia cues. The NSE Nifty went below the 8,700-mark by falling 21.20 points, or 0.24 per cent, to trade at 8,695.20.",
            "Kotak Mahindra Bank said on Wednesday that it has been given additional time till June 30, 2017 to bring down promoter stake in the bank to 30% from 33.6% as on December 2016.",
            "Trai is understood to have found no issues with Reliance Jio's contentious promotional tariff plans that have been challenged by rivals like Airtel and Vodafone for being \"in violation\" of the regulator's rules.",
            "India Inc on Wednesday said the budget builds a positive sentiment that government will take all steps to boost growth with its focus on rural economy and infrastructure but rued no cut in corporate tax for large companies.",
            "The iPhone 7 Plus 32GB, 128GB and 256GB will cost Rs 72,000, Rs 82,000 and Rs 92,000 respectively.Bank credit increased by nearly Rs 1.7 lakh crore during the current financial year up to January 20, 2017, as compared to a more than Rs 11-lakhcrore increase in deposits."};

    /*integer array for Recycler View images*/    public Integer[] arrayImages = {R.mipmap.image1, R.mipmap.image2, R.mipmap.image3, R.mipmap.image4, R.mipmap.image5, R.mipmap.image6, R.mipmap.image7, R.mipmap.image8, R.mipmap.image9, R.mipmap.image10, R.mipmap.image11, R.mipmap.image12, R.mipmap.image13, R.mipmap.image14, R.mipmap.image15, R.mipmap.image16, R.mipmap.image17, R.mipmap.image18, R.mipmap.image19, R.mipmap.image20, R.mipmap.image21, R.mipmap.image22, R.mipmap.image23, R.mipmap.image24, R.mipmap.image25};

    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            fromScreen = bundle.getString(getResources().getString(R.string.extraFromScreen));
        }
    }

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_expand_view, container, false);

        init();
        return mainView;
    }

    private void init() {
        //Set Sliding Menu enable        homeActivity.setSlidingMenuEnable(false);
        homeActivity.setSelectedPositionInSlidingMenu(3);

        //Setup Actionbar        TextView actionBarTitle = (TextView) mainView.findViewById(R.id.txt_actionbar_title);
        actionBarTitle.setText(getString(R.string.expand_view));
        ImageView actionBarMenu = (ImageView) mainView.findViewById(R.id.img_actionbar_menu);
        actionBarMenu.setImageResource(R.mipmap.ic_back);

        pupulateData();
        initNSetRecyclerViewEvents();
        bindList(alstExpandView);
    }

    private void initNSetRecyclerViewEvents() {
        recyclerViewExpandView = (RecyclerView) mainView.findViewById(R.id.frag_expand_view_recyclerview);
        recyclerViewExpandView.setHasFixedSize(true);
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerViewExpandView.setLayoutManager(layoutManager);
    }

    /*add data in arraylist*/    public void pupulateData() {
        alstExpandView = new ArrayList<>();
        for (int i = 0; i < arrayTitle.length; i++) {
            alstExpandView.add(new ExpandViewModel(i,arrayTitle[i], arrayDesc[i], arrayImages[i],false));
        }
    }

    private void bindList(ArrayList<ExpandViewModel> alstExpandView) {
        mExpanViewAdapter = new ExpandViewAdapter(getActivity(), alstExpandView);
        recyclerViewExpandView.setAdapter(mExpanViewAdapter);
    }

    @Override    public void clickEvent(View v) {
        super.clickEvent(v);
        switch (v.getId()) {
            case R.id.img_actionbar_menu: // Back button                onBackPressed();
                break;

            case R.id.list_item_expand_view_lytmain:
                ExpandViewModel mExpandViewModel = (ExpandViewModel) v.getTag();
                for(int i =0;i<alstExpandView.size();i++) {
                    if(alstExpandView.get(i) == mExpandViewModel) {
                        mExpandViewModel.setChecked(true);
                        alstExpandView.set(mExpandViewModel.getPosition(), mExpandViewModel);
                    }else{
                        alstExpandView.get(i).setChecked(false);
                        alstExpandView.set(mExpandViewModel.getPosition(), mExpandViewModel);
                    }
                    recyclerViewExpandView.smoothScrollToPosition(mExpandViewModel.getPosition());
                    mExpanViewAdapter.notifyDataSetChanged();
                }
                break;
        }
    }

    /**     * Handle Activity click events     */    @Override    public void onBackPressed() {
        if(fromScreen.equalsIgnoreCase(getResources().getString(R.string.extraMenu))){
            homeActivity.pushFragments(new DashBoardFragment(), true, true, true);
        }else{
            homeActivity.popFragment();
        }
    }
}


4)LatestUpdateCategoryFragment.java
==================================
package com.credencys.myapplication.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.credencys.myapplication.R;
import com.credencys.myapplication.adapter.LatestUpdateCategoryAdapter;
import com.credencys.myapplication.api.RestClient;
import com.credencys.myapplication.models.LatestUpdateCategoryModel;
import com.credencys.myapplication.utility.ToastHelper;
import com.credencys.myapplication.utility.Utils;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;

/** * Created by manisha on 25/1/17. */public class LatestUpdateCategoryFragment extends BaseFragment {
    private View mainView;
    private RecyclerView recyclerViewLatestUpdate;
    private TextView txtNoRecords;
    private ArrayList<LatestUpdateCategoryModel.Items> alstLatestUpdate;
    private int fragPosition = 0;

    @Override    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fragPosition = getArguments().getInt(getResources().getString(R.string.fragment_position));
    }

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_latest_update_category, container, false);

        init();

        return mainView;
    }

    @Override    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isResumed()) {
            //Only manually call onResume if fragment is already visible            //Otherwise allow natural fragment lifecycle to call onResume            onResume();
        }
    }

    @Override    public void onResume() {
        super.onResume();
        if (!getUserVisibleHint()) {
            return;
        }
        callApi();
        Log.e("Position", "Position" + fragPosition);
    }

    public void callApi() {
        new Handler().postDelayed(new Runnable() {
            @Override            public void run() {
                /*get and set data as per selected item */                if (fragPosition == 0) {
                    if (Utils.getInstance().checkInternetConnection(getActivity())) {
                        getTopStoryData(true, true);
                    } else {
                        alstLatestUpdate = homeActivity.dbHelper.GetTopStoryData();
                        bindList(alstLatestUpdate);
                        ToastHelper.getInstance().showToast(getActivity(),getResources().getString(R.string.msgInternetConnectionNotAvailable));

                    }
                } else if (fragPosition == 1) {
                    if (Utils.getInstance().checkInternetConnection(getActivity())) {
                        getCricketData(true, true);
                    } else {
                        alstLatestUpdate = homeActivity.dbHelper.GetCricketData();
                        bindList(alstLatestUpdate);
                        ToastHelper.getInstance().showToast(getActivity(),getResources().getString(R.string.msgInternetConnectionNotAvailable));
                    }
                } else if (fragPosition == 2) {
                    if (Utils.getInstance().checkInternetConnection(getActivity())) {
                        getBusinessData(true, true);
                    } else {
                        alstLatestUpdate = homeActivity.dbHelper.GetBusinessData();
                        bindList(alstLatestUpdate);
                        ToastHelper.getInstance().showToast(getActivity(),getResources().getString(R.string.msgInternetConnectionNotAvailable));

                    }
                } else if (fragPosition == 3) {
                    if (Utils.getInstance().checkInternetConnection(getActivity())) {
                        getTechnologyData(true, true);
                    } else {
                        alstLatestUpdate = homeActivity.dbHelper.GetTechnologyData();
                        bindList(alstLatestUpdate);
                        ToastHelper.getInstance().showToast(getActivity(),getResources().getString(R.string.msgInternetConnectionNotAvailable));

                    }
                } else if (fragPosition == 4) {
                    if (Utils.getInstance().checkInternetConnection(getActivity())) {
                        getLifeStyleData(true, true);
                    } else {
                        alstLatestUpdate = homeActivity.dbHelper.GetLifeStyleData();
                        bindList(alstLatestUpdate);
                        ToastHelper.getInstance().showToast(getActivity(),getResources().getString(R.string.msgInternetConnectionNotAvailable));

                    }
                }
            }
        }, getResources().getInteger(android.R.integer.config_mediumAnimTime));
    }

   /* init recyclerView*/    private void init() {
        txtNoRecords = (TextView) mainView.findViewById(R.id.frag_latest_update_txt_norecords);
        homeActivity.setSelectedPositionInSlidingMenu(1);
        initNSetRecyclerViewEvents();
    }

    private void initNSetRecyclerViewEvents() {
        recyclerViewLatestUpdate = (RecyclerView) mainView.findViewById(R.id.frag_latest_update_recycler_view);
        recyclerViewLatestUpdate.setHasFixedSize(true);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerViewLatestUpdate.setLayoutManager(layoutManager);
    }

    @Override    public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) {
       /* get Api response and set data in list and insert into database*/        if (reqCode == getResources().getInteger(R.integer.reqCodeTopStory)) {
            LatestUpdateCategoryModel mLatestUpdateCategoryModel = (LatestUpdateCategoryModel) response.body();
            getData(mLatestUpdateCategoryModel);
            insertTopStory();

        } else if (reqCode == getResources().getInteger(R.integer.reqCodeCricket)) {
            LatestUpdateCategoryModel mLatestUpdateCategoryModel = (LatestUpdateCategoryModel) response.body();
            getData(mLatestUpdateCategoryModel);
            insertCricket();

        } else if (reqCode == getResources().getInteger(R.integer.reqCodeBusiness)) {
            LatestUpdateCategoryModel mLatestUpdateCategoryModel = (LatestUpdateCategoryModel) response.body();
            getData(mLatestUpdateCategoryModel);
            insertBusiness();

        } else if (reqCode == getResources().getInteger(R.integer.reqCodeTechnology)) {
            LatestUpdateCategoryModel mLatestUpdateCategoryModel = (LatestUpdateCategoryModel) response.body();
            getData(mLatestUpdateCategoryModel);
            insertTechnology();

        } else if (reqCode == getResources().getInteger(R.integer.reqCodeLifeStyle)) {
            LatestUpdateCategoryModel mLatestUpdateCategoryModel = (LatestUpdateCategoryModel) response.body();
            getData(mLatestUpdateCategoryModel);
            insertLifeStyle();
        }
    }

    @Override    public void onApiError(Call<Object> call, Object object, int reqCode) {
        ToastHelper.getInstance().showToast(getActivity(), object.toString());
    }

   /* get data from service and add into  arraylist*/    public void getData(LatestUpdateCategoryModel categoryModel) {
        if (alstLatestUpdate == null)
            alstLatestUpdate = new ArrayList<LatestUpdateCategoryModel.Items>();

        if (categoryModel.getItems() != null)
            alstLatestUpdate.addAll(categoryModel.getItems());
    }

    /* get data from service and add into database topstory table*/    public void insertTopStory() {
        if (alstLatestUpdate.size() > 0) {
            homeActivity.dbHelper.deleteTopStory();
            for (int i = 0; i < alstLatestUpdate.size(); i++) {
                homeActivity.dbHelper.insertTopStoryData(alstLatestUpdate.get(i));
            }
        }
        bindList(alstLatestUpdate);
    }

    /* get data from service and add into database cricket table*/    public void insertCricket() {

        if (alstLatestUpdate.size() > 0) {
            homeActivity.dbHelper.deleteCricket();
            for (int i = 0; i < alstLatestUpdate.size(); i++) {
                homeActivity.dbHelper.insertCricketData(alstLatestUpdate.get(i));
            }
        }
        bindList(alstLatestUpdate);
    }

    /* get data from service and add into database business table*/    public void insertBusiness() {
        if (alstLatestUpdate.size() > 0) {
            homeActivity.dbHelper.deleteBusiness();
            for (int i = 0; i < alstLatestUpdate.size(); i++) {
                homeActivity.dbHelper.insertBusinessData(alstLatestUpdate.get(i));
            }
        }
        bindList(alstLatestUpdate);
    }

    /* get data from service and add into database technology table*/    public void insertTechnology() {
        if (alstLatestUpdate.size() > 0) {
            homeActivity.dbHelper.deleteTechnology();
            for (int i = 0; i < alstLatestUpdate.size(); i++) {
                homeActivity.dbHelper.insertTechnologyData(alstLatestUpdate.get(i));
            }
        }
        bindList(alstLatestUpdate);
    }

    /* get data from service and add into database lifestyle table*/    public void insertLifeStyle() {
        if (alstLatestUpdate.size() > 0) {
            homeActivity.dbHelper.deleteLifeStyle();
            for (int i = 0; i < alstLatestUpdate.size(); i++) {
                homeActivity.dbHelper.insertLifeStyleData(alstLatestUpdate.get(i));
            }
        }
        bindList(alstLatestUpdate);
    }

    /**     * Function for bind  list     */    private void bindList(ArrayList<LatestUpdateCategoryModel.Items> alstLatestUpdate) {
        if (alstLatestUpdate != null && alstLatestUpdate.size() > 0) {
            recyclerViewLatestUpdate.setVisibility(View.VISIBLE);
            txtNoRecords.setVisibility(View.GONE);
            LatestUpdateCategoryAdapter adapter = (LatestUpdateCategoryAdapter) recyclerViewLatestUpdate.getAdapter();

            if (adapter != null && adapter.getItemCount() > 0) {
                adapter.setListItems(alstLatestUpdate);
            } else {
                adapter = new LatestUpdateCategoryAdapter(getActivity(), alstLatestUpdate);
                recyclerViewLatestUpdate.setAdapter(adapter);
            }
        } else {
            recyclerViewLatestUpdate.setVisibility(View.GONE);
            txtNoRecords.setVisibility(View.VISIBLE);
        }
    }

    /**     * Reset variables     */    public void resetListVariables() {
        alstLatestUpdate = new ArrayList<LatestUpdateCategoryModel.Items>();
        recyclerViewLatestUpdate.setAdapter(null);
    }

    /**     * Function for call api for get top story data     */    public void getTopStoryData(boolean resetVariables, boolean showDialog) {
        if (resetVariables)
            resetListVariables();
        Call<LatestUpdateCategoryModel> objectCall = RestClient.getApiClient().getTopStory();
        homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeTopStory), getActivity().getResources().getString(R.string.msgLoading),showDialog);
    }

    /**     * Function for call api for get cricket data     */    public void getCricketData(boolean resetVariables, boolean showDialog) {
        if (resetVariables)
            resetListVariables();
        Call<LatestUpdateCategoryModel> objectCall = RestClient.getApiClient().getCricketData();
        homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeCricket),getActivity().getResources().getString(R.string.msgLoading), showDialog);
    }

    /**     * Function for call api for get business data     */    public void getBusinessData(boolean resetVariables, boolean showDialog) {
        if (resetVariables)
            resetListVariables();
        Call<LatestUpdateCategoryModel> objectCall = RestClient.getApiClient().getBusinessData();
        homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeBusiness), getActivity().getResources().getString(R.string.msgLoading),showDialog);
    }

    /**     * Function for call api for get technology data     */    public void getTechnologyData(boolean resetVariables, boolean showDialog) {
        if (resetVariables)
            resetListVariables();
        Call<LatestUpdateCategoryModel> objectCall = RestClient.getApiClient().getTechnology();
        homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeTechnology), getActivity().getResources().getString(R.string.msgLoading),showDialog);
    }

    /**     * Function for call api for get lifestyle data     */    public void getLifeStyleData(boolean resetVariables, boolean showDialog) {
        if (resetVariables)
            resetListVariables();
        Call<LatestUpdateCategoryModel> objectCall = RestClient.getApiClient().getLifestyleData();
        homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeLifeStyle), getActivity().getResources().getString(R.string.msgLoading),showDialog);
    }
}

5)LatestUpdateFragment.java
==========================
package com.credencys.myapplication.fragment;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.credencys.myapplication.R;
import com.credencys.myapplication.adapter.PagerAdapterLatestUpdate;

/** * Created by manisha on 25/1/17. */
public class LatestUpdateFragment extends BaseFragment{
  private View mainView;
  private ViewPager viewPagerLatestUpdate;
  private TabLayout tabLayoutLatestUpdate;
  private PagerAdapterLatestUpdate mPagerAdapterLatestUpdate;
  private String fromScreen="";

  @Override  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Bundle bundle = getArguments();
      if (bundle != null) {
          fromScreen = bundle.getString(getResources().getString(R.string.extraFromScreen));
      }
  }

  @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      mainView=inflater.inflate(R.layout.fragment_latest_update, container, false);

      init();
      initTabLayout();

      return mainView;
  }

  private void init()
  {
      //Set Sliding Menu enable      homeActivity.setSlidingMenuEnable(false);

      //Set up rest client      homeActivity.restClient.setupRestClient(getActivity());
      homeActivity.setSelectedPositionInSlidingMenu(1);

      //Setup Actionbar      TextView actionBarTitle= (TextView) mainView.findViewById(R.id.txt_actionbar_title);
      actionBarTitle.setText(getString(R.string.latest_update));
      ImageView  actionBarMenu = (ImageView) mainView.findViewById(R.id.img_actionbar_menu);
      actionBarMenu.setImageResource(R.mipmap.ic_back);
  }

  private void initTabLayout()
  {
      viewPagerLatestUpdate= (ViewPager) mainView.findViewById(R.id.fragment_latest_update_view_pager);
      tabLayoutLatestUpdate= (TabLayout) mainView.findViewById(R.id.fragment_latest_update_tab_layout);

      if(mPagerAdapterLatestUpdate==null)
          mPagerAdapterLatestUpdate=new PagerAdapterLatestUpdate(getActivity(),getChildFragmentManager());

      viewPagerLatestUpdate.setAdapter(mPagerAdapterLatestUpdate);
      tabLayoutLatestUpdate.setupWithViewPager(viewPagerLatestUpdate);
  }

    @Override    public void clickEvent(View v) {
        super.clickEvent(v);

        switch (v.getId())
        {
            case R.id.img_actionbar_menu: // Back button                onBackPressed();
                break;
        }
    }

    /**     * Handle Activity click events     */    @Override    public void onBackPressed() {
        if(fromScreen.equalsIgnoreCase(getResources().getString(R.string.extraMenu))){
            homeActivity.pushFragments(new DashBoardFragment(), true, true, true);
        }else{
            homeActivity.popFragment();
        }
    }
}

6)LoginFragment.java
===================
package com.credencys.myapplication.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;

import com.credencys.myapplication.R;
import com.credencys.myapplication.models.LoginModel;
import com.credencys.myapplication.utility.CustomDialog;
import com.credencys.myapplication.utility.PrefHelper;
import com.credencys.myapplication.utility.Utils;
import com.google.gson.Gson;

/** * Created by manisha on 24/1/17. */
public class LoginFragment extends BaseFragment {
    private EditText edtEmail,edtPassword;
    private CheckBox chkRememberMe;
    private String mEmail="",mPassword="";
    public boolean ischecked = false;
    private View view;
    private boolean is_login;

    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Gson gson = new Gson();
        if(PrefHelper.getString(getActivity().getString(R.string.prefLoginUserData),"").length()>0) {
            homeActivity.loginModel = gson.fromJson(PrefHelper.getString(getActivity().getString(R.string.prefLoginUserData), ""), LoginModel.class);
        }
        is_login = PrefHelper.getBoolean(getResources().getString(R.string.is_login),false);
        if(is_login) {
            homeActivity.removeAllFragment();
            homeActivity.pushFragments(new DashBoardFragment(), true, false, true);
        }
    }

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_login, container, false);
        initData();
        if(homeActivity.loginModel != null) {
            mEmail = homeActivity.loginModel.getEmail();
            mPassword = homeActivity.loginModel.getPassword();
        }

        boolean ischecked = PrefHelper.getBoolean(getResources().getString(R.string.pref_remember_me), false);
        if (ischecked == true) {
            edtEmail.setText(mEmail);
            edtPassword.setText(mPassword);
            chkRememberMe.setChecked(true);
        } else {
            edtEmail.setText("");
            edtPassword.setText("");
            chkRememberMe.setChecked(false);
        }
        return view;
    }

    private void initData(){
        Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.frag_login_rlyt_parent));
        edtEmail = (EditText)view.findViewById(R.id.frag_login_edt_email);
        edtPassword = (EditText)view.findViewById(R.id.frag_login_edt_password);
        chkRememberMe = (CheckBox) view.findViewById(R.id.frag_login_chk_remember_me);
        homeActivity.setSlidingMenuEnable(false);
        if (ischecked == true) {
            edtEmail.setText(mEmail);
            edtPassword.setText(mPassword);
            chkRememberMe.setChecked(true);
        }
    }

    /**     * Handle Activity click events     */    public void clickEvent(View view) {
        switch (view.getId()) {
            case R.id.frag_login_btn_login:
                    if (FieldValidation()) {
                        if (homeActivity.dbHelper.isUserExists(edtEmail.getText().toString().trim(), edtPassword.getText().toString().trim())) {
                            if (chkRememberMe.isChecked()) {
                                PrefHelper.setBoolean(getResources().getString(R.string.pref_remember_me), true);
                            } else {
                                PrefHelper.setBoolean(getResources().getString(R.string.pref_remember_me), false);
                            }

                            PrefHelper.setBoolean(getResources().getString(R.string.is_login), true);
                            homeActivity.removeAllFragment();
                            homeActivity.pushFragments(new DashBoardFragment(), true, false, true);
                        } else {
                            CustomDialog.getInstance().showMessageDialog(getActivity(),
                                    getResources().getString(R.string.please_enter_valid_username_password));
                        }
                    }
                break;

            case R.id.frag_login_btn_sign_up:
                homeActivity.pushFragments(new RegistrationFragment(), true, false, true);
                break;
        }
    }

    @Override    public void onStop() {
        super.onStop();
    }

    /*Validate fields*/    public boolean FieldValidation() {
        boolean flag = true;
        mEmail = edtEmail.getText().toString().trim();
        mPassword = edtPassword.getText().toString().trim();

        if (!Utils.getInstance().validateString(mEmail)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_email));
        } else if (!Utils.getInstance().isEmailValid(mEmail)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_valid_email));
        } else if (!Utils.getInstance().validateString(mPassword)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_password));
        }
        return flag;
    }

    /**     * Handle Activity click events     */    @Override    public void onBackPressed() {
        homeActivity.popFragment();
    }
}

7)MyGalleryFragment.java
=======================
package com.credencys.myapplication.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.credencys.myapplication.R;
import com.credencys.myapplication.adapter.MyGalleryAdapter;
import com.credencys.myapplication.widgets.TouchImageView;

import java.util.ArrayList;

/** * Created by manisha on 25/1/17. */
public class MyGalleryFragment extends BaseFragment {
    private View mainView;
    private String fromScreen="";
    private ArrayList<String>alstGalleryImages;
    private RecyclerView recyclerViewMyGallery;
    private GridLayoutManager gridManager;
    private TextView txtNoRecord;

    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            fromScreen = bundle.getString(getResources().getString(R.string.extraFromScreen));
        }
    }

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_my_gallery, container, false);

        init();
        return mainView;
    }

    private void init()
    {
        //Set Sliding Menu enable        homeActivity.setSelectedPositionInSlidingMenu(4);
        homeActivity.setSlidingMenuEnable(false);

        //Setup Actionbar        TextView actionBarTitle= (TextView) mainView.findViewById(R.id.txt_actionbar_title);
        actionBarTitle.setText(getString(R.string.my_gallery));
        ImageView actionBarMenu = (ImageView) mainView.findViewById(R.id.img_actionbar_menu);
        actionBarMenu.setImageResource(R.mipmap.ic_back);

        txtNoRecord = (TextView)mainView.findViewById(R.id.frag_my_gallery_txt_norecords);
        initRecyclerViewEvents();bindList(alstGalleryImages);
    }

    private void initRecyclerViewEvents() {
        alstGalleryImages = new ArrayList<>();
        alstGalleryImages = getGallaryImagesPath(getActivity());

        recyclerViewMyGallery = (RecyclerView) mainView.findViewById(R.id.frag_my_gallery_recycler_view);
        recyclerViewMyGallery.setHasFixedSize(true);
        gridManager = new GridLayoutManager(getActivity(), 3);
        recyclerViewMyGallery.setLayoutManager(gridManager);
        bindList(alstGalleryImages);
    }

    private void bindList(ArrayList<String> alstGalleryImages) {
        if (alstGalleryImages != null && alstGalleryImages.size() > 0) {
            recyclerViewMyGallery.setVisibility(View.VISIBLE);
            txtNoRecord.setVisibility(View.GONE);
            MyGalleryAdapter  adapter = new MyGalleryAdapter(getActivity(), alstGalleryImages);
            recyclerViewMyGallery.setAdapter(adapter);
        } else {
            txtNoRecord.setVisibility(View.VISIBLE);
            recyclerViewMyGallery.setVisibility(View.GONE);
        }
    }

    /**     * Getting All Images Path.     *     * @param activity     *            the activity     * @return ArrayList with images Path of gallery     */    private ArrayList<String> getGallaryImagesPath(Activity activity) {
        Uri uri;
        Cursor cursor;
        int column_index_data;
        ArrayList<String> listOfAllImages = new ArrayList<String>();
        String absolutePathOfImage = null;
        uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String[] projection = { MediaStore.MediaColumns.DATA,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME };
        cursor = activity.getContentResolver().query(uri, projection, null,
                null, null);

        column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);

        while (cursor.moveToNext()) {
            absolutePathOfImage = cursor.getString(column_index_data);
            listOfAllImages.add(absolutePathOfImage);
        }
        return listOfAllImages;
    }

    /**Show Image in full screen with pinch zoom */    private void openImageInFullScreen(String imageUrl)
    {
        if(imageUrl!=null && imageUrl.length()>0)
        {
            final Dialog dialog=new Dialog(getActivity(),R.style.DialogTheme);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.setContentView(R.layout.dialog_fullscreen_view);

            /* Set Dialog width match parent*/            dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);

            final TouchImageView imgGalleryImage= (TouchImageView) dialog.findViewById(R.id.dialog_fullscreen_view_image);
            ImageView imgClose= (ImageView) dialog.findViewById(R.id.dialog_fullscreen_view_image_img_close);

            /**Note: Set Zoomable false until image not load, and set scale type CENTER_INSIDE to display placeholder proper*/            imgGalleryImage.enableZoom(false);
            imgGalleryImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

            Glide.with(this)
                    .load(imageUrl)
                    .placeholder(R.mipmap.default_no_image)
                    .error(R.mipmap.default_no_image)
                    .listener(new RequestListener<String, GlideDrawable>() {
                        @Override                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            imgGalleryImage.enableZoom(false);
                            return false;
                        }

                        @Override                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            imgGalleryImage.enableZoom(true);
                            imgGalleryImage.setScaleType(ImageView.ScaleType.MATRIX);
                            return false;
                        }
                    })
                    .dontAnimate()
                    .into(imgGalleryImage);
            imgClose.setOnClickListener(new View.OnClickListener() {
                @Override                public void onClick(View view) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

    @Override    public void clickEvent(View v) {
        super.clickEvent(v);
        switch (v.getId())
        {
            case R.id.img_actionbar_menu: // Back button                onBackPressed();
                break;

            case R.id.list_item_my_gallery_rlyt_gallery:
                String imageUrl = (String) v.getTag();
                openImageInFullScreen(imageUrl);
                break;
        }
    }

    /**     * Handle Activity click events     */    @Override    public void onBackPressed() {
        if(fromScreen.equalsIgnoreCase(getResources().getString(R.string.extraMenu))){
            homeActivity.pushFragments(new DashBoardFragment(), true, true, true);
        }else{
            homeActivity.popFragment();
        }
    }
}

8)NearByLocationFragment.java
============================
package com.credencys.myapplication.fragment;

/** * Created by Manisha on 2/2/2017. */
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.credencys.myapplication.R;
import com.credencys.myapplication.api.RestClient;
import com.credencys.myapplication.interfaces.LocationUpdateListener;
import com.credencys.myapplication.models.NearByLocationModel;
import com.credencys.myapplication.utility.CustomDialog;
import com.credencys.myapplication.utility.PrefHelper;
import com.credencys.myapplication.utility.ToastHelper;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Response;

public class NearByLocationFragment extends BaseFragment implements OnMapReadyCallback {
    private GoogleMap googleMap;
    private View mainView;
    private double latitude = 0, longitude = 0;
    private String fromScreen = "";

    @Override    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            fromScreen = bundle.getString(getResources().getString(R.string.extraFromScreen));
        }
    }

    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mainView = inflater.inflate(R.layout.fragment_near_by_location, container, false);

        init();

        homeActivity.getCurrentLocation(new LocationUpdateListener() {
            @Override            public void onLocationUpdate(Location location) {
                PrefHelper.setDouble(getString(R.string.prefUserLatitude), location.getLatitude());
                PrefHelper.setDouble(getString(R.string.prefUserLongitude), location.getLongitude());

                initMap();
            }

            @Override            public void onLocationPermissionDeny() {

            }

            @Override            public void onGPSRequestDeny() {

            }
        });


        return mainView;
    }

    private void init() {
        //Set Sliding Menu enable        homeActivity.setSlidingMenuEnable(false);

        //Set up rest client get locations        homeActivity.restClient.setupMapRestClient(getActivity());

        //Setup Actionbar        TextView actionBarTitle = (TextView) mainView.findViewById(R.id.txt_actionbar_title);
        actionBarTitle.setText(getString(R.string.near_by_location));
        ImageView actionBarMenu = (ImageView) mainView.findViewById(R.id.img_actionbar_menu);
        actionBarMenu.setImageResource(R.mipmap.ic_back);
    }

    /*Initialize Google map*/    private void initMap() {
        try {
            new Handler().postDelayed(new Runnable() {

                @Override                public void run() {
                    if (isAdded()) {
                        FragmentManager fm = getChildFragmentManager();
                        SupportMapFragment mapFragment = SupportMapFragment.newInstance();
                        fm.beginTransaction().replace(R.id.frag_near_by_location_container, mapFragment).commit();
                        mapFragment.getMapAsync(NearByLocationFragment.this);
                    }
                }
            }, 400);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*get nearby location on map ready Google map*/    @Override    public void onMapReady(GoogleMap googleMap) {
        CustomDialog.getInstance().hide();
        this.googleMap = googleMap;

        setLocationOnMap();
        getNearByLocation(true);
    }

    private void setLocationOnMap() {
        try {
            latitude = PrefHelper.getDouble(getResources().getString(R.string.prefUserLatitude),0);
            longitude = PrefHelper.getDouble(getResources().getString(R.string.prefUserLongitude),0);

            if (latitude > 0 && longitude > 0) {
                LatLng latLng = new LatLng(latitude, longitude);
                googleMap.clear();

                googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                googleMap.animateCamera(CameraUpdateFactory.zoomIn());
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(20.0f), 1000, null);

                /* set Marker on current location*/                googleMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_pin))
                        .anchor(0.5f, 0.5f) // Anchors the marker on the bottom left                        .position(latLng));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

   /* function for call api to get  near by location*/    public void getNearByLocation(boolean showDialog) {
        String location = latitude + "," + longitude;
        if (latitude > 0 && longitude > 0) {
            Call<NearByLocationModel> objectCall = RestClient.getApiClient().getNearByLocation(location, "distance", "nearbylocation", getResources().getString(R.string.google_maps_key));
            homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeNearByLocation), getActivity().getResources().getString(R.string.msgFetchingData), showDialog);
        }
    }

    @Override    public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) {
        if (reqCode == getResources().getInteger(R.integer.reqCodeNearByLocation)) {
            NearByLocationModel nearByLocationModel = (NearByLocationModel) response.body();

           /* get and near by location from api and into arrayList */            ArrayList<NearByLocationModel.Results> alstNames = new ArrayList<>();
            if (nearByLocationModel.getResults() != null)
                alstNames.addAll(nearByLocationModel.getResults());

             /* set Marker on near by location */            for (int i = 0; i < alstNames.size(); i++) {
                MarkerOptions markerOptions = new MarkerOptions();

                LatLng latLng = new LatLng(alstNames.get(i).getGeometry().getLocation().getLat(), alstNames.get(i).getGeometry().getLocation().getLng());
                markerOptions.position(latLng);
                markerOptions.title(alstNames.get(i).getName());
                googleMap.addMarker(markerOptions);
            }
        }
    }

    @Override    public void onApiError(Call<Object> call, Object object, int reqCode) {
        ToastHelper.getInstance().showToast(getActivity(), object.toString());
    }

    @Override    public void clickEvent(View v) {
        super.clickEvent(v);
        switch (v.getId()) {
            case R.id.img_actionbar_menu: // Back button                onBackPressed();
                break;
        }
    }

    /**     * Handle Activity click events     */    @Override    public void onBackPressed() {
        if (fromScreen.equalsIgnoreCase(getResources().getString(R.string.extraMenu))) {
            homeActivity.pushFragments(new DashBoardFragment(), true, true, true);
        } else {
            homeActivity.popFragment();
        }
    }
}

9)ProfileFragment.java
======================
package com.credencys.myapplication.fragment;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.credencys.myapplication.R;
import com.credencys.myapplication.activity.ImageCropActivity;
import com.credencys.myapplication.utility.Constants;
import com.credencys.myapplication.utility.CustomDialog;
import com.credencys.myapplication.utility.FileUtils;
import com.credencys.myapplication.utility.PermissionUtil;
import com.credencys.myapplication.utility.PrefHelper;
import com.credencys.myapplication.utility.Utils;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;

/** * Created by manisha on 26/1/17. */
public class ProfileFragment extends BaseFragment {
    private EditText edtFirstName, edtLastName, edtEmail, edtPhoneNumber;
    private TextView txtBirthDate;
    private String mFirstName = "", mLastName = "", mEmail = "", mBirthDate = "", mPhoneNumber = "";
    private int mGender;
    private RadioGroup radioGroupGender;
    private RadioButton rbtnMale, rbtnFemale;
    private View view;
    private ImageView imgProfile;
    private RelativeLayout rlytParent;
    final int REQ_CODE_PERMISSION_CAMERA = 40;
    final int REQ_CODE_PERMISSION_GALLERY = 41;
    private Uri outputFileUri;

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_profile, container, false);
        initData();

        return view;
    }

    public void initData() {
        //Hide keyboard        rlytParent = (RelativeLayout) view.findViewById(R.id.frag_profile_parentView);
        Utils.getInstance().hideKeyboard(rlytParent, getActivity());

        //setActionbar        Utils.getInstance().hideKeyboard(rlytParent, getActivity());
        TextView txtActionbarTitle = (TextView) view.findViewById(R.id.txt_actionbar_title);
        txtActionbarTitle.setText(getResources().getString(R.string.profile));
        homeActivity.setSelectedPositionInSlidingMenu(-1);

        edtFirstName = (EditText) view.findViewById(R.id.frag_profile_edt_first_name);
        edtLastName = (EditText) view.findViewById(R.id.frag_profile_edt_last_name);
        edtEmail = (EditText) view.findViewById(R.id.frag_profile_edt_email);
        edtEmail.getBackground().setColorFilter(getResources().getColor(R.color.colorAccent), PorterDuff.Mode.SRC_ATOP);
        txtBirthDate = (TextView) view.findViewById(R.id.frag_profile_txt_birth_date);
        edtPhoneNumber = (EditText) view.findViewById(R.id.frag_profile_edt_phone_number);
        radioGroupGender = (RadioGroup) view.findViewById(R.id.frag_profile_radio_group);
        rbtnMale = (RadioButton) view.findViewById(R.id.frag_profile_rbtn_male);
        rbtnFemale = (RadioButton) view.findViewById(R.id.frag_profile_rbtn_female);
        imgProfile = (ImageView) view.findViewById(R.id.frag_profile_img_profile);

        setData();

    }

    public void setData() {
        edtFirstName.setText(homeActivity.loginModel.getFirstName());
        edtLastName.setText(homeActivity.loginModel.getLastName());
        edtEmail.setText(homeActivity.loginModel.getEmail());
        txtBirthDate.setText(homeActivity.loginModel.getDob());
        edtPhoneNumber.setText(homeActivity.loginModel.getPhoneNumber());
        outputFileUri =  Uri.parse(homeActivity.loginModel.getUserImage());

        setProfileImage(outputFileUri);

        if (homeActivity.loginModel.getGender() == 0) {
            rbtnMale.setChecked(true);
            rbtnFemale.setChecked(false);
        } else {
            rbtnMale.setChecked(false);
            rbtnFemale.setChecked(true);
        }
    }

    /**     * Handle Activity click events     */    public void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.frag_profile_btn_save:
                if (FieldValidation()) {
                    mEmail = edtEmail.getText().toString().trim();
                    mBirthDate = txtBirthDate.getText().toString().trim();
                    mPhoneNumber = edtPhoneNumber.getText().toString().trim();
                    int selectedId = radioGroupGender.getCheckedRadioButtonId();
                    RadioButton radioButton = (RadioButton) view.findViewById(selectedId);
                    if (radioButton.getText().toString().equalsIgnoreCase("male")) {
                        mGender = 0;
                    } else if (radioButton.getText().toString().equalsIgnoreCase("female")) {
                        mGender = 1;
                    }

                    PrefHelper.setBoolean(getResources().getString(R.string.is_login),true);
                    homeActivity.dbHelper.updateProfile(homeActivity.loginModel.getUserId(),  mFirstName, mLastName,homeActivity.loginModel.getPassword(), mEmail,mBirthDate, mPhoneNumber, outputFileUri.toString(), mGender);
                    homeActivity.removeAllFragment();
                    homeActivity.pushFragments(new DashBoardFragment(), true, false, true);

                }
                break;

            case R.id.frag_profile_txt_birth_date:
                Utils.getInstance().hideKeyboard(view, getActivity());
                showDatePickerDialog();
                break;

            case R.id.frag_profile_img_profile:
                dialogChoosePicture();
                break;

            case R.id.img_actionbar_menu:
                handleBackPressEvent(false);
                break;
        }
    }

    public void showDatePickerDialog() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear + 1) + "/" + String.valueOf(year);
                txtBirthDate.setText(date);

            }

        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());
        datePickerDialog.show();
    }

    public void dialogChoosePicture() {
        final Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Dialog);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.custom_dialog_media_chooser);
        TextView btnGallery = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_library);
        btnGallery.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                dialog.dismiss();
                openGallery();
            }
        });

        TextView btnCamera = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_camera);
        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                dialog.dismiss();
                openCameraForCaptureImage();
            }
        });

        TextView btnCancel = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQ_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK) {
            Intent intent = new Intent(getActivity(), ImageCropActivity.class);
            intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100);
            intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100);
            intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri);
            startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE);

        } else if (requestCode == Constants.REQ_CODE_GALLERY_IMAGE && resultCode == Activity.RESULT_OK && null != data) {

            if (data != null && data.getData() != null) {
                Uri selectedImageUri = data.getData();
                String picturePath = Utils.getInstance().getRealPathFromURI(getActivity(), selectedImageUri);
                String copiedFilepath = FileUtils.getInstance().copyFile(picturePath, FileUtils.getInstance().getFilePath(getActivity(), FileUtils.MEDIA_TYPE.PICTURE));

                Intent intent = new Intent(getActivity(), ImageCropActivity.class);
                intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100);
                intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100);
                outputFileUri = Uri.fromFile(new File(copiedFilepath));
                intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri);
                startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE);

            }

        } else if (requestCode == Constants.REQ_CODE_CROP_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                outputFileUri = bundle.getParcelable(ImageCropActivity.EXTRA_IMAGE_URI);
                setProfileImage(outputFileUri);
            }
        }
    }

    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        ArrayList<String> listNotGrantedPermissions;
        switch (requestCode) {
            case REQ_CODE_PERMISSION_CAMERA:
                listNotGrantedPermissions = PermissionUtil.getInstance().verifyPermissions(permissions, grantResults);
                if (listNotGrantedPermissions != null && listNotGrantedPermissions.size() > 0) {
                    checkCameraPermissions(listNotGrantedPermissions, requestCode, false);
                } else {
                    openCameraForCaptureImage();
                }
                break;

            case REQ_CODE_PERMISSION_GALLERY:
                listNotGrantedPermissions = PermissionUtil.getInstance().verifyPermissions(permissions, grantResults);
                if (listNotGrantedPermissions != null && listNotGrantedPermissions.size() > 0) {
                    checkCameraPermissions(listNotGrantedPermissions, requestCode, false);
                } else {
                    openGallery();
                }
                break;
        }
    }

    private void openGallery() {
        ArrayList<String> listPermissionsNeed = PermissionUtil.getInstance().getGalleryPermission();
        if (checkCameraPermissions(listPermissionsNeed, REQ_CODE_PERMISSION_GALLERY, true)) {
            Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, Constants.REQ_CODE_GALLERY_IMAGE);
        }
    }

    private void openCameraForCaptureImage() {
        ArrayList<String> listPermissionsNeed = PermissionUtil.getInstance().getCameraPermissionsList();
        if (checkCameraPermissions(listPermissionsNeed, REQ_CODE_PERMISSION_CAMERA, true)) {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    /*for Nougat to get uri*/                    outputFileUri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", new File(FileUtils.getInstance().getFilePath(getActivity(),FileUtils.MEDIA_TYPE.PICTURE)));
                }else {
                    outputFileUri = FileUtils.getInstance().getFileUri(getActivity(), FileUtils.MEDIA_TYPE.PICTURE);
                }

                Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

                startActivityForResult(captureIntent, Constants.REQ_CODE_CAPTURE_IMAGE);
            } catch (ActivityNotFoundException e) {
                e.getMessage();
            }
        }
    }

    private boolean checkCameraPermissions(ArrayList<String> listPermissions, int reqCode, boolean isFirstTime) {
        if (listPermissions == null || listPermissions.size() <= 0)
            return true;
        ArrayList<String> listPermissionsNeeded = new ArrayList<String>();
        if (isFirstTime) {
            for (int i = 0; i < listPermissions.size(); i++) {
                if (ActivityCompat.checkSelfPermission(getActivity(), listPermissions.get(i)) != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(listPermissions.get(i));
                }
            }
        }

        if (!listPermissionsNeeded.isEmpty()) {
            requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), reqCode);
            return false;
        }
        return true;
    }

    private void setProfileImage(Uri uri) {
        if (uri != null) {
            Glide.with(getActivity()).load(uri)
                .placeholder(R.mipmap.ic_default_profile)
                .error(R.mipmap.ic_default_profile)
                .into(imgProfile);
        } else {
            imgProfile.setImageResource(R.mipmap.ic_default_profile);
        }
    }

    public boolean FieldValidation() {
        boolean flag = true;
        mFirstName = edtFirstName.getText().toString().trim();
        mLastName = edtLastName.getText().toString().trim();
        mPhoneNumber = edtPhoneNumber.getText().toString().trim();
        mBirthDate = txtBirthDate.getText().toString().trim();

        if(outputFileUri == null){
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_select_image));
        } else if (!Utils.getInstance().validateString(mFirstName)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_first_name));
        } else if (!Utils.getInstance().validateString(mLastName)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_last_name));
        }else if (mPhoneNumber.length() < 10) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_valid_phone_number));
        }else if (!Utils.getInstance().validateString(mBirthDate) || mBirthDate.equalsIgnoreCase(getResources().getString(R.string.birth_Date))) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_birth_date));
        }
        return flag;
    }

    private void handleBackPressEvent(boolean isHardwareBackButton) {
        if (homeActivity.isSlidingMenuOpen() || !isHardwareBackButton) // Open Sliding menu on click of menu icon            homeActivity.toggleSlidingMenu();
        else {
            homeActivity.popFragment();
        }
    }

    /**     * Handle Activity click events     */    @Override    public void onBackPressed() {
        handleBackPressEvent(true);
    }
}

10)RegistrationFragment.java
===========================
package com.credencys.myapplication.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.credencys.myapplication.R;
import com.credencys.myapplication.activity.ImageCropActivity;
import com.credencys.myapplication.utility.Constants;
import com.credencys.myapplication.utility.CustomDialog;
import com.credencys.myapplication.utility.FileUtils;
import com.credencys.myapplication.utility.PermissionUtil;
import com.credencys.myapplication.utility.PrefHelper;
import com.credencys.myapplication.utility.Utils;
import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;

/** * Created by manisha on 24/1/17. */
public class RegistrationFragment extends BaseFragment {
    private EditText edtFirstName, edtLastName, edtEmail, edtPassword, edtConfirmPassword, edtPhoneNumber;
    private TextView txtBirthDate, txtBirthDateLable;
    private String mFirstName, mLastName, mEmail, mPassword, mConfirmPwd, mBirthDate, mPhoneNumber;
    private int mGender;
    private RadioGroup radioGroupGender;
    private View view;
    Uri outputFileUri;
    private ImageView imgProfile, imgActionBarMenu;
    final int REQ_CODE_PERMISSION_CAMERA = 40;
    final int REQ_CODE_PERMISSION_GALLERY = 41;

    @Nullable    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_registration, container, false);
        initData();

        return view;
    }

    public void initData() {

        edtFirstName = (EditText) view.findViewById(R.id.frag_register_edt_first_name);
        edtLastName = (EditText) view.findViewById(R.id.frag_register_edt_last_name);
        edtEmail = (EditText) view.findViewById(R.id.frag_register_edt_email);
        edtPassword = (EditText) view.findViewById(R.id.frag_register_edt_password);
        edtConfirmPassword = (EditText) view.findViewById(R.id.frag_register_edt_confirm_password);
        txtBirthDate = (TextView) view.findViewById(R.id.frag_register_txt_birth_date);
        edtPhoneNumber = (EditText) view.findViewById(R.id.frag_register_edt_phone_number);
        radioGroupGender = (RadioGroup) view.findViewById(R.id.frag_register_radio_group_gender);
        TextView txtActionbarTitle = (TextView) view.findViewById(R.id.txt_actionbar_title);
        imgProfile = (ImageView) view.findViewById(R.id.frag_register_img_profile);
        txtBirthDateLable = (TextView) view.findViewById(R.id.frag_register_txt_lbl_birthdate);
        txtBirthDateLable.setVisibility(View.INVISIBLE);

        Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.frag_register_parent_view));
        txtActionbarTitle.setText(getResources().getString(R.string.sign_up));
        imgActionBarMenu = (ImageView) view.findViewById(R.id.img_actionbar_menu);
        imgActionBarMenu.setVisibility(View.INVISIBLE);
        homeActivity.setSlidingMenuEnable(false);
    }

    /**     * Handle Activity click events     */    public void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.frag_register_btn_signup:
                if (FieldValidation()) {
                    mBirthDate = txtBirthDate.getText().toString().trim();
                    int selectedId = radioGroupGender.getCheckedRadioButtonId();
                    RadioButton radioButton = (RadioButton) view.findViewById(selectedId);
                    if (radioButton.getText().toString().equalsIgnoreCase(getResources().getString(R.string.male))) {
                        mGender = 0;
                    } else if (radioButton.getText().toString().equalsIgnoreCase(getResources().getString(R.string.female))) {
                        mGender = 1;
                    }

                    if (homeActivity.dbHelper.isEmailExist(edtEmail.getText().toString().trim())) {
                        CustomDialog.getInstance().showMessageDialog(getActivity(),
                                getResources().getString(R.string.email_already_exists));
                    } else {
                        homeActivity.dbHelper.insertUser(mFirstName, mLastName, mEmail, mPassword, mBirthDate, mPhoneNumber, outputFileUri.toString(), mGender);
                        PrefHelper.setBoolean(getResources().getString(R.string.is_login),true);
                        homeActivity.removeAllFragment();
                        homeActivity.pushFragments(new DashBoardFragment(), true, false, true);
                    }
                }
                break;

            case R.id.frag_register_txt_birth_date:
                Utils.getInstance().hideKeyboard(view, getActivity());
                showDatePickerDialog();
                break;

            case R.id.frag_register_img_profile:
                dialogChoosePicture();
                break;
        }
    }

/*    Function for show datepicker dialog*/    public void showDatePickerDialog() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear + 1) + "/" + String.valueOf(year);
                txtBirthDate.setText(date);
                txtBirthDateLable.setVisibility(View.VISIBLE);

            }

        },
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());
        datePickerDialog.show();
    }

/*  custom dialog for choose picture*/    public void dialogChoosePicture() {
        final Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Dialog);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.custom_dialog_media_chooser);
        TextView btnGallery = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_library);
        btnGallery.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                dialog.dismiss();
                openGallery();

            }
        });

        TextView btnCamera = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_camera);
        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                dialog.dismiss();
                openCameraForCaptureImage();
            }
        });

        TextView btnCancel = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_cancel);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.REQ_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK) {

            Intent intent = new Intent(getActivity(), ImageCropActivity.class);
            intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100);
            intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri);

            startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE);

        } else if (requestCode == Constants.REQ_CODE_GALLERY_IMAGE && resultCode == Activity.RESULT_OK && null != data) {

            if (data != null && data.getData() != null) {
                Uri selectedImageUri = data.getData();
                String picturePath = Utils.getInstance().getRealPathFromURI(getActivity(), selectedImageUri);
                //Copy Original File to app media folder                String copiedFilepath = FileUtils.getInstance().copyFile(picturePath, FileUtils.getInstance().getFilePath(getActivity(), FileUtils.MEDIA_TYPE.PICTURE));
                Intent intent = new Intent(getActivity(), ImageCropActivity.class);
                intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100);
                intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100);

                outputFileUri = Uri.fromFile(new File(copiedFilepath));
                intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri);
                startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE);
            }
        } else if (requestCode == Constants.REQ_CODE_CROP_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                outputFileUri = bundle.getParcelable(ImageCropActivity.EXTRA_IMAGE_URI);
                setProfileImage(outputFileUri);
            }
        }
    }

    private void setProfileImage(Uri uri) {
        String strPath = "";
        if(uri != null) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                strPath = uri.toString();
                if (strPath.substring(0, 7).matches("file://")) {
                    strPath = strPath.substring(7);
                }
            } else {
                strPath = uri.getPath();
            }
        }

        if (Utils.getInstance().validateString(strPath)) {
            Glide.with(getActivity()).load(strPath)
                    .placeholder(R.mipmap.ic_default_profile)
                    .error(R.mipmap.ic_default_profile)
                    .into(imgProfile);
        } else {
            imgProfile.setImageResource(R.mipmap.ic_default_profile);
        }
    }

    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        ArrayList<String> listNotGrantedPermissions;
        switch (requestCode) {
            case REQ_CODE_PERMISSION_CAMERA:
                listNotGrantedPermissions = PermissionUtil.getInstance().verifyPermissions(permissions, grantResults);
                if (listNotGrantedPermissions != null && listNotGrantedPermissions.size() > 0) {
                    checkCameraPermissions(listNotGrantedPermissions, requestCode, false);
                } else {
                    openCameraForCaptureImage();
                }
                break;

            case REQ_CODE_PERMISSION_GALLERY:
                listNotGrantedPermissions = PermissionUtil.getInstance().verifyPermissions(permissions, grantResults);
                if (listNotGrantedPermissions != null && listNotGrantedPermissions.size() > 0) {
                    checkCameraPermissions(listNotGrantedPermissions, requestCode, false);
                } else {
                    openGallery();
                }
                break;
        }
    }

    /*function for check open gallery*/    private void openGallery() {
        ArrayList<String> listPermissionsNeed = PermissionUtil.getInstance().getGalleryPermission();
        if (checkCameraPermissions(listPermissionsNeed, REQ_CODE_PERMISSION_GALLERY, true)) {
            Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i, Constants.REQ_CODE_GALLERY_IMAGE);
        }
    }

    /*function for check open camera*/    private void openCameraForCaptureImage() {
        ArrayList<String> listPermissionsNeed = PermissionUtil.getInstance().getCameraPermissionsList();
        if (checkCameraPermissions(listPermissionsNeed, REQ_CODE_PERMISSION_CAMERA, true)) {
            try {
                Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    outputFileUri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", new File(FileUtils.getInstance().getFilePath(getActivity(),FileUtils.MEDIA_TYPE.PICTURE)));
                }else {
                    outputFileUri = FileUtils.getInstance().getFileUri(getActivity(), FileUtils.MEDIA_TYPE.PICTURE);
                }

                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                startActivityForResult(captureIntent, Constants.REQ_CODE_CAPTURE_IMAGE);
            } catch (ActivityNotFoundException e) {
                e.getMessage();
            }
        }
    }

    /*function for check camera permission*/    private boolean checkCameraPermissions(ArrayList<String> listPermissions, int reqCode, boolean isFirstTime) {
        if (listPermissions == null || listPermissions.size() <= 0)
            return true;
        ArrayList<String> listPermissionsNeeded = new ArrayList<String>();
        if (isFirstTime) {
            for (int i = 0; i < listPermissions.size(); i++) {
                if (ActivityCompat.checkSelfPermission(getActivity(), listPermissions.get(i)) != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNeeded.add(listPermissions.get(i));
                }
            }
        }

        if (!listPermissionsNeeded.isEmpty()) {
            requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), reqCode);
            return false;
        }
        return true;
    }

    /*Validate fields*/    public boolean FieldValidation() {
        boolean flag = true;
        mFirstName = edtFirstName.getText().toString().trim();
        mLastName = edtLastName.getText().toString().trim();
        mEmail = edtEmail.getText().toString().trim();
        mPassword = edtPassword.getText().toString().trim();
        mConfirmPwd = edtConfirmPassword.getText().toString().trim();
        mBirthDate = txtBirthDate.getText().toString().trim();
        mPhoneNumber = edtPhoneNumber.getText().toString().trim();

        if (outputFileUri == null) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_select_image));
        } else if (!Utils.getInstance().validateString(mFirstName)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_first_name));

        } else if (!Utils.getInstance().validateString(mLastName)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_last_name));
        } else if (!Utils.getInstance().validateString(mEmail)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_email));

        } else if (!Utils.getInstance().isEmailValid(mEmail)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_valid_email));

        } else if (!Utils.getInstance().validateString(mPassword)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_password));
        } else if (mPassword.length() < 8) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.password_is_too_short));
        } else if (!Utils.getInstance().validateString(mConfirmPwd)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_confirm_password));
        } else if (!TextUtils.equals(mPassword, mConfirmPwd)) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.password_does_not_match));
        } else if (mPhoneNumber.length() < 10) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(),
                    getResources().getString(R.string.please_enter_valid_phone_number));
        } else if (!Utils.getInstance().validateString(mBirthDate) || mBirthDate.equalsIgnoreCase(getResources().getString(R.string.birth_Date))) {
            flag = false;
            CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.please_enter_birth_date));
        }
        return flag;
    }

    /**     * Handle Activity click events     */    @Override    public void onBackPressed() {
        homeActivity.popFragment();
    }
}

* interfaces
===========
1)BackPressedEventListener.java
==============================
package com.credencys.myapplication.interfaces;


public interface BackPressedEventListener {
   public void onBackPressed();
}

2)ClickEventListener.java
=======================
package com.credencys.myapplication.interfaces;

import android.view.View;

public interface ClickEventListener {
    public void clickEvent(View v);
}

3)LocationUpdateListener.java
=============================
package com.credencys.myapplication.interfaces;

import android.location.Location;

public interface LocationUpdateListener {
    /**Called when got location of user*/    void onLocationUpdate(Location location);
    /**Called when user deny to request of enable Location permission*/    void onLocationPermissionDeny();
    /**Called when user deny to request to enable GPS*/    void onGPSRequestDeny();
}

4)RecyclerViewItemClickListener.java
===================================
package com.credencys.myapplication.interfaces;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerViewItemClickListener implements RecyclerView.OnItemTouchListener {
        private OnItemClickListener mListener;

        public interface OnItemClickListener {
            public void onItemClick(View view, int position);
        }

        GestureDetector mGestureDetector;

        public RecyclerViewItemClickListener(Context context, OnItemClickListener listener) {
            mListener = listener;
            mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }
            });
        }

        @Override        public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
            View childView = view.findChildViewUnder(e.getX(), e.getY());
            if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
                mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
            }
            return false;
        }

        @Override        public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {

        }

    @Override    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }
}

* Models
========
1) ExpandViewModel.java
=======================
package com.credencys.myapplication.models;

public class ExpandViewModel {
    private int position;
    private String title;
    private String description;
    private int imgId;
    public boolean isChecked;

    public ExpandViewModel(int position, String title, String description, int imgId, boolean isChecked) {
        this.title = title;
        this.description = description;
        this.imgId = imgId;
        this.isChecked = isChecked;
        this.position = position;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getImgId() {
        return imgId;
    }

    public void setImgId(int imgId) {
        this.imgId = imgId;
    }

    public boolean isChecked() {
        return isChecked;
    }

    public void setChecked(boolean checked) {
        isChecked = checked;
    }

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }
}

2)LatestUpdateCategoryModel.java
==============================
package com.credencys.myapplication.models;

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class LatestUpdateCategoryModel {
    @SerializedName("status")
    private String status;
    @SerializedName("feed")
    private Feed feed;
    @SerializedName("items")
    private List<Items> items;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Feed getFeed() {
        return feed;
    }

    public void setFeed(Feed feed) {
        this.feed = feed;
    }

    public List<Items> getItems() {
        return items;
    }

    public void setItems(List<Items> items) {
        this.items = items;
    }

    public static class Feed {
        @SerializedName("url")
        private String url;
        @SerializedName("title")
        private String title;
        @SerializedName("link")
        private String link;
        @SerializedName("author")
        private String author;
        @SerializedName("description")
        private String description;
        @SerializedName("image")
        private String image;

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getLink() {
            return link;
        }

        public void setLink(String link) {
            this.link = link;
        }

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String author) {
            this.author = author;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }
    }

    public static class Enclosure {
    }

    public static class Categories {
    }

    public static class Items {
        @SerializedName("title")
        private String title;
        @SerializedName("pubDate")
        private String pubDate;
        @SerializedName("link")
        private String link;
        @SerializedName("guid")
        private String guid;
        @SerializedName("author")
        private String author;
        @SerializedName("thumbnail")
        private String thumbnail;
        @SerializedName("description")
        private String description;
        @SerializedName("content")
        private String content;
        @SerializedName("enclosure")
        private List<Enclosure> enclosure;
        @SerializedName("categories")
        private List<Categories> categories;

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getPubDate() {
            return pubDate;
        }

        public void setPubDate(String pubDate) {
            this.pubDate = pubDate;
        }

        public String getLink() {
            return link;
        }

        public void setLink(String link) {
            this.link = link;
        }

        public String getGuid() {
            return guid;
        }

        public void setGuid(String guid) {
            this.guid = guid;
        }

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String author) {
            this.author = author;
        }

        public String getThumbnail() {
            return thumbnail;
        }

        public void setThumbnail(String thumbnail) {
            this.thumbnail = thumbnail;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public List<Enclosure> getEnclosure() {
            return enclosure;
        }

        public void setEnclosure(List<Enclosure> enclosure) {
            this.enclosure = enclosure;
        }

        public List<Categories> getCategories() {
            return categories;
        }

        public void setCategories(List<Categories> categories) {
            this.categories = categories;
        }
    }
}

3)LoginModel.java
================
package com.credencys.myapplication.models;

public class LoginModel {
    private int userId;
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private String phoneNumber;
    private String dob;
    private int gender;
    private String userImage;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public int getGender() {
        return gender;
    }

    public void setGender(int gender) {
        this.gender = gender;
    }

    public String getUserImage() {
        return userImage;
    }

    public void setUserImage(String userImage) {
        this.userImage = userImage;
    }
}

4) NearByLocationModel.java
===========================
package com.credencys.myapplication.models;

import com.google.gson.annotations.SerializedName;

import java.util.List;

public class NearByLocationModel {
    @SerializedName("html_attributions")
    private List<Html_attributions> html_attributions;
    @SerializedName("next_page_token")
    private String next_page_token;
    @SerializedName("results")
    private List<Results> results;
    @SerializedName("status")
    private String status;

    public List<Html_attributions> getHtml_attributions() {
        return html_attributions;
    }

    public void setHtml_attributions(List<Html_attributions> html_attributions) {
        this.html_attributions = html_attributions;
    }

    public String getNext_page_token() {
        return next_page_token;
    }

    public void setNext_page_token(String next_page_token) {
        this.next_page_token = next_page_token;
    }

    public List<Results> getResults() {
        return results;
    }

    public void setResults(List<Results> results) {
        this.results = results;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public static class Html_attributions {
    }

    public static class Location {
        @SerializedName("lat")
        private double lat;
        @SerializedName("lng")
        private double lng;

        public double getLat() {
            return lat;
        }

        public void setLat(double lat) {
            this.lat = lat;
        }

        public double getLng() {
            return lng;
        }

        public void setLng(double lng) {
            this.lng = lng;
        }
    }

    public static class Northeast {
        @SerializedName("lat")
        private double lat;
        @SerializedName("lng")
        private double lng;

        public double getLat() {
            return lat;
        }

        public void setLat(double lat) {
            this.lat = lat;
        }

        public double getLng() {
            return lng;
        }

        public void setLng(double lng) {
            this.lng = lng;
        }
    }

    public static class Southwest {
        @SerializedName("lat")
        private double lat;
        @SerializedName("lng")
        private double lng;

        public double getLat() {
            return lat;
        }

        public void setLat(double lat) {
            this.lat = lat;
        }

        public double getLng() {
            return lng;
        }

        public void setLng(double lng) {
            this.lng = lng;
        }
    }

    public static class Viewport {
        @SerializedName("northeast")
        private Northeast northeast;
        @SerializedName("southwest")
        private Southwest southwest;

        public Northeast getNortheast() {
            return northeast;
        }

        public void setNortheast(Northeast northeast) {
            this.northeast = northeast;
        }

        public Southwest getSouthwest() {
            return southwest;
        }

        public void setSouthwest(Southwest southwest) {
            this.southwest = southwest;
        }
    }

    public static class Geometry {
        @SerializedName("location")
        private Location location;
        @SerializedName("viewport")
        private Viewport viewport;

        public Location getLocation() {
            return location;
        }

        public void setLocation(Location location) {
            this.location = location;
        }

        public Viewport getViewport() {
            return viewport;
        }

        public void setViewport(Viewport viewport) {
            this.viewport = viewport;
        }
    }

    public static class Results {
        @SerializedName("geometry")
        private Geometry geometry;
        @SerializedName("icon")
        private String icon;
        @SerializedName("id")
        private String id;
        @SerializedName("name")
        private String name;
        @SerializedName("place_id")
        private String place_id;
        @SerializedName("reference")
        private String reference;
        @SerializedName("scope")
        private String scope;
//        @SerializedName("types")//        private List<Types> types;
        public Geometry getGeometry() {
            return geometry;
        }

        public void setGeometry(Geometry geometry) {
            this.geometry = geometry;
        }

        public String getIcon() {
            return icon;
        }

        public void setIcon(String icon) {
            this.icon = icon;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPlace_id() {
            return place_id;
        }

        public void setPlace_id(String place_id) {
            this.place_id = place_id;
        }

        public String getReference() {
            return reference;
        }

        public void setReference(String reference) {
            this.reference = reference;
        }

        public String getScope() {
            return scope;
        }

        public void setScope(String scope) {
            this.scope = scope;
        }

//        public List<Types> getTypes() {//            return types;//        }////        public void setTypes(List<Types> types) {//            this.types = types;//        }    }
}

5)SlidingMenuModel.java
========================
package com.credencys.myapplication.models;

/** * Created by Manisha */public class SlidingMenuModel {
    private int mId;
    private String mName;
    private int mIcon;

    public void setId(int id) {this.mId = id;}

    public int getId() {return mId;}

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        this.mName = name;
    }

    public int getIcon() {
        return mIcon;
    }

    public void setIcon(int icon) {
        this.mIcon = icon;
    }

}

* utility

1) Constants.java
==============
public class Constants {

    public static final int REQ_CODE_CAPTURE_IMAGE=50,REQ_CODE_GALLERY_IMAGE=51,REQ_CODE_CROP_IMAGE=53;

}

2)CustomDialog.java
==================
package com.credencys.myapplication.utility;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;

import com.credencys.myapplication.R;

public class CustomDialog {
    private static CustomDialog customDialog;
    ProgressDialog progressDialog;

    public static CustomDialog getInstance() {
        if (customDialog == null) {
            customDialog = new CustomDialog();
        }
        return customDialog;
    }

    /**     * Show progress dialog without message, Before show new dialog it is hide previous showing dialog     * @param context Context of activity.     * @param cancelable true: Hide out side touch or back press, false: Can not hide out side touch     * */    public void show(@NonNull Context context, boolean cancelable) {
        try {
            //Before show new dialog hide previous showing dialog            hide();
            progressDialog = new ProgressDialog(context);
            progressDialog.setCancelable(cancelable);
            progressDialog.setMessage(context.getString(R.string.msgLoading));
            progressDialog.show();

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

    /**     * Show progress dialog without message, Before show new dialog it is hide previous showing dialog     * @param context Context of activity.     * @param message Message of dialog.     * @param cancelable true: Hide out side touch or back press, false: Can not hide out side touch     * */    public void show(@NonNull Context context,@NonNull String message,boolean cancelable) {

        try {

            //Before show new dialog hide previous showing dialog            hide();
            //Set default dialog message "Loading"            message=(message!=null && message.trim().length()>0)?message:context.getString(R.string.msgLoading);
            progressDialog = new ProgressDialog(context);
            progressDialog.setMessage(message);
            progressDialog.setCancelable(cancelable);

            progressDialog.show();

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

    }

    public void hide() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    public boolean isDialogShowing() {
        if (progressDialog != null)
            return progressDialog.isShowing();
        else            return false;
    }

    //Show alert dialog    public void showMessageDialog(Context context, String title, String message) {

        if (message != null && message.trim().length() > 0) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            //builder.setTitle(title);            builder.setCancelable(true);
            builder.setMessage(message);
            builder.setPositiveButton(context.getString(R.string.btnOk),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });
            // create alert dialog            AlertDialog alertDialog = builder.create();
            // show it            alertDialog.show();
        }
    }

    //Show alert dialog    public void showMessageDialog(Context context,String message) {
        if (message != null && message.trim().length() > 0) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);

            //builder.setTitle(title);            builder.setCancelable(true);
            builder.setMessage(message);
            builder.setPositiveButton(context.getString(R.string.btnOk),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });

            // create alert dialog            AlertDialog alertDialog = builder.create();
            // show it            alertDialog.show();
        }
    }
}

3)FileUtils.java
===============
package com.credencys.myapplication.utility;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.credencys.myapplication.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class FileUtils {

    private String TAG=FileUtils.class.getName();
    private static FileUtils fileUtils;
    public enum MEDIA_TYPE{PICTURE,VIDEO}
    public static FileUtils getInstance()
    {
        if(fileUtils==null)
            fileUtils=new FileUtils();
        return fileUtils;
    }

    /**Return File URI according media type*/    public Uri getFileUri(Context context,MEDIA_TYPE mediaType)
    {
        try {

            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), context.getString(R.string.app_name));
            //Create Media Directory            File  mediaDir=new File(mediaStorageDir + File.separator + context.getString(R.string.dirMedia));
            if(!mediaDir.exists())
                mediaDir.mkdirs();

            String subDirName="",fileExtension="";
            switch (mediaType)
            {
                case PICTURE:
                    subDirName=context.getString(R.string.dirImages);
                    fileExtension=".jpg";
                    break;
                case VIDEO:
                    subDirName=context.getString(R.string.dirVideos);
                    fileExtension=".mp4";
                    break;
            }
            File subDir = new File(mediaDir + File.separator + subDirName);
            if(!subDir.exists())
                subDir.mkdirs();

            String mediaFileName = System.currentTimeMillis() + fileExtension;

            File mediaFile = new File(subDir, mediaFileName);

            return Uri.fromFile(mediaFile);

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

    /**Return File path according media type*/    public String getFilePath(Context context,MEDIA_TYPE mediaType)
    {
        try {

            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), context.getString(R.string.app_name));
            //Create Media Directory            File  mediaDir=new File(mediaStorageDir + File.separator + context.getString(R.string.dirMedia));
            if(!mediaDir.exists())
                mediaDir.mkdirs();

            String subDirName="",fileExtension="";
            switch (mediaType)
            {
                case PICTURE:
                    subDirName=context.getString(R.string.dirImages);
                    fileExtension=".jpg";
                    break;
                case VIDEO:
                    subDirName=context.getString(R.string.dirVideos);
                    fileExtension=".mp4";
                    break;
            }
            File subDir = new File(mediaDir + File.separator + subDirName);
            if(!subDir.exists())
                subDir.mkdirs();

            String mediaFileName = System.currentTimeMillis() + fileExtension;

            File mediaFile = new File(subDir, mediaFileName);

            return mediaFile.getAbsolutePath();

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

    /**Copy file from source to target location with target file name and extension     * @param sourcePath Source file path     * @param targetPath Target File path with file name e.g path/filName.jpg     * */    public String copyFile(String sourcePath,String targetPath) {
        InputStream in = null;
        OutputStream out = null;
        try {

            //create output directory if it doesn't exist            /*File dir = new File (targetPath);            if (!dir.exists())            {                dir.mkdirs();            }*/            //File sourceFile=new File(inputPath);            File outputFile=new File(targetPath);
//            File outputFile=new File(outputPath + File.separator + sourceFile.getName());
            in = new FileInputStream(sourcePath);
            out = new FileOutputStream(outputFile.getAbsoluteFile());

            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            in.close();
            //in = null;
            // write the output file (You have now copied the file)            out.flush();
            out.close();
            //out = null;
            return outputFile.getAbsolutePath();

        }  catch (FileNotFoundException fnfe1) {
            Log.e(TAG, fnfe1.getMessage());
        }
        catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return "";
    }
}

4)PermissionUtil.java
===================
/** Copyright 2015 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
package com.credencys.myapplication.utility;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;

import java.util.ArrayList;

/** * Utility class that wraps access to the runtime permissions API in M and provides basic helper * methods. */public class PermissionUtil {
    static PermissionUtil permissionUtil;

    public static PermissionUtil getInstance()
    {
        if(permissionUtil==null)
            permissionUtil=new PermissionUtil();
        return permissionUtil;
    }

    /**     * Check that all given permissions have been granted by verifying that each entry in the     * given array is of the value {@link PackageManager#PERMISSION_GRANTED}.     *     * @see Activity#onRequestPermissionsResult(int, String[], int[])     */    public static boolean verifyPermissions(int[] grantResults) {
        // At least one result must be checked.        if(grantResults.length < 1){
            return false;
        }

        // Verify that each required permission has been granted, otherwise return false.        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }



    public  ArrayList<String> verifyPermissions(String permissions[],int[] grantResults) {
        // At least one result must be checked.
        if(permissions!=null && grantResults!=null && permissions.length>0 && grantResults.length>0)
        {
            ArrayList<String> listPermissionsNotGranted=new ArrayList<String>();
            // Verify that each required permission has been granted, otherwise return false.            for (int i=0;i<grantResults.length;i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    listPermissionsNotGranted.add(permissions[i]);
                }
            }
            return listPermissionsNotGranted;
        }

        return null;

    }

    public ArrayList<String> getCameraPermissionsList()
    {
        ArrayList<String> listPermissionsNeed=new ArrayList<String>();
        listPermissionsNeed.add(Manifest.permission.CAMERA);
        listPermissionsNeed.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);

        return listPermissionsNeed;
    }

    public ArrayList<String> getGalleryPermission()
    {
        ArrayList<String> listPermissionsNeed=new ArrayList<String>();
        listPermissionsNeed.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);

        return listPermissionsNeed;
    }

}

5)PrefHelper.java
===============
package com.credencys.myapplication.utility;

import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.credencys.myapplication.MyApplication;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Map;

/** * This class is help to store/get data into preference * */public class PrefHelper {
   public static void setString(String key, String value) {
      final Editor editor = MyApplication.myPref.edit();
      editor.putString(key, value);
      apply(editor);
   }

   public static String getString(String key,String defaultValue) {
      return MyApplication.myPref.getString(key, defaultValue);
   }

   public static void setInt(String key,int value) {
      final Editor editor = MyApplication.myPref.edit();
      editor.putInt(key, value);
      apply(editor);
   }

   public static int getInt(String key,int defaultValue) {
      return MyApplication.myPref.getInt(key, defaultValue);
   }

   public static boolean getBoolean(String key,boolean defaultValue) {
      return MyApplication.myPref.getBoolean(key, defaultValue);
   }

   public static void setBoolean(String key,boolean value) {
      final Editor editor = MyApplication.myPref.edit();
      editor.putBoolean(key, value);
      apply(editor);
   }

   public static long getLong(String key,long defaultValue) {
      return MyApplication.myPref.getLong(key, defaultValue);
   }

   public static void setLong(String key,long value) {
      final Editor editor = MyApplication.myPref.edit();
      editor.putLong(key, value);
      apply(editor);
   }

   public static double getDouble(String key,double defaultValue) {
      return Double.longBitsToDouble(MyApplication.myPref.getLong(key, Double.doubleToLongBits(defaultValue)));
   }

   public static void setDouble(String key,double value) {
      final Editor editor = MyApplication.myPref.edit();
      editor.putLong(key, Double.doubleToRawLongBits(value));
      apply(editor);
   }

   public static void deletePreference(String key) {
      final Editor editor = MyApplication.myPref.edit();
      editor.remove(key);
      apply(editor);
   }

   public static void deletePreferences(String[] keys) {
      if(keys!=null && keys.length>0)
      {
//       Editor editor = null;         for(int i=0;i<keys.length;i++)
         {
            final Editor editor= MyApplication.myPref.edit();
            editor.remove(keys[i]);
            apply(editor);
         }
      }
   }

   public static void deleteAllPreferences() {
      final Editor editor = MyApplication.myPref.edit();
      editor.clear();
      apply(editor);
   }

   /*Delete all preference of app except passed argument*/   public static void deletePreferencesExcept(ArrayList<String> keysNotDelete) {
      //SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(MyApplication.appInstance);      Map<String,?> keys = MyApplication.myPref.getAll();

      for(Map.Entry<String,?> entry : keys.entrySet()){
         Log.d("map values", entry.getKey() + ": " +
               entry.getValue().toString());
         if(!keysNotDelete.contains(entry.getKey()))
         {
            final Editor editor= MyApplication.myPref.edit();
            editor.remove(entry.getKey());
            apply(editor);
         }
      }
   }

   // Faster pref saving for high performance   private static final Method sApplyMethod = findApplyMethod();

   private static Method findApplyMethod() {
      try {
         final Class<Editor> cls = Editor.class;
         return cls.getMethod("apply");
      } catch (final NoSuchMethodException unused) {
         // fall through      }
      return null;
   }

   public static void apply(final Editor editor) {
      if (sApplyMethod != null) {
         try {
            sApplyMethod.invoke(editor);
            return;
         } catch (final InvocationTargetException unused) {
            // fall through         } catch (final IllegalAccessException unused) {
            // fall through         }
      }
      editor.commit();
   }
}

6)Utils.java
==============
package com.credencys.myapplication.utility;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import org.apache.commons.lang3.StringEscapeUtils;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** * Created by manisha on 26/2/17. */public class Utils {
    private static Utils utils;
    public static Utils getInstance() {
        if (utils == null)
            utils = new Utils();
        return utils;
    }

    public boolean isEmailValid(String email) {
        String expression = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        CharSequence inputStr = email;
        boolean flag = false;
        Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            flag = true;
        }
        return flag;
    }

    public boolean checkInternetConnection(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // test for connection        if (cm.getActiveNetworkInfo() != null                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            Log.v("", "Internet Connection Not Available");
            //Toast.makeText(context, context.getResources().getString(R.string.network_connectivity_not_available), Toast.LENGTH_SHORT).show();            return false;
        }
    }

    public String generateHashKey(Context context) {
        String hashKey = "";
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                hashKey = Base64.encodeToString(md.digest(), Base64.DEFAULT);
                MyLog.v("TAG", "Hash Key:" + hashKey);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hashKey;
    }

    @SuppressLint("NewApi")
    public boolean validateString(String object) {
        boolean flag = false;
        if (object != null && !object.equalsIgnoreCase("null") && !object.equalsIgnoreCase("(null)") &&
                !object.isEmpty() && !object.equalsIgnoreCase("(null)")) {
            flag = true;
        }
        return flag;
    }

    /**     * Delete all files and directory itself     */    private void deleteRecursive(File fileOrDirectory) {
        if (fileOrDirectory.isDirectory())
            for (File child : fileOrDirectory.listFiles())
                deleteRecursive(child);

        fileOrDirectory.delete();
    }

    public void hideKeyboard(View v, Context context) {
        InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    public void showKeyboard(View v, Context context) {       /*     * InputMethodManager mgr =        * (InputMethodManager)context.getSystemService(       * Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(v, 0);     */        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
    }

    /**     * Function is used to hide keyboard while user click outside of keyboard on screen.     * @param view  contains parent view id to get all child views.     */    @SuppressLint("ClickableViewAccessibility")
    public void setupOutSideTouchHideKeyboard(final View view)
    {
        if(view==null)
            return;
        // Set up touch listener for non-text box views to hide keyboard.        if (!(view instanceof EditText))
        {
            view.setOnTouchListener(new View.OnTouchListener()
            {

                @Override                public boolean onTouch(View v, MotionEvent event)
                {
                    hideKeyboard(view,view.getContext());
                    return false;
                }

            });
        }

        // If a layout container, iterate over children and seed recursion.        if (view instanceof ViewGroup)
        {

            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++)
            {

                View innerView = ((ViewGroup) view).getChildAt(i);

                setupOutSideTouchHideKeyboard(innerView);
            }
        }
    }

    public int[] getScreenWidthHeight(Context context)
    {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displaymetrics);
        int screenWidth = displaymetrics.widthPixels;
        int screenHeight = displaymetrics.heightPixels;
        int[] wh = { screenWidth, screenHeight };
//    int[] wh = { width, height };        return wh;
    }

    public float getFileSizeInMb(File file)
    {
        try{
            if(!file.exists())
                return 0;
            // Get length of file in bytes            long fileSizeInBytes = file.length();
            // Convert the bytes to Kilobytes (1 KB = 1024 Bytes)            float fileSizeInKB = fileSizeInBytes / 1024;
            // Convert the KB to MegaBytes (1 MB = 1024 KBytes)            float fileSizeInMB = fileSizeInKB / 1024;
            return fileSizeInMB;
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return 0;
    }

    /**Return image path of given URI*/    public String getRealPathFromURI(Context context,Uri contentURI) {
//        Cursor cursor = getActivity().getContentResolver().query(contentURI, null, null, null, null);        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentURI, projection, null, null, null);
        //Some of gallery application is return null        if (cursor == null) {
            return contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(projection[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            return picturePath;
        }
    }

    /**It will encode the unicode characters properly before sending to web server.*/    public String escapeJava(String text)
    {
        if(text!=null && text.length()>0)
            return StringEscapeUtils.escapeJava(text);
        return "";
    }

    /**it will decode the unicode characters properly after receiving the response from web server.*/    public String unescapeJava(String text)
    {
        if(text!=null && text.length()>0)
            return StringEscapeUtils.unescapeJava(text);
        return "";
    }

    /**Return formatted date of passed output format*/    public String getFormattedDate(String date, String input, String output) {
        try {
            SimpleDateFormat sdfInput = new SimpleDateFormat(input);
            SimpleDateFormat sdfOutput = new SimpleDateFormat(output);

            return sdfOutput.format(sdfInput.parse(date));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    public Date covertStringToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Date date = null;

        try {
            date = formatter.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}

* widgets

1) BitmapCroppingWorkerTask.java
================================
// "Therefore those skilled at the unorthodox// are infinite as heaven and earth,// inexhaustible as the great rivers.// When they come to an end,// they begin again,// like the days and months;// they die and are reborn,// like the four seasons."//// - Sun Tsu,// "The Art of War"
package com.credencys.myapplication.widgets;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;

import com.credencys.myapplication.cropwindow.ImageViewUtil;

import java.lang.ref.WeakReference;

/** * Task to crop bitmap asynchronously from the UI thread. */class BitmapCroppingWorkerTask extends AsyncTask<Void, Void, BitmapCroppingWorkerTask.Result> {

    //region: Fields and Consts
    /**     * Use a WeakReference to ensure the ImageView can be garbage collected     */    private final WeakReference<CropImageView> mCropImageViewReference;

    /**     * the bitmap to crop     */    private final Bitmap mBitmap;

    /**     * The Android URI of the image to load     */    private final Uri mUri;

    /**     * The context of the crop image view widget used for loading of bitmap by Android URI     */    private final Context mContext;

    /**     * Required cropping rectangle     */    private final Rect mRect;

    /**     * The shape to crop the image     */    private final CropImageView.CropShape mCropShape;

    /**     * Degrees the image was rotated after loading     */    private final int mDegreesRotated;

    /**     * required width of the cropping image     */    private final int mReqWidth;

    /**     * required height of the cropping image     */    private final int mReqHeight;
    //endregion
    public BitmapCroppingWorkerTask(CropImageView cropImageView, Bitmap bitmap, Rect rect, CropImageView.CropShape cropShape) {
        mCropImageViewReference = new WeakReference<>(cropImageView);
        mContext = cropImageView.getContext();
        mBitmap = bitmap;
        mRect = rect;
        mCropShape = cropShape;
        mUri = null;
        mDegreesRotated = 0;
        mReqWidth = 0;
        mReqHeight = 0;
    }

    public BitmapCroppingWorkerTask(CropImageView cropImageView, Uri uri, Rect rect, CropImageView.CropShape cropShape, int degreesRotated, int reqWidth, int reqHeight) {
        mCropImageViewReference = new WeakReference<>(cropImageView);
        mContext = cropImageView.getContext();
        mUri = uri;
        mRect = rect;
        mCropShape = cropShape;
        mDegreesRotated = degreesRotated;
        mReqWidth = reqWidth;
        mReqHeight = reqHeight;
        mBitmap = null;
    }

    /**     * The Android URI that this task is currently loading.     */    public Uri getUri() {
        return mUri;
    }

    /**     * Crop image in background.     *     * @param params ignored     * @return the decoded bitmap data     */    @Override    protected Result doInBackground(Void... params) {
        try {
            if (!isCancelled()) {
                Bitmap bitmap = null;
                if (mUri != null) {
                    bitmap = ImageViewUtil.cropBitmap(
                            mContext,
                            mUri,
                            mRect,
                            mDegreesRotated,
                            mReqWidth,
                            mReqHeight);
                } else if (mBitmap != null) {
                    bitmap = ImageViewUtil.cropBitmap(mBitmap, mRect);
                }
                if (bitmap != null && mCropShape == CropImageView.CropShape.OVAL) {
                    bitmap = ImageViewUtil.toOvalBitmap(bitmap);
                }
                return new Result(bitmap);
            }
            return null;
        } catch (Exception e) {
            return new Result(e);
        }
    }

    /**     * Once complete, see if ImageView is still around and set bitmap.     *     * @param result the result of bitmap cropping     */    @Override    protected void onPostExecute(Result result) {
        if (result != null) {
            boolean completeCalled = false;
            if (!isCancelled()) {
                CropImageView cropImageView = mCropImageViewReference.get();
                if (cropImageView != null) {
                    completeCalled = true;
                    cropImageView.onGetImageCroppingAsyncComplete(result);
                }
            }
            if (!completeCalled && result.bitmap != null) {
                // fast release of unused bitmap                result.bitmap.recycle();
            }
        }
    }

    //region: Inner class: Result
    /**     * The result of BitmapCroppingWorkerTask async loading.     */    public static final class Result {

        /**         * The cropped bitmap         */        public final Bitmap bitmap;

        /**         * The error that occurred during async bitmap cropping.         */        public final Exception error;

        Result(Bitmap bitmap) {
            this.bitmap = bitmap;
            this.error = null;
        }

        Result(Exception error) {
            this.bitmap = null;
            this.error = error;
        }
    }
    //endregion}
2)BitmapLoadingWorkerTask.java
====================================
// "Therefore those skilled at the unorthodox// are infinite as heaven and earth,// inexhaustible as the great rivers.// When they come to an end,// they begin again,// like the days and months;// they die and are reborn,// like the four seasons."//// - Sun Tsu,// "The Art of War"
package com.credencys.myapplication.widgets;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.DisplayMetrics;

import com.credencys.myapplication.cropwindow.ImageViewUtil;

import java.lang.ref.WeakReference;

/** * Task to load bitmap asynchronously from the UI thread. */class BitmapLoadingWorkerTask extends AsyncTask<Void, Void, BitmapLoadingWorkerTask.Result> {

    //region: Fields and Consts
    /**     * Use a WeakReference to ensure the ImageView can be garbage collected     */    private final WeakReference<CropImageView> mCropImageViewReference;

    /**     * The Android URI of the image to load     */    private final Uri mUri;

    /**     * Optional: if given use this rotation and not by exif     */    private final Integer mPreSetRotation;

    /**     * The context of the crop image view widget used for loading of bitmap by Android URI     */    private final Context mContext;

    /**     * required width of the cropping image after density adjustment     */    private final int mWidth;

    /**     * required height of the cropping image after density adjustment     */    private final int mHeight;
    //endregion
    public BitmapLoadingWorkerTask(CropImageView cropImageView, Uri uri, Integer preSetRotation) {
        mUri = uri;
        mPreSetRotation = preSetRotation;
        mCropImageViewReference = new WeakReference<>(cropImageView);

        mContext = cropImageView.getContext();

        DisplayMetrics metrics = cropImageView.getResources().getDisplayMetrics();
        double densityAdj = metrics.density > 1 ? 1 / metrics.density : 1;
        mWidth = (int) (metrics.widthPixels * densityAdj);
        mHeight = (int) (metrics.heightPixels * densityAdj);
    }

    /**     * The Android URI that this task is currently loading.     */    public Uri getUri() {
        return mUri;
    }

    /**     * Decode image in background.     *     * @param params ignored     * @return the decoded bitmap data     */    @Override    protected Result doInBackground(Void... params) {
        try {
            if (!isCancelled()) {
                ImageViewUtil.DecodeBitmapResult decodeResult =
                        ImageViewUtil.decodeSampledBitmap(mContext, mUri, mWidth, mHeight);

                if (!isCancelled()) {
                    ImageViewUtil.RotateBitmapResult rotateResult = mPreSetRotation != null                            ? ImageViewUtil.rotateBitmapResult(decodeResult.bitmap, mPreSetRotation)
                            : ImageViewUtil.rotateBitmapByExif(mContext, decodeResult.bitmap, mUri);

                    return new Result(mUri, rotateResult.bitmap, decodeResult.sampleSize, rotateResult.degrees);
                }
            }
            return null;
        } catch (Exception e) {
            return new Result(mUri, e);
        }
    }

    /**     * Once complete, see if ImageView is still around and set bitmap.     *     * @param result the result of bitmap loading     */    @Override    protected void onPostExecute(Result result) {
        if (result != null) {
            boolean completeCalled = false;
            if (!isCancelled()) {
                CropImageView cropImageView = mCropImageViewReference.get();
                if (cropImageView != null) {
                    completeCalled = true;
                    cropImageView.onSetImageUriAsyncComplete(result);
                }
            }
            if (!completeCalled && result.bitmap != null) {
                // fast release of unused bitmap                result.bitmap.recycle();
            }
        }
    }

    //region: Inner class: Result
    /**     * The result of BitmapLoadingWorkerTask async loading.     */    public static final class Result {

        /**         * The Android URI of the image to load         */        public final Uri uri;

        /**         * The loaded bitmap         */        public final Bitmap bitmap;

        /**         * The sample size used to load the given bitmap         */        public final int loadSampleSize;

        /**         * The degrees the image was rotated         */        public final int degreesRotated;

        /**         * The error that occurred during async bitmap loading.         */        public final Exception error;

        Result(Uri uri, Bitmap bitmap, int loadSampleSize, int degreesRotated) {
            this.uri = uri;
            this.bitmap = bitmap;
            this.loadSampleSize = loadSampleSize;
            this.degreesRotated = degreesRotated;
            this.error = null;
        }

        Result(Uri uri, Exception error) {
            this.uri = uri;
            this.bitmap = null;
            this.loadSampleSize = 0;
            this.degreesRotated = 0;
            this.error = error;
        }
    }
    //endregion}

3)CropImageView.java
=========================
/* * Copyright 2013, Edmodo, Inc.  * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. * You may obtain a copy of the License in the LICENSE file, or at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"  * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language  * governing permissions and limitations under the License.  */
package com.credencys.myapplication.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.credencys.myapplication.R;
import com.credencys.myapplication.cropwindow.ImageViewUtil;
import com.credencys.myapplication.cropwindow.edge.Edge;

import java.lang.ref.WeakReference;

/** * Custom view that provides cropping capabilities to an image. */public class CropImageView extends FrameLayout {
    //region: Fields and Consts    /**     * Image view widget used to show the image for cropping.     */    private final ImageView mImageView;

    /**     * Overlay over the image view to show cropping UI.     */    private final CropOverlayView mCropOverlayView;

    /**     * Progress bar widget to show progress bar on async image loading and cropping.     */    private final ProgressBar mProgressBar;

    private Bitmap mBitmap;

    private int mDegreesRotated = 0;

    private int mLayoutWidth;

    private int mLayoutHeight;

    private int mImageResource = 0;

    /**     * if to show progress bar when image async loading/cropping is in progress.<br>
     * default: true, disable to provide custom progress bar UI.     */    private boolean mShowProgressBar = true;

    /**     * callback to be invoked when image async loading is complete     */    private WeakReference<OnSetImageUriCompleteListener> mOnSetImageUriCompleteListener;

    /**     * callback to be invoked when image async cropping is complete     */    private WeakReference<OnGetCroppedImageCompleteListener> mOnGetCroppedImageCompleteListener;

    /**     * The URI that the image was loaded from (if loaded from URI)     */    private Uri mLoadedImageUri;

    /**     * The sample size the image was loaded by if was loaded by URI     */    private int mLoadedSampleSize = 1;

    /**     * Task used to load bitmap async from UI thread     */    private WeakReference<BitmapLoadingWorkerTask> mBitmapLoadingWorkerTask;

    /**     * Task used to crop bitmap async from UI thread     */    private WeakReference<BitmapCroppingWorkerTask> mBitmapCroppingWorkerTask;
    //endregion
    public CropImageView(Context context) {
        this(context, null);
    }

    public CropImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        int guidelines = Defaults.DEFAULT_GUIDELINES;
        boolean fixAspectRatio = Defaults.DEFAULT_FIXED_ASPECT_RATIO;
        int aspectRatioX = Defaults.DEFAULT_ASPECT_RATIO_X;
        int aspectRatioY = Defaults.DEFAULT_ASPECT_RATIO_Y;
        ImageView.ScaleType scaleType = Defaults.VALID_SCALE_TYPES[Defaults.DEFAULT_SCALE_TYPE_INDEX];
        CropShape cropShape = CropShape.RECTANGLE;
        float snapRadius = Defaults.SNAP_RADIUS_DP;

        if (attrs != null) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CropImageView, 0, 0);
            try {
                guidelines = ta.getInteger(R.styleable.CropImageView_guidelines, guidelines);
                fixAspectRatio = ta.getBoolean(R.styleable.CropImageView_fixAspectRatio, Defaults.DEFAULT_FIXED_ASPECT_RATIO);
                aspectRatioX = ta.getInteger(R.styleable.CropImageView_aspectRatioX, Defaults.DEFAULT_ASPECT_RATIO_X);
                aspectRatioY = ta.getInteger(R.styleable.CropImageView_aspectRatioY, Defaults.DEFAULT_ASPECT_RATIO_Y);
                scaleType = Defaults.VALID_SCALE_TYPES[ta.getInt(R.styleable.CropImageView_scaleType, Defaults.DEFAULT_SCALE_TYPE_INDEX)];
                cropShape = Defaults.VALID_CROP_SHAPES[ta.getInt(R.styleable.CropImageView_cropShape, Defaults.DEFAULT_CROP_SHAPE_INDEX)];
                snapRadius = ta.getFloat(R.styleable.CropImageView_snapRadius, snapRadius);
                mShowProgressBar = ta.getBoolean(R.styleable.CropImageView_showProgressBar, mShowProgressBar);
            } finally {
                ta.recycle();
            }
        }

        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.crop_image_view, this, true);

        mImageView = (ImageView) v.findViewById(R.id.crop_image_view_image);
        mImageView.setScaleType(scaleType);

        mCropOverlayView = (CropOverlayView) v.findViewById(R.id.crop_image_view_crop_overlay_view);
        mCropOverlayView.setInitialAttributeValues(guidelines, fixAspectRatio, aspectRatioX, aspectRatioY);
        mCropOverlayView.setCropShape(cropShape);
        mCropOverlayView.setSnapRadius(snapRadius);
        mCropOverlayView.setVisibility(mBitmap != null ? VISIBLE : INVISIBLE);

        mProgressBar = (ProgressBar) v.findViewById(R.id.crop_image_view_progress_bar);
        setProgressBarVisibility();
    }

    /**     * Set the scale type of the image in the crop view     */    public ImageView.ScaleType getScaleType() {
        return mImageView.getScaleType();
    }

    /**     * Set the scale type of the image in the crop view     */    public void setScaleType(ImageView.ScaleType scaleType) {
        mImageView.setScaleType(scaleType);
    }

    /**     * The shape of the cropping area - rectangle/circular.     */    public CropShape getCropShape() {
        return mCropOverlayView.getCropShape();
    }

    /**     * The shape of the cropping area - rectangle/circular.     */    public void setCropShape(CropShape cropShape) {
        mCropOverlayView.setCropShape(cropShape);
    }

    /**     * Sets whether the aspect ratio is fixed or not; true fixes the aspect ratio, while     * false allows it to be changed.     *     * @param fixAspectRatio Boolean that signals whether the aspect ratio should be     * maintained.     */    public void setFixedAspectRatio(boolean fixAspectRatio) {
        mCropOverlayView.setFixedAspectRatio(fixAspectRatio);
    }

    /**     * Sets the guidelines for the CropOverlayView to be either on, off, or to show when     * resizing the application.     *     * @param guidelines Integer that signals whether the guidelines should be on, off, or     * only showing when resizing.     */    public void setGuidelines(int guidelines) {
        mCropOverlayView.setGuidelines(guidelines);
    }

    /**     * Sets the both the X and Y values of the aspectRatio.     *     * @param aspectRatioX int that specifies the new X value of the aspect ratio     * @param aspectRatioY int that specifies the new Y value of the aspect ratio     */    public void setAspectRatio(int aspectRatioX, int aspectRatioY) {
        mCropOverlayView.setAspectRatioX(aspectRatioX);
        mCropOverlayView.setAspectRatioY(aspectRatioY);
    }

    /**     * An edge of the crop window will snap to the corresponding edge of a     * specified bounding box when the crop window edge is less than or equal to     * this distance (in pixels) away from the bounding box edge. (default: 3)     */    public void setSnapRadius(float snapRadius) {
        if (snapRadius >= 0) {
            mCropOverlayView.setSnapRadius(snapRadius);
        }
    }

    /**     * if to show progress bar when image async loading/cropping is in progress.<br>
     * default: true, disable to provide custom progress bar UI.     */    public boolean isShowProgressBar() {
        return mShowProgressBar;
    }

    /**     * if to show progress bar when image async loading/cropping is in progress.<br>
     * default: true, disable to provide custom progress bar UI.     */    public void setShowProgressBar(boolean showProgressBar) {
        mShowProgressBar = showProgressBar;
        setProgressBarVisibility();
    }

    /**     * Returns the integer of the imageResource     */    public int getImageResource() {
        return mImageResource;
    }

    /**     * Get the URI of an image that was set by URI, null otherwise.     */    public Uri getImageUri() {
        return mLoadedImageUri;
    }

    /**     * Gets the crop window's position relative to the source Bitmap (not the image     * displayed in the CropImageView).     *     * @return a RectF instance containing cropped area boundaries of the source Bitmap     */    public Rect getActualCropRect() {
        if (mBitmap != null) {
            final Rect displayedImageRect = ImageViewUtil.getBitmapRect(mBitmap, mImageView, mImageView.getScaleType());

            // Get the scale factor between the actual Bitmap dimensions and the displayed dimensions for width.            final float actualImageWidth = mBitmap.getWidth();
            final float displayedImageWidth = displayedImageRect.width();
            final float scaleFactorWidth = actualImageWidth / displayedImageWidth;

            // Get the scale factor between the actual Bitmap dimensions and the displayed dimensions for height.            final float actualImageHeight = mBitmap.getHeight();
            final float displayedImageHeight = displayedImageRect.height();
            final float scaleFactorHeight = actualImageHeight / displayedImageHeight;

            // Get crop window position relative to the displayed image.            final float displayedCropLeft = Edge.LEFT.getCoordinate() - displayedImageRect.left;
            final float displayedCropTop = Edge.TOP.getCoordinate() - displayedImageRect.top;
            final float displayedCropWidth = Edge.getWidth();
            final float displayedCropHeight = Edge.getHeight();

            // Scale the crop window position to the actual size of the Bitmap.            float actualCropLeft = displayedCropLeft * scaleFactorWidth;
            float actualCropTop = displayedCropTop * scaleFactorHeight;
            float actualCropRight = actualCropLeft + displayedCropWidth * scaleFactorWidth;
            float actualCropBottom = actualCropTop + displayedCropHeight * scaleFactorHeight;

            // Correct for floating point errors. Crop rect boundaries should not exceed the source Bitmap bounds.            actualCropLeft = Math.max(0f, actualCropLeft);
            actualCropTop = Math.max(0f, actualCropTop);
            actualCropRight = Math.min(mBitmap.getWidth(), actualCropRight);
            actualCropBottom = Math.min(mBitmap.getHeight(), actualCropBottom);

            return new Rect((int) actualCropLeft, (int) actualCropTop, (int) actualCropRight, (int) actualCropBottom);
        } else {
            return null;
        }
    }

    /**     * Gets the crop window's position relative to the source Bitmap (not the image     * displayed in the CropImageView) and the original rotation.     *     * @return a RectF instance containing cropped area boundaries of the source Bitmap     */    @SuppressWarnings("SuspiciousNameCombination")
    public Rect getActualCropRectNoRotation() {
        if (mBitmap != null) {
            Rect rect = getActualCropRect();
            int rotateSide = mDegreesRotated / 90;
            if (rotateSide == 1) {
                rect.set(rect.top, mBitmap.getWidth() - rect.right, rect.bottom, mBitmap.getWidth() - rect.left);
            } else if (rotateSide == 2) {
                rect.set(mBitmap.getWidth() - rect.right, mBitmap.getHeight() - rect.bottom, mBitmap.getWidth() - rect.left, mBitmap.getHeight() - rect.top);
            } else if (rotateSide == 3) {
                rect.set(mBitmap.getHeight() - rect.bottom, rect.left, mBitmap.getHeight() - rect.top, rect.right);
            }
            rect.set(rect.left * mLoadedSampleSize, rect.top * mLoadedSampleSize, rect.right * mLoadedSampleSize, rect.bottom * mLoadedSampleSize);
            return rect;
        } else {
            return null;
        }
    }

    /**     * Gets the cropped image based on the current crop window.     *     * @return a new Bitmap representing the cropped image     */    public Bitmap getCroppedImage() {
        return getCroppedImage(0, 0);
    }

    /**     * Gets the cropped image based on the current crop window.<br>
     * If image loaded from URI will use sample size to fit in the requested width and height down-sampling     * if required - optimization to get best size to quality.     *     * @return a new Bitmap representing the cropped image     */    public Bitmap getCroppedImage(int reqWidth, int reqHeight) {
        if (mBitmap != null) {
            if (mLoadedImageUri != null && mLoadedSampleSize > 1) {
                return ImageViewUtil.cropBitmap(
                        getContext(),
                        mLoadedImageUri,
                        getActualCropRectNoRotation(),
                        mDegreesRotated,
                        reqWidth,
                        reqHeight);
            } else {
                return ImageViewUtil.cropBitmap(mBitmap, getActualCropRect());
            }
        } else {
            return null;
        }
    }

    /**     * Gets the cropped circle image based on the current crop selection.<br>
     * Same as {@link #getCroppedImage()} (as the bitmap is rectangular by nature) but the pixels beyond the     * oval crop will be transparent.     *     * @return a new Circular Bitmap representing the cropped image     */    public Bitmap getCroppedOvalImage() {
        if (mBitmap != null) {
            Bitmap cropped = getCroppedImage();
            return ImageViewUtil.toOvalBitmap(cropped);
        } else {
            return null;
        }
    }

    /**     * Gets the cropped image based on the current crop window.<br>
     * The result will be invoked to listener set by {@link #setOnGetCroppedImageCompleteListener(OnGetCroppedImageCompleteListener)}.     */    public void getCroppedImageAsync() {
        getCroppedImageAsync(CropShape.RECTANGLE, 0, 0);
    }

    /**     * Gets the cropped image based on the current crop window.<br>
     * If image loaded from URI will use sample size to fit in the requested width and height down-sampling     * if required - optimization to get best size to quality.<br>
     * The result will be invoked to listener set by {@link #setOnGetCroppedImageCompleteListener(OnGetCroppedImageCompleteListener)}.     *     * @param cropShape the shape to crop the image     */    public void getCroppedImageAsync(CropShape cropShape, int reqWidth, int reqHeight) {
        if (mOnGetCroppedImageCompleteListener == null) {
            throw new IllegalArgumentException("OnGetCroppedImageCompleteListener is not set");
        }
        BitmapCroppingWorkerTask currentTask = mBitmapCroppingWorkerTask != null ? mBitmapCroppingWorkerTask.get() : null;
        if (currentTask != null) {
            // cancel previous cropping            currentTask.cancel(true);
        }

        mBitmapCroppingWorkerTask = mLoadedImageUri != null && mLoadedSampleSize > 1                ? new WeakReference<>(new BitmapCroppingWorkerTask(this, mLoadedImageUri, getActualCropRectNoRotation(), cropShape, mDegreesRotated, reqWidth, reqHeight))
                : new WeakReference<>(new BitmapCroppingWorkerTask(this, mBitmap, getActualCropRect(), cropShape));
        mBitmapCroppingWorkerTask.get().execute();
        setProgressBarVisibility();
    }

    /**     * Set the callback to be invoked when image async loading ({@link #setImageUriAsync(Uri)})     * is complete (successful or failed).     */    public void setOnSetImageUriCompleteListener(OnSetImageUriCompleteListener listener) {
        mOnSetImageUriCompleteListener = listener != null ? new WeakReference<>(listener) : null;
    }

    /**     * Set the callback to be invoked when image async cropping ({@link #getCroppedImageAsync()})     * is complete (successful or failed).     */    public void setOnGetCroppedImageCompleteListener(OnGetCroppedImageCompleteListener listener) {
        mOnGetCroppedImageCompleteListener = listener != null ? new WeakReference<>(listener) : null;
    }

    /**     * Sets a Bitmap as the content of the CropImageView.     *     * @param bitmap the Bitmap to set     */    public void setImageBitmap(Bitmap bitmap) {
        setBitmap(bitmap, true);
    }

    /**     * Sets a Bitmap and initializes the image rotation according to the EXIT data.<br>
     * <br>
     * The EXIF can be retrieved by doing the following:     * <code>ExifInterface exif = new ExifInterface(path);</code>
     *     * @param bitmap the original bitmap to set; if null, this     * @param exif the EXIF information about this bitmap; may be null     */    public void setImageBitmap(Bitmap bitmap, ExifInterface exif) {
        if (bitmap != null && exif != null) {
            ImageViewUtil.RotateBitmapResult result = ImageViewUtil.rotateBitmapByExif(bitmap, exif);
            bitmap = result.bitmap;
            mDegreesRotated = result.degrees;
        }
        setBitmap(bitmap, true);
    }

    /**     * Sets a Drawable as the content of the CropImageView.     *     * @param resId the drawable resource ID to set     */    public void setImageResource(int resId) {
        if (resId != 0) {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
            setBitmap(bitmap, true);
            mImageResource = resId;
        }
    }

    /**     * Sets a bitmap loaded from the given Android URI as the content of the CropImageView.<br>
     * Can be used with URI from gallery or camera source.<br>
     * Will rotate the image by exif data.<br>
     *     * @param uri the URI to load the image from     * @deprecated Use {@link #setImageUriAsync(Uri)} for better async handling     */    @Deprecated    public void setImageUri(Uri uri) {
        if (uri != null) {

            DisplayMetrics metrics = getResources().getDisplayMetrics();
            double densityAdj = metrics.density > 1 ? 1 / metrics.density : 1;
            //mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
            int width = displayMetrics.widthPixels;
            int height = width;

//            int width = (int) (metrics.widthPixels * densityAdj);//            int height = (int) (metrics.heightPixels * densityAdj);
            ImageViewUtil.DecodeBitmapResult decodeResult =
                    ImageViewUtil.decodeSampledBitmap(getContext(), uri, width, height);

            ImageViewUtil.RotateBitmapResult rotateResult =
                    ImageViewUtil.rotateBitmapByExif(getContext(), decodeResult.bitmap, uri);

            setBitmap(rotateResult.bitmap, true);

            mLoadedImageUri = uri;
            mLoadedSampleSize = decodeResult.sampleSize;
            mDegreesRotated = rotateResult.degrees;
        }
    }

    /**     * Sets a bitmap loaded from the given Android URI as the content of the CropImageView.<br>
     * Can be used with URI from gallery or camera source.<br>
     * Will rotate the image by exif data.<br>
     *     * @param uri the URI to load the image from     */    public void setImageUriAsync(Uri uri) {
        setImageUriAsync(uri, null);
    }

    /**     * Clear the current image set for cropping.     */    public void clearImage() {
        clearImage(true);
    }

    /**     * Rotates image by the specified number of degrees clockwise. Cycles from 0 to 360     * degrees.     *     * @param degrees Integer specifying the number of degrees to rotate.     */    public void rotateImage(int degrees) {
        if (mBitmap != null) {
            Matrix matrix = new Matrix();
            matrix.postRotate(degrees);
            Bitmap bitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true);
            setBitmap(bitmap, false);

            mDegreesRotated += degrees;
            mDegreesRotated = mDegreesRotated % 360;
        }
    }

    //region: Private methods    /**     * Load image from given URI async using {@link BitmapLoadingWorkerTask}<br>
     * optionally rotate the loaded image given degrees, used for restore state.     */    private void setImageUriAsync(Uri uri, Integer preSetRotation) {
        if (uri != null) {
            BitmapLoadingWorkerTask currentTask = mBitmapLoadingWorkerTask != null ? mBitmapLoadingWorkerTask.get() : null;
            if (currentTask != null) {
                // cancel previous loading (no check if the same URI because camera URI can be the same for different images)                currentTask.cancel(true);
            }

            // either no existing task is working or we canceled it, need to load new URI            clearImage(true);
            mBitmapLoadingWorkerTask = new WeakReference<>(new BitmapLoadingWorkerTask(this, uri, preSetRotation));
            mBitmapLoadingWorkerTask.get().execute();
            setProgressBarVisibility();
        }
    }

    /**     * On complete of the async bitmap loading by {@link #setImageUriAsync(Uri)} set the result     * to the widget if still relevant and call listener if set.     *     * @param result the result of bitmap loading     */    void onSetImageUriAsyncComplete(BitmapLoadingWorkerTask.Result result) {

        mBitmapLoadingWorkerTask = null;
        setProgressBarVisibility();

        if (result.error == null) {
            setBitmap(result.bitmap, true);
            mLoadedImageUri = result.uri;
            mLoadedSampleSize = result.loadSampleSize;
            mDegreesRotated = result.degreesRotated;
        }

        OnSetImageUriCompleteListener listener = mOnSetImageUriCompleteListener != null                ? mOnSetImageUriCompleteListener.get() : null;
        if (listener != null) {
            listener.onSetImageUriComplete(this, result.uri, result.error);
        }
    }

    /**     * On complete of the async bitmap cropping by {@link #getCroppedImageAsync()} call listener if set.     *     * @param result the result of bitmap cropping     */    void onGetImageCroppingAsyncComplete(BitmapCroppingWorkerTask.Result result) {
        mBitmapCroppingWorkerTask = null;
        setProgressBarVisibility();

        OnGetCroppedImageCompleteListener listener = mOnGetCroppedImageCompleteListener != null                ? mOnGetCroppedImageCompleteListener.get() : null;
        if (listener != null) {
            listener.onGetCroppedImageComplete(this, result.bitmap, result.error);
        }
    }

    /**     * Set the given bitmap to be used in for cropping<br>
     * Optionally clear full if the bitmap is new, or partial clear if the bitmap has been manipulated.     */    private void setBitmap(Bitmap bitmap, boolean clearFull) {
        if (mBitmap != bitmap) {

            clearImage(clearFull);

            mBitmap = bitmap;
            mImageView.setImageBitmap(mBitmap);
            if (mCropOverlayView != null) {
                mCropOverlayView.resetCropOverlayView();
                mCropOverlayView.setVisibility(VISIBLE);
            }
        }
    }

    /**     * Clear the current image set for cropping.<br>
     * Full clear will also clear the data of the set image like Uri or Resource id while partial clear     * will only clear the bitmap and recycle if required.     */    private void clearImage(boolean full) {
        // if we allocated the bitmap, release it as fast as possible        if (mBitmap != null && (mImageResource > 0 || mLoadedImageUri != null)) {
            mBitmap.recycle();
            mBitmap = null;
        }

        if (full) {
            // clean the loaded image flags for new image            mImageResource = 0;
            mLoadedImageUri = null;
            mLoadedSampleSize = 1;
            mDegreesRotated = 0;

            mImageView.setImageBitmap(null);

            if (mCropOverlayView != null) {
                mCropOverlayView.setVisibility(INVISIBLE);
            }
        }
    }

    @Override    public Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable("instanceState", super.onSaveInstanceState());
        bundle.putParcelable("LOADED_IMAGE_URI", mLoadedImageUri);
        bundle.putInt("LOADED_IMAGE_RESOURCE", mImageResource);
        if (mLoadedImageUri == null && mImageResource < 1) {
            bundle.putParcelable("SET_BITMAP", mBitmap);
        }
        if (mBitmapLoadingWorkerTask != null) {
            BitmapLoadingWorkerTask task = mBitmapLoadingWorkerTask.get();
            if (task != null) {
                bundle.putParcelable("LOADING_IMAGE_URI", task.getUri());
            }
        }
        bundle.putInt("DEGREES_ROTATED", mDegreesRotated);
        return bundle;
    }

    @Override    public void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;

            Bitmap bitmap = null;
            Uri uri = bundle.getParcelable("LOADED_IMAGE_URI");
            if (uri != null) {
                setImageUriAsync(uri, bundle.getInt("DEGREES_ROTATED"));
            } else {
                int resId = bundle.getInt("LOADED_IMAGE_RESOURCE");
                if (resId > 0) {
                    setImageResource(resId);
                } else {
                    bitmap = bundle.getParcelable("SET_BITMAP");
                    if (bitmap != null) {
                        setBitmap(bitmap, true);
                    } else {
                        uri = bundle.getParcelable("LOADING_IMAGE_URI");
                        if (uri != null) {
                            setImageUriAsync(uri);
                        }
                    }
                }
            }

            mDegreesRotated = bundle.getInt("DEGREES_ROTATED");
            if (mBitmap != null && bitmap == null) {
                // Fixes the rotation of the image when we reloaded it.                int tmpRotated = mDegreesRotated;
                rotateImage(mDegreesRotated);
                mDegreesRotated = tmpRotated;
            }
            super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
        } else {
            super.onRestoreInstanceState(state);
        }
    }

    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {

        if (mBitmap != null) {
            Rect bitmapRect = ImageViewUtil.getBitmapRect(mBitmap, this, mImageView.getScaleType());
            mCropOverlayView.setBitmapRect(bitmapRect);
        } else {
            mCropOverlayView.setBitmapRect(Defaults.EMPTY_RECT);
        }
    }

    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (mBitmap != null) {

            // Bypasses a baffling bug when used within a ScrollView, where heightSize is set to 0.            if (heightSize == 0) {
                heightSize = mBitmap.getHeight();
            }

            int desiredWidth;
            int desiredHeight;

            double viewToBitmapWidthRatio = Double.POSITIVE_INFINITY;
            double viewToBitmapHeightRatio = Double.POSITIVE_INFINITY;

            // Checks if either width or height needs to be fixed            if (widthSize < mBitmap.getWidth()) {
                viewToBitmapWidthRatio = (double) widthSize / (double) mBitmap.getWidth();
            }
            if (heightSize < mBitmap.getHeight()) {
                viewToBitmapHeightRatio = (double) heightSize / (double) mBitmap.getHeight();
            }

            // If either needs to be fixed, choose smallest ratio and calculate from there            if (viewToBitmapWidthRatio != Double.POSITIVE_INFINITY || viewToBitmapHeightRatio != Double.POSITIVE_INFINITY) {
                if (viewToBitmapWidthRatio <= viewToBitmapHeightRatio) {
                    desiredWidth = widthSize;
                    desiredHeight = (int) (mBitmap.getHeight() * viewToBitmapWidthRatio);
                } else {
                    desiredHeight = heightSize;
                    desiredWidth = (int) (mBitmap.getWidth() * viewToBitmapHeightRatio);
                }
            } else {
                // Otherwise, the picture is within frame layout bounds. Desired width is simply picture size                desiredWidth = mBitmap.getWidth();
                desiredHeight = mBitmap.getHeight();
            }

            int width = getOnMeasureSpec(widthMode, widthSize, desiredWidth);
            int height = getOnMeasureSpec(heightMode, heightSize, desiredHeight);

            mLayoutWidth = width;
            mLayoutHeight = height;

            Rect bitmapRect = ImageViewUtil.getBitmapRect(mBitmap.getWidth(),
                    mBitmap.getHeight(),
                    mLayoutWidth,
                    mLayoutHeight,
                    mImageView.getScaleType());
            mCropOverlayView.setBitmapRect(bitmapRect);

            // MUST CALL THIS            setMeasuredDimension(mLayoutWidth, mLayoutHeight);

        } else {
            mCropOverlayView.setBitmapRect(Defaults.EMPTY_RECT);
            setMeasuredDimension(widthSize, heightSize);
        }
    }

    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (mLayoutWidth > 0 && mLayoutHeight > 0) {
            // Gets original parameters, and creates the new parameters            ViewGroup.LayoutParams origParams = this.getLayoutParams();
            origParams.width = mLayoutWidth;
            origParams.height = mLayoutHeight;
            setLayoutParams(origParams);
        }
    }

    /**     * Determines the specs for the onMeasure function. Calculates the width or height     * depending on the mode.     *     * @param measureSpecMode The mode of the measured width or height.     * @param measureSpecSize The size of the measured width or height.     * @param desiredSize The desired size of the measured width or height.     * @return The final size of the width or height.     */    private static int getOnMeasureSpec(int measureSpecMode, int measureSpecSize, int desiredSize) {
        // Measure Width        int spec;
        if (measureSpecMode == MeasureSpec.EXACTLY) {
            // Must be this size            spec = measureSpecSize;
        } else if (measureSpecMode == MeasureSpec.AT_MOST) {
            // Can't be bigger than...; match_parent value            spec = Math.min(desiredSize, measureSpecSize);
        } else {
            // Be whatever you want; wrap_content            spec = desiredSize;
        }

        return spec;
    }

    /**     * Set visibility of progress bar when async loading/cropping is in process and show is enabled.     */    private void setProgressBarVisibility() {
        boolean visible =
                mShowProgressBar && (
                        (mBitmap == null && mBitmapLoadingWorkerTask != null) ||
                                (mBitmapCroppingWorkerTask != null));
        mProgressBar.setVisibility(visible ? VISIBLE : INVISIBLE);
    }
    //endregion
    //region: Inner class: CropShape
    /**     * The possible cropping area shape.     */    public enum CropShape {
        RECTANGLE,
        OVAL    }
    //endregion
    //region: Inner class: OnSetImageUriCompleteListener
    /**     * Interface definition for a callback to be invoked when image async loading is complete.     */    public interface OnSetImageUriCompleteListener {

        /**         * Called when a crop image view has completed loading image for cropping.<br>
         * If loading failed error parameter will contain the error.         *         * @param view The crop image view that loading of image was complete.         * @param uri the URI of the image that was loading         * @param error if error occurred during loading will contain the error, otherwise null.         */        void onSetImageUriComplete(CropImageView view, Uri uri, Exception error);
    }
    //endregion
    //region: Inner class: OnGetCroppedImageCompleteListener
    /**     * Interface definition for a callback to be invoked when image async cropping is complete.     */    public interface OnGetCroppedImageCompleteListener {

        /**         * Called when a crop image view has completed loading image for cropping.<br>
         * If loading failed error parameter will contain the error.         *         * @param view The crop image view that cropping of image was complete.         * @param bitmap the cropped image bitmap (null if failed)         * @param error if error occurred during cropping will contain the error, otherwise null.         */        void onGetCroppedImageComplete(CropImageView view, Bitmap bitmap, Exception error);
    }
    //endregion}
4)CropOverlayView.java
=========================
/* * Copyright 2013, Edmodo, Inc.  * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. * You may obtain a copy of the License in the LICENSE file, or at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"  * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language  * governing permissions and limitations under the License.  */
package com.credencys.myapplication.widgets;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;

import com.credencys.myapplication.cropwindow.AspectRatioUtil;
import com.credencys.myapplication.cropwindow.HandleUtil;
import com.credencys.myapplication.cropwindow.PaintUtil;
import com.credencys.myapplication.cropwindow.edge.Edge;
import com.credencys.myapplication.cropwindow.handle.Handle;

/** * A custom View representing the crop window and the shaded background outside the crop window. */public class CropOverlayView extends View {
    //region: Fields and Consts    /**     * The Paint used to draw the white rectangle around the crop area.     */    private Paint mBorderPaint;

    /**     * The Paint used to draw the guidelines within the crop area when pressed.     */    private Paint mGuidelinePaint;

    /**     * The Paint used to draw the corners of the Border     */    private Paint mCornerPaint;

    /**     * The Paint used to darken the surrounding areas outside the crop area.     */    private Paint mBackgroundPaint;

    /**     * The bounding box around the Bitmap that we are cropping.     */    private Rect mBitmapRect;

    // The radius of the touch zone (in pixels) around a given Handle.    private float mHandleRadius;

    // An edge of the crop window will snap to the corresponding edge of a    // specified bounding box when the crop window edge is less than or equal to    // this distance (in pixels) away from the bounding box edge.    private float mSnapRadius;

    // Holds the x and y offset between the exact touch location and the exact    // handle location that is activated. There may be an offset because we    // allow for some leeway (specified by mHandleRadius) in activating a    // handle. However, we want to maintain these offset values while the handle    // is being dragged so that the handle doesn't jump.    private Pair<Float, Float> mTouchOffset;

    // The Handle that is currently pressed; null if no Handle is pressed.    private Handle mPressedHandle;

    // Flag indicating if the crop area should always be a certain aspect ratio    // (indicated by mTargetAspectRatio).    private boolean mFixAspectRatio = Defaults.DEFAULT_FIXED_ASPECT_RATIO;

    // Floats to save the current aspect ratio of the image    private int mAspectRatioX = Defaults.DEFAULT_ASPECT_RATIO_X;

    private int mAspectRatioY = Defaults.DEFAULT_ASPECT_RATIO_Y;

    // The aspect ratio that the crop area should maintain; this variable is    // only used when mMaintainAspectRatio is true.    private float mTargetAspectRatio = ((float) mAspectRatioX) / mAspectRatioY;

    /**     * Instance variables for customizable attributes     */    private int mGuidelines;

    /**     * The shape of the cropping area - rectangle/circular.     */    private CropImageView.CropShape mCropShape;

    // Whether the Crop View has been initialized for the first time    private boolean initializedCropWindow = false;

    // Instance variables for the corner values    private float mCornerExtension;

    private float mCornerOffset;

    private float mCornerLength;

    /**     * Used to set back LayerType after changing to software.     */    private Integer mOriginalLayerType;
    //endregion
    public CropOverlayView(Context context) {
        super(context);
        init(context);
    }

    public CropOverlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    /**     * Informs the CropOverlayView of the image's position relative to the     * ImageView. This is necessary to call in order to draw the crop window.     *     * @param bitmapRect the image's bounding box     */    public void setBitmapRect(Rect bitmapRect) {
        mBitmapRect = bitmapRect;
        initCropWindow(mBitmapRect);
    }

    /**     * Resets the crop overlay view.     */    public void resetCropOverlayView() {

        if (initializedCropWindow) {
            initCropWindow(mBitmapRect);
            invalidate();
        }
    }

    /**     * The shape of the cropping area - rectangle/circular.     */    public CropImageView.CropShape getCropShape() {
        return mCropShape;
    }

    /**     * The shape of the cropping area - rectangle/circular.     */    public void setCropShape(CropImageView.CropShape cropShape) {
        if (mCropShape != cropShape) {
            mCropShape = cropShape;
            if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT <= 17) {
                if (mCropShape == CropImageView.CropShape.OVAL) {
                    mOriginalLayerType = getLayerType();
                    if (mOriginalLayerType != View.LAYER_TYPE_SOFTWARE) {
                        // TURN off hardware acceleration                        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                    } else {
                        mOriginalLayerType = null;
                    }
                } else if (mOriginalLayerType != null) {
                    // return hardware acceleration back                    setLayerType(mOriginalLayerType, null);
                    mOriginalLayerType = null;
                }
            }
            invalidate();
        }
    }

    /**     * Sets the guidelines for the CropOverlayView to be either on, off, or to     * show when resizing the application.     *     * @param guidelines Integer that signals whether the guidelines should be     * on, off, or only showing when resizing.     */    public void setGuidelines(int guidelines) {
        if (guidelines < 0 || guidelines > 2)
            throw new IllegalArgumentException("Guideline value must be set between 0 and 2. See documentation.");
        else {
            mGuidelines = guidelines;

            if (initializedCropWindow) {
                initCropWindow(mBitmapRect);
                invalidate();
            }
        }
    }

    /**     * Sets whether the aspect ratio is fixed or not; true fixes the aspect     * ratio, while false allows it to be changed.     *     * @param fixAspectRatio Boolean that signals whether the aspect ratio     * should be maintained.     */    public void setFixedAspectRatio(boolean fixAspectRatio) {
        mFixAspectRatio = fixAspectRatio;

        if (initializedCropWindow) {
            initCropWindow(mBitmapRect);
            invalidate();
        }
    }

    /**     * Sets the X value of the aspect ratio; is defaulted to 1.     *     * @param aspectRatioX int that specifies the new X value of the aspect     * ratio     */    public void setAspectRatioX(int aspectRatioX) {
        if (aspectRatioX <= 0)
            throw new IllegalArgumentException("Cannot set aspect ratio value to a number less than or equal to 0.");
        else {
            mAspectRatioX = aspectRatioX;
            mTargetAspectRatio = ((float) mAspectRatioX) / mAspectRatioY;

            if (initializedCropWindow) {
                initCropWindow(mBitmapRect);
                invalidate();
            }
        }
    }

    /**     * Sets the Y value of the aspect ratio; is defaulted to 1.     *     * @param aspectRatioY int that specifies the new Y value of the aspect     * ratio     */    public void setAspectRatioY(int aspectRatioY) {
        if (aspectRatioY <= 0)
            throw new IllegalArgumentException("Cannot set aspect ratio value to a number less than or equal to 0.");
        else {
            mAspectRatioY = aspectRatioY;
            mTargetAspectRatio = ((float) mAspectRatioX) / mAspectRatioY;

            if (initializedCropWindow) {
                initCropWindow(mBitmapRect);
                invalidate();
            }
        }
    }

    /**     * An edge of the crop window will snap to the corresponding edge of a     * specified bounding box when the crop window edge is less than or equal to     * this distance (in pixels) away from the bounding box edge. (default: 3)     */    public void setSnapRadius(float snapRadius) {
        mSnapRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, snapRadius, getResources().getDisplayMetrics());
    }

    /**     * Sets all initial values, but does not call initCropWindow to reset the     * views. Used once at the very start to initialize the attributes.     *     * @param guidelines Integer that signals whether the guidelines should be     * on, off, or only showing when resizing.     * @param fixAspectRatio Boolean that signals whether the aspect ratio     * should be maintained.     * @param aspectRatioX float that specifies the new X value of the aspect     * ratio     * @param aspectRatioY float that specifies the new Y value of the aspect     * ratio     */    public void setInitialAttributeValues(int guidelines, boolean fixAspectRatio, int aspectRatioX, int aspectRatioY) {
        if (guidelines < 0 || guidelines > 2)
            throw new IllegalArgumentException("Guideline value must be set between 0 and 2. See documentation.");
        else            mGuidelines = guidelines;

        mFixAspectRatio = fixAspectRatio;

        if (aspectRatioX <= 0)
            throw new IllegalArgumentException("Cannot set aspect ratio value to a number less than or equal to 0.");
        else {
            mAspectRatioX = aspectRatioX;
            mTargetAspectRatio = ((float) mAspectRatioX) / mAspectRatioY;
        }

        if (aspectRatioY <= 0)
            throw new IllegalArgumentException("Cannot set aspect ratio value to a number less than or equal to 0.");
        else {
            mAspectRatioY = aspectRatioY;
            mTargetAspectRatio = ((float) mAspectRatioX) / mAspectRatioY;
        }

    }

    //region: Private methods    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {

        // Initialize the crop window here because we need the size of the view        // to have been determined.        initCropWindow(mBitmapRect);
    }

    @Override    protected void onDraw(Canvas canvas) {

        super.onDraw(canvas);

        // Draw translucent background for the cropped area.        drawBackground(canvas, mBitmapRect);

        if (showGuidelines()) {
            // Determines whether guidelines should be drawn or not            if (mGuidelines == Defaults.GUIDELINES_ON) {
                drawRuleOfThirdsGuidelines(canvas);
            } else if (mGuidelines == Defaults.GUIDELINES_ON_TOUCH) {
                // Draw only when resizing                if (mPressedHandle != null)
                    drawRuleOfThirdsGuidelines(canvas);
            }
        }

        float w = mBorderPaint.getStrokeWidth();
        float l = Edge.LEFT.getCoordinate() + w / 2;
        float t = Edge.TOP.getCoordinate() + w / 2;
        float r = Edge.RIGHT.getCoordinate() - w / 2;
        float b = Edge.BOTTOM.getCoordinate() - w / 2;
        if (mCropShape == CropImageView.CropShape.RECTANGLE) {
            // Draw rectangle crop window border.            canvas.drawRect(l, t, r, b, mBorderPaint);
            drawCorners(canvas);
        } else {
            // Draw circular crop window border            Defaults.EMPTY_RECT_F.set(l, t, r, b);
            canvas.drawOval(Defaults.EMPTY_RECT_F, mBorderPaint);
        }
    }

    @Override    public boolean onTouchEvent(@SuppressWarnings("NullableProblems") MotionEvent event) {

        // If this View is not enabled, don't allow for touch interactions.        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                onActionDown(event.getX(), event.getY());
                return true;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                getParent().requestDisallowInterceptTouchEvent(false);
                onActionUp();
                return true;

            case MotionEvent.ACTION_MOVE:
                onActionMove(event.getX(), event.getY());
                getParent().requestDisallowInterceptTouchEvent(true);
                return true;

            default:
                return false;
        }
    }

    private void init(Context context) {

        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();

        mHandleRadius = HandleUtil.getTargetRadius(context);

        mSnapRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, Defaults.SNAP_RADIUS_DP, displayMetrics);

        mBorderPaint = PaintUtil.newBorderPaint(context);
        mGuidelinePaint = PaintUtil.newGuidelinePaint();
        mBackgroundPaint = PaintUtil.newBackgroundPaint();
        mCornerPaint = PaintUtil.newCornerPaint(context);

        // Sets the values for the corner sizes        mCornerOffset = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                Defaults.DEFAULT_CORNER_OFFSET_DP,
                displayMetrics);
        mCornerExtension = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                Defaults.DEFAULT_CORNER_EXTENSION_DP,
                displayMetrics);
        mCornerLength = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                Defaults.DEFAULT_CORNER_LENGTH_DP,
                displayMetrics);

        // Sets guidelines to default until specified otherwise        mGuidelines = Defaults.DEFAULT_GUIDELINES;
    }

    /**     * Set the initial crop window size and position. This is dependent on the     * size and position of the image being cropped.     *     * @param bitmapRect the bounding box around the image being cropped     */    private void initCropWindow(Rect bitmapRect) {

        if (bitmapRect.width() == 0 || bitmapRect.height() == 0) {
            return;
        }

        // Tells the attribute functions the crop window has already been        // initialized        if (!initializedCropWindow) {
            initializedCropWindow = true;
        }

        if (mFixAspectRatio                && (bitmapRect.left != 0 || bitmapRect.right != 0                || bitmapRect.top != 0 || bitmapRect.bottom != 0)) {

            // If the image aspect ratio is wider than the crop aspect ratio,            // then the image height is the determining initial length. Else,            // vice-versa.            if (AspectRatioUtil.calculateAspectRatio(bitmapRect) > mTargetAspectRatio) {

                Edge.TOP.setCoordinate(bitmapRect.top);
                Edge.BOTTOM.setCoordinate(bitmapRect.bottom);

                float centerX = getWidth() / 2f;

                //dirty fix for wrong crop overlay aspect ratio when using fixed aspect ratio                mTargetAspectRatio = (float) mAspectRatioX / mAspectRatioY;

                // Limits the aspect ratio to no less than 40 wide or 40 tall                float cropWidth = Math.max(Edge.MIN_CROP_LENGTH_PX,
                        AspectRatioUtil.calculateWidth(Edge.TOP.getCoordinate(),
                                Edge.BOTTOM.getCoordinate(),
                                mTargetAspectRatio));

                // Create new TargetAspectRatio if the original one does not fit                // the screen                if (cropWidth == Edge.MIN_CROP_LENGTH_PX) {
                    mTargetAspectRatio = (Edge.MIN_CROP_LENGTH_PX) / (Edge.BOTTOM.getCoordinate() - Edge.TOP.getCoordinate());
                }

                float halfCropWidth = cropWidth / 2f;
                Edge.LEFT.setCoordinate(centerX - halfCropWidth);
                Edge.RIGHT.setCoordinate(centerX + halfCropWidth);

            } else {

                Edge.LEFT.setCoordinate(bitmapRect.left);
                Edge.RIGHT.setCoordinate(bitmapRect.right);

                float centerY = getHeight() / 2f;

                // Limits the aspect ratio to no less than 40 wide or 40 tall                float cropHeight = Math.max(Edge.MIN_CROP_LENGTH_PX,
                        AspectRatioUtil.calculateHeight(Edge.LEFT.getCoordinate(),
                                Edge.RIGHT.getCoordinate(),
                                mTargetAspectRatio));

                // Create new TargetAspectRatio if the original one does not fit                // the screen                if (cropHeight == Edge.MIN_CROP_LENGTH_PX) {
                    mTargetAspectRatio = (Edge.RIGHT.getCoordinate() - Edge.LEFT.getCoordinate()) / Edge.MIN_CROP_LENGTH_PX;
                }

                float halfCropHeight = cropHeight / 2f;
                Edge.TOP.setCoordinate(centerY - halfCropHeight);
                Edge.BOTTOM.setCoordinate(centerY + halfCropHeight);
            }

        } else { // ... do not fix aspect ratio...
            // Initialize crop window to have 10% padding w/ respect to image.            float horizontalPadding = 0.1f * bitmapRect.width();
            float verticalPadding = 0.1f * bitmapRect.height();

            Edge.LEFT.setCoordinate(bitmapRect.left + horizontalPadding);
            Edge.TOP.setCoordinate(bitmapRect.top + verticalPadding);
            Edge.RIGHT.setCoordinate(bitmapRect.right - horizontalPadding);
            Edge.BOTTOM.setCoordinate(bitmapRect.bottom - verticalPadding);
        }
    }

    /**     * Indicates whether the crop window is small enough that the guidelines     * should be shown. Public because this function is also used to determine     * if the center handle should be focused.     *     * @return boolean Whether the guidelines should be shown or not     */    public static boolean showGuidelines() {
        if ((Math.abs(Edge.LEFT.getCoordinate() - Edge.RIGHT.getCoordinate()) < Defaults.DEFAULT_SHOW_GUIDELINES_LIMIT)
                || (Math.abs(Edge.TOP.getCoordinate() - Edge.BOTTOM.getCoordinate()) < Defaults.DEFAULT_SHOW_GUIDELINES_LIMIT)) {
            return false;
        } else {
            return true;
        }
    }

    private void drawRuleOfThirdsGuidelines(Canvas canvas) {

        float sw = mBorderPaint.getStrokeWidth();
        float l = Edge.LEFT.getCoordinate() + sw;
        float t = Edge.TOP.getCoordinate() + sw;
        float r = Edge.RIGHT.getCoordinate() - sw;
        float b = Edge.BOTTOM.getCoordinate() - sw;

        float oneThirdCropWidth = Edge.getWidth() / 3;
        float oneThirdCropHeight = Edge.getHeight() / 3;

        if (mCropShape == CropImageView.CropShape.OVAL) {

            float w = Edge.getWidth() / 2 - sw;
            float h = Edge.getHeight() / 2 - sw;

            // Draw vertical guidelines.            float x1 = l + oneThirdCropWidth;
            float x2 = r - oneThirdCropWidth;
            float yv = (float) (h * Math.sin(Math.acos((w - oneThirdCropWidth) / w)));
            canvas.drawLine(x1, t + h - yv, x1, b - h + yv, mGuidelinePaint);
            canvas.drawLine(x2, t + h - yv, x2, b - h + yv, mGuidelinePaint);

            // Draw horizontal guidelines.            float y1 = t + oneThirdCropHeight;
            float y2 = b - oneThirdCropHeight;
            float xv = (float) (w * Math.cos(Math.asin((h - oneThirdCropHeight) / h)));
            canvas.drawLine(l + w - xv, y1, r - w + xv, y1, mGuidelinePaint);
            canvas.drawLine(l + w - xv, y2, r - w + xv, y2, mGuidelinePaint);
        } else {

            // Draw vertical guidelines.            float x1 = l + oneThirdCropWidth;
            float x2 = r - oneThirdCropWidth;
            canvas.drawLine(x1, t, x1, b, mGuidelinePaint);
            canvas.drawLine(x2, t, x2, b, mGuidelinePaint);

            // Draw horizontal guidelines.            float y1 = t + oneThirdCropHeight;
            float y2 = b - oneThirdCropHeight;
            canvas.drawLine(l, y1, r, y1, mGuidelinePaint);
            canvas.drawLine(l, y2, r, y2, mGuidelinePaint);
        }
    }

    private void drawBackground(Canvas canvas, Rect bitmapRect) {

        float l = Edge.LEFT.getCoordinate();
        float t = Edge.TOP.getCoordinate();
        float r = Edge.RIGHT.getCoordinate();
        float b = Edge.BOTTOM.getCoordinate();

        if (mCropShape == CropImageView.CropShape.RECTANGLE) {
            canvas.drawRect(bitmapRect.left, bitmapRect.top, bitmapRect.right, t, mBackgroundPaint);
            canvas.drawRect(bitmapRect.left, b, bitmapRect.right, bitmapRect.bottom, mBackgroundPaint);
            canvas.drawRect(bitmapRect.left, t, l, b, mBackgroundPaint);
            canvas.drawRect(r, t, bitmapRect.right, b, mBackgroundPaint);
        } else {
            Path circleSelectionPath = new Path();
            if (Build.VERSION.SDK_INT >= 11 && Build.VERSION.SDK_INT <= 17 && mCropShape == CropImageView.CropShape.OVAL) {
                Defaults.EMPTY_RECT_F.set(l + 2, t + 2, r - 2, b - 2);
            } else {
                Defaults.EMPTY_RECT_F.set(l, t, r, b);
            }
            circleSelectionPath.addOval(Defaults.EMPTY_RECT_F, Path.Direction.CW);
            canvas.save();
            canvas.clipPath(circleSelectionPath, Region.Op.XOR);
            canvas.drawRect(bitmapRect.left, bitmapRect.top, bitmapRect.right, bitmapRect.bottom, mBackgroundPaint);
            canvas.restore();
        }
    }

    private void drawCorners(Canvas canvas) {

        float w = mBorderPaint.getStrokeWidth() * 1.5f + 1;
        float l = Edge.LEFT.getCoordinate() + w;
        float t = Edge.TOP.getCoordinate() + w;
        float r = Edge.RIGHT.getCoordinate() - w;
        float b = Edge.BOTTOM.getCoordinate() - w;

        // Top left        canvas.drawLine(l - mCornerOffset, t - mCornerExtension, l - mCornerOffset, t + mCornerLength, mCornerPaint);
        canvas.drawLine(l, t - mCornerOffset, l + mCornerLength, t - mCornerOffset, mCornerPaint);

        // Top right        canvas.drawLine(r + mCornerOffset, t - mCornerExtension, r + mCornerOffset, t + mCornerLength, mCornerPaint);
        canvas.drawLine(r, t - mCornerOffset, r - mCornerLength, t - mCornerOffset, mCornerPaint);

        // Bottom left        canvas.drawLine(l - mCornerOffset, b + mCornerExtension, l - mCornerOffset, b - mCornerLength, mCornerPaint);
        canvas.drawLine(l, b + mCornerOffset, l + mCornerLength, b + mCornerOffset, mCornerPaint);

        // Bottom left        canvas.drawLine(r + mCornerOffset, b + mCornerExtension, r + mCornerOffset, b - mCornerLength, mCornerPaint);
        canvas.drawLine(r, b + mCornerOffset, r - mCornerLength, b + mCornerOffset, mCornerPaint);
    }

    /**     * Handles a {@link MotionEvent#ACTION_DOWN} event.     *     * @param x the x-coordinate of the down action     * @param y the y-coordinate of the down action     */    private void onActionDown(float x, float y) {
        float left = Edge.LEFT.getCoordinate();
        float top = Edge.TOP.getCoordinate();
        float right = Edge.RIGHT.getCoordinate();
        float bottom = Edge.BOTTOM.getCoordinate();

        mPressedHandle = HandleUtil.getPressedHandle(x, y, left, top, right, bottom, mHandleRadius, mCropShape);
        if (mPressedHandle == null) {
            return;
        }

        // Calculate the offset of the touch point from the precise location        // of the handle. Save these values in a member variable since we want        // to maintain this offset as we drag the handle.        mTouchOffset = HandleUtil.getOffset(mPressedHandle, x, y, left, top, right, bottom);
        invalidate();
    }

    /**     * Handles a {@link MotionEvent#ACTION_UP} or     * {@link MotionEvent#ACTION_CANCEL} event.     */    private void onActionUp() {
        if (mPressedHandle == null) {
            return;
        }

        mPressedHandle = null;
        invalidate();
    }

    /**     * Handles a {@link MotionEvent#ACTION_MOVE} event.     *     * @param x the x-coordinate of the move event     * @param y the y-coordinate of the move event     */    private void onActionMove(float x, float y) {

        if (mPressedHandle == null) {
            return;
        }

        // Adjust the coordinates for the finger position's offset (i.e. the        // distance from the initial touch to the precise handle location).        // We want to maintain the initial touch's distance to the pressed        // handle so that the crop window size does not "jump".        x += mTouchOffset.first;
        y += mTouchOffset.second;

        // Calculate the new crop window size/position.        if (mFixAspectRatio) {
            mPressedHandle.updateCropWindow(x, y, mTargetAspectRatio, mBitmapRect, mSnapRadius);
        } else {
            mPressedHandle.updateCropWindow(x, y, mBitmapRect, mSnapRadius);
        }
        invalidate();
    }
    //endregion}

5)Defaults.java
=====================
// "Therefore those skilled at the unorthodox// are infinite as heaven and earth,// inexhaustible as the great rivers.// When they come to an end,// they begin again,// like the days and months;// they die and are reborn,// like the four seasons."//// - Sun Tsu,// "The Art of War"
package com.credencys.myapplication.widgets;

import android.graphics.Rect;
import android.graphics.RectF;
import android.widget.ImageView;

import com.credencys.myapplication.cropwindow.PaintUtil;

/** * Defaults used in the library. */class Defaults {

    public static final Rect EMPTY_RECT = new Rect();

    public static final RectF EMPTY_RECT_F = new RectF();

    // Sets the default image guidelines to show when resizing    public static final int DEFAULT_GUIDELINES = 1;

    public static final boolean DEFAULT_FIXED_ASPECT_RATIO = false;

    public static final int DEFAULT_ASPECT_RATIO_X = 1;

    public static final int DEFAULT_ASPECT_RATIO_Y = 1;

    public static final int DEFAULT_SCALE_TYPE_INDEX = 0;

    public static final int DEFAULT_CROP_SHAPE_INDEX = 0;

    public static final float SNAP_RADIUS_DP = 3;

    public static final float DEFAULT_SHOW_GUIDELINES_LIMIT = 100;

    // Gets default values from PaintUtil, sets a bunch of values such that the    // corners will draw correctly    public static final float DEFAULT_CORNER_THICKNESS_DP = PaintUtil.getCornerThickness();

    public static final float DEFAULT_LINE_THICKNESS_DP = PaintUtil.getLineThickness();

    public static final float DEFAULT_CORNER_OFFSET_DP = (DEFAULT_CORNER_THICKNESS_DP / 2) - (DEFAULT_LINE_THICKNESS_DP / 2);

    public static final float DEFAULT_CORNER_EXTENSION_DP = DEFAULT_CORNER_THICKNESS_DP / 2 + DEFAULT_CORNER_OFFSET_DP;

    public static final float DEFAULT_CORNER_LENGTH_DP = 15;

    public static final int GUIDELINES_ON_TOUCH = 1;

    public static final int GUIDELINES_ON = 2;

    public static final ImageView.ScaleType[] VALID_SCALE_TYPES = new ImageView.ScaleType[]{ImageView.ScaleType.CENTER_INSIDE, ImageView.ScaleType.FIT_CENTER};

    public static final CropImageView.CropShape[] VALID_CROP_SHAPES = new CropImageView.CropShape[]{CropImageView.CropShape.RECTANGLE, CropImageView.CropShape.OVAL};
}

6) ShapedImageView.java
=================================
package com.credencys.myapplication.widgets;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.drawable.shapes.Shape;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.credencys.myapplication.R;

import java.util.Arrays;

public class ShapedImageView extends ImageView {

    public static final int SHAPE_MODE_ROUND_RECT = 1;
    public static final int SHAPE_MODE_CIRCLE = 2;
    private static final int LAYER_FLAGS = Canvas.MATRIX_SAVE_FLAG | Canvas.CLIP_SAVE_FLAG | Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG;
    private int mShapeMode = 0;
    private float mRadius = 0;
    private int mStrokeColor = 0x26000000;
    private float mStrokeWidth = 0;
    private Path mPath;
    private Shape mShape, mStrokeShape;
    private Paint mPaint, mStrokePaint, mPathPaint;
    private Bitmap mStrokeBitmap;
    private PathExtension mExtension;

    public ShapedImageView(Context context) {
        super(context);
        init(null);
    }

    public ShapedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public ShapedImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            setLayerType(LAYER_TYPE_HARDWARE, null);
        }

        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ShapedImageView);
            mShapeMode = a.getInt(R.styleable.ShapedImageView_shape_mode, 2);
            mRadius = a.getDimension(R.styleable.ShapedImageView_round_radius, 0);

            mStrokeWidth = a.getDimension(R.styleable.ShapedImageView_stroke_width, 0);
            mStrokeColor = a.getColor(R.styleable.ShapedImageView_stroke_color, mStrokeColor);
            a.recycle();
        }
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setFilterBitmap(true);
        mPaint.setColor(Color.BLACK);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

        mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mStrokePaint.setFilterBitmap(true);
        mStrokePaint.setColor(mStrokeColor);

        mPathPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPathPaint.setFilterBitmap(true);
        mPathPaint.setColor(Color.BLACK);
        mPathPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.XOR));

        mPath = new Path();
    }

    @Override    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            switch (mShapeMode) {
                case SHAPE_MODE_ROUND_RECT:
                    break;

                case SHAPE_MODE_CIRCLE:
                    int min = Math.min(getWidth(), getHeight());
                    mRadius = (float) min / 2;
                    break;
            }

            if (mShape == null) {
                float[] radius = new float[8];
                Arrays.fill(radius, mRadius);
                mShape = new RoundRectShape(radius, null, null);
                mStrokeShape = new RoundRectShape(radius, null, null);
            }
            mShape.resize(getWidth(), getHeight());
            mStrokeShape.resize(getWidth() - mStrokeWidth * 2, getHeight() - mStrokeWidth * 2);

            if (mStrokeWidth > 0 && mStrokeBitmap == null) {
                mStrokeBitmap = makeStrokeBitmap(getWidth(), getHeight());
            }

            if (mExtension != null) {
                mExtension.onLayout(mPath, getWidth(), getHeight());
            }
        }
    }

    @Override    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mStrokeWidth > 0 && mStrokeShape != null && mStrokeBitmap != null) {
            int i = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, LAYER_FLAGS);
            mStrokePaint.setXfermode(null);
            canvas.drawBitmap(mStrokeBitmap, 0, 0, mStrokePaint);
            canvas.translate(mStrokeWidth, mStrokeWidth);
            mStrokePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
            mStrokeShape.draw(canvas, mStrokePaint);
            canvas.restoreToCount(i);
        }

        if (mExtension != null) {
            canvas.drawPath(mPath, mPathPaint);
        }

        switch (mShapeMode) {
            case SHAPE_MODE_ROUND_RECT:
            case SHAPE_MODE_CIRCLE:
                if (mShape != null) {
                    mShape.draw(canvas, mPaint);
                }
                break;
        }
    }

    @Override    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mStrokeWidth > 0 && mStrokeBitmap == null && mStrokeShape != null) {
            mStrokeBitmap = makeStrokeBitmap(getWidth(), getHeight());
        }
    }

    @Override    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mStrokeBitmap != null) {
            mStrokeBitmap.recycle();
            mStrokeBitmap = null;
        }
    }

    private Bitmap makeStrokeBitmap(int w, int h) {
        Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bm);
        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setColor(mStrokeColor);
        c.drawRect(new RectF(0, 0, w, h), p);
        return bm;
    }

    public void setExtension(PathExtension extension) {
        mExtension = extension;
        requestLayout();
    }

    public interface PathExtension {
        void onLayout(Path path, int width, int height);
    }

    public void setShapeMode(int shapeMode)
    {
        this.mShapeMode=shapeMode;
        invalidate();
    }


}

7) TouchImageView.java
============================
package com.credencys.myapplication.widgets;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.Scroller;

public class TouchImageView extends ImageView {

   private static final String DEBUG = "DEBUG";

   // SuperMin and SuperMax multipliers. Determine how much the image can be   // zoomed below or above the zoom boundaries, before animating back to the   // min/max zoom boundary.   //   private static final float SUPER_MIN_MULTIPLIER = .75f;
   private static final float SUPER_MAX_MULTIPLIER = 1.25f;

   // Scale of image ranges from minScale to maxScale, where minScale == 1   // when the image is stretched to fit view.   //   private float normalizedScale;

   // Matrix applied to image. MSCALE_X and MSCALE_Y should always be equal.   // MTRANS_X and MTRANS_Y are the other values used. prevMatrix is the matrix   // saved prior to the screen rotating.   //   private Matrix matrix, prevMatrix;

   public static enum State {
      NONE, DRAG, ZOOM, FLING, ANIMATE_ZOOM   };

   private State state;

   private float minScale;
   private float maxScale;
   private float superMinScale;
   private float superMaxScale;
   private float[] m;

   private Context context;
   private Fling fling;

   // Size of view and previous view size (ie before rotation)   private int viewWidth, viewHeight, prevViewWidth, prevViewHeight;

   // Size of image when it is stretched to fit view. Before and After   // rotation.   private float matchViewWidth, matchViewHeight, prevMatchViewWidth,
         prevMatchViewHeight;

   // After setting image, a value of true means the new image should maintain   // the zoom of the previous image. False means it should be resized within   // the view.   private boolean maintainZoomAfterSetImage;

   // True when maintainZoomAfterSetImage has been set to true and setImage has   // been called.   private boolean setImageCalledRecenterImage;

   private ScaleGestureDetector mScaleDetector;
   private GestureDetector mGestureDetector;

   public TouchImageView(Context context) {
      super(context);
      sharedConstructing(context);
   }

   public TouchImageView(Context context, AttributeSet attrs) {
      super(context, attrs);
      sharedConstructing(context);
   }

   public TouchImageView(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
      sharedConstructing(context);
   }

   private void sharedConstructing(Context context) {
      super.setClickable(true);
      this.context = context;
      mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
      mGestureDetector = new GestureDetector(context, new GestureListener());
      matrix = new Matrix();
      prevMatrix = new Matrix();
      m = new float[9];
      normalizedScale = 1;
      minScale = 1;
      maxScale = 3;
      superMinScale = SUPER_MIN_MULTIPLIER * minScale;
      superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
      maintainZoomAfterSetImage = true;
      setImageMatrix(matrix);
      setScaleType(ScaleType.MATRIX);
      setState(State.NONE);
      setOnTouchListener(new TouchImageViewListener());
   }

   public void enableZoom(boolean enable)
   {
      if(enable)
         setOnTouchListener(new TouchImageViewListener());
      else         setOnTouchListener(null);

   }

   @Override   public void setImageResource(int resId) {
      super.setImageResource(resId);
      setImageCalled();
      savePreviousImageValues();
      fitImageToView();
   }

   @Override   public void setImageBitmap(Bitmap bm) {
      super.setImageBitmap(bm);
      setImageCalled();
      savePreviousImageValues();
      fitImageToView();
   }

   @Override   public void setImageDrawable(Drawable drawable) {
      super.setImageDrawable(drawable);
      setImageCalled();
      savePreviousImageValues();
      fitImageToView();
   }

   @Override   public void setImageURI(Uri uri) {
      super.setImageURI(uri);
      setImageCalled();
      savePreviousImageValues();
      fitImageToView();
   }

   private void setImageCalled() {
      if (!maintainZoomAfterSetImage) {
         setImageCalledRecenterImage = true;
      }
   }

   /**    * Save the current matrix and view dimensions in the prevMatrix and    * prevView variables.    */   private void savePreviousImageValues() {
      if (matrix != null) {
         matrix.getValues(m);
         prevMatrix.setValues(m);
         prevMatchViewHeight = matchViewHeight;
         prevMatchViewWidth = matchViewWidth;
         prevViewHeight = viewHeight;
         prevViewWidth = viewWidth;
      }
   }

   @Override   public Parcelable onSaveInstanceState() {
      Bundle bundle = new Bundle();
      bundle.putParcelable("instanceState", super.onSaveInstanceState());
      bundle.putFloat("saveScale", normalizedScale);
      bundle.putFloat("matchViewHeight", matchViewHeight);
      bundle.putFloat("matchViewWidth", matchViewWidth);
      bundle.putInt("viewWidth", viewWidth);
      bundle.putInt("viewHeight", viewHeight);
      matrix.getValues(m);
      bundle.putFloatArray("matrix", m);
      return bundle;
   }

   @Override   public void onRestoreInstanceState(Parcelable state) {
      if (state instanceof Bundle) {
         Bundle bundle = (Bundle) state;
         normalizedScale = bundle.getFloat("saveScale");
         m = bundle.getFloatArray("matrix");
         prevMatrix.setValues(m);
         prevMatchViewHeight = bundle.getFloat("matchViewHeight");
         prevMatchViewWidth = bundle.getFloat("matchViewWidth");
         prevViewHeight = bundle.getInt("viewHeight");
         prevViewWidth = bundle.getInt("viewWidth");
         super.onRestoreInstanceState(bundle.getParcelable("instanceState"));
         return;
      }

      super.onRestoreInstanceState(state);
   }

   /**    * Get the max zoom multiplier.    *     * @return max zoom multiplier.    */   public float getMaxZoom() {
      return maxScale;
   }

   /**    * Set the max zoom multiplier. Default value: 3.    *     * @param max    *            max zoom multiplier.    */   public void setMaxZoom(float max) {
      maxScale = max;
      superMaxScale = SUPER_MAX_MULTIPLIER * maxScale;
   }

   /**    * Get the min zoom multiplier.    *     * @return min zoom multiplier.    */   public float getMinZoom() {
      return minScale;
   }

   /**    * After setting image, a value of true means the new image should maintain    * the zoom of the previous image. False means the image should be resized    * within the view. Defaults value is true.    *     * @param maintainZoom    */   public void maintainZoomAfterSetImage(boolean maintainZoom) {
      maintainZoomAfterSetImage = maintainZoom;
   }

   /**    * Get the current zoom. This is the zoom relative to the initial scale, not    * the original resource.    *     * @return current zoom multiplier.    */   public float getCurrentZoom() {
      return normalizedScale;
   }

   /**    * Set the min zoom multiplier. Default value: 1.    *     * @param min    *            min zoom multiplier.    */   public void setMinZoom(float min) {
      minScale = min;
      superMinScale = SUPER_MIN_MULTIPLIER * minScale;
   }

   /**    * For a given point on the view (ie, a touch event), returns the point    * relative to the original drawable's coordinate system.    *     * @param x    * @param y    * @return PointF relative to original drawable's coordinate system.    */   public PointF getDrawablePointFromTouchPoint(float x, float y) {
      return transformCoordTouchToBitmap(x, y, true);
   }

   /**    * For a given point on the view (ie, a touch event), returns the point    * relative to the original drawable's coordinate system.    *     * @param p    * @return PointF relative to original drawable's coordinate system.    */   public PointF getDrawablePointFromTouchPoint(PointF p) {
      return transformCoordTouchToBitmap(p.x, p.y, true);
   }

   /**    * Performs boundary checking and fixes the image matrix if it is out of    * bounds.    */   private void fixTrans() {
      matrix.getValues(m);
      float transX = m[Matrix.MTRANS_X];
      float transY = m[Matrix.MTRANS_Y];

      float fixTransX = getFixTrans(transX, viewWidth, getImageWidth());
      float fixTransY = getFixTrans(transY, viewHeight, getImageHeight());

      if (fixTransX != 0 || fixTransY != 0) {
         matrix.postTranslate(fixTransX, fixTransY);
      }
   }

   /**    * When transitioning from zooming from focus to zoom from center (or vice    * versa) the image can become unaligned within the view. This is apparent    * when zooming quickly. When the content size is less than the view size,    * the content will often be centered incorrectly within the view.    * fixScaleTrans first calls fixTrans() and then makes sure the image is    * centered correctly within the view.    */   private void fixScaleTrans() {
      fixTrans();
      matrix.getValues(m);
      if (getImageWidth() < viewWidth) {
         m[Matrix.MTRANS_X] = (viewWidth - getImageWidth()) / 2;
      }

      if (getImageHeight() < viewHeight) {
         m[Matrix.MTRANS_Y] = (viewHeight - getImageHeight()) / 2;
      }
      matrix.setValues(m);
   }

   private float getFixTrans(float trans, float viewSize, float contentSize) {
      float minTrans, maxTrans;

      if (contentSize <= viewSize) {
         minTrans = 0;
         maxTrans = viewSize - contentSize;

      } else {
         minTrans = viewSize - contentSize;
         maxTrans = 0;
      }

      if (trans < minTrans)
         return -trans + minTrans;
      if (trans > maxTrans)
         return -trans + maxTrans;
      return 0;
   }

   private float getFixDragTrans(float delta, float viewSize, float contentSize) {
      if (contentSize <= viewSize) {
         return 0;
      }
      return delta;
   }

   private float getImageWidth() {
      return matchViewWidth * normalizedScale;
   }

   private float getImageHeight() {
      return matchViewHeight * normalizedScale;
   }

   @Override   protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      Drawable drawable = getDrawable();
      if (drawable == null || drawable.getIntrinsicWidth() == 0            || drawable.getIntrinsicHeight() == 0) {
         setMeasuredDimension(0, 0);
         return;
      }

      int drawableWidth = drawable.getIntrinsicWidth();
      int drawableHeight = drawable.getIntrinsicHeight();
      int widthSize = MeasureSpec.getSize(widthMeasureSpec);
      int widthMode = MeasureSpec.getMode(widthMeasureSpec);
      int heightSize = MeasureSpec.getSize(heightMeasureSpec);
      int heightMode = MeasureSpec.getMode(heightMeasureSpec);
      viewWidth = setViewSize(widthMode, widthSize, drawableWidth);
      viewHeight = setViewSize(heightMode, heightSize, drawableHeight);

      //      // Set view dimensions      //      setMeasuredDimension(viewWidth, viewHeight);

      //      // Fit content within view      //      fitImageToView();
   }

   /**    * If the normalizedScale is equal to 1, then the image is made to fit the    * screen. Otherwise, it is made to fit the screen according to the    * dimensions of the previous image matrix. This allows the image to    * maintain its zoom after rotation.    */   private void fitImageToView() {
      Drawable drawable = getDrawable();
      if (drawable == null || drawable.getIntrinsicWidth() == 0            || drawable.getIntrinsicHeight() == 0) {
         return;
      }
      if (matrix == null || prevMatrix == null) {
         return;
      }

      int drawableWidth = drawable.getIntrinsicWidth();
      int drawableHeight = drawable.getIntrinsicHeight();

      //      // Scale image for view      //      float scaleX = (float) viewWidth / drawableWidth;
      float scaleY = (float) viewHeight / drawableHeight;
      float scale = Math.min(scaleX, scaleY);

      //      // Center the image      //      float redundantYSpace = viewHeight - (scale * drawableHeight);
      float redundantXSpace = viewWidth - (scale * drawableWidth);
      matchViewWidth = viewWidth - redundantXSpace;
      matchViewHeight = viewHeight - redundantYSpace;
      if (normalizedScale == 1 || setImageCalledRecenterImage) {
         //         // Stretch and center image to fit view         //         matrix.setScale(scale, scale);
         matrix.postTranslate(redundantXSpace / 2, redundantYSpace / 2);
         normalizedScale = 1;
         setImageCalledRecenterImage = false;

      } else {
         prevMatrix.getValues(m);

         //         // Rescale Matrix after rotation         //         m[Matrix.MSCALE_X] = matchViewWidth / drawableWidth
               * normalizedScale;
         m[Matrix.MSCALE_Y] = matchViewHeight / drawableHeight
               * normalizedScale;

         //         // TransX and TransY from previous matrix         //         float transX = m[Matrix.MTRANS_X];
         float transY = m[Matrix.MTRANS_Y];

         //         // Width         //         float prevActualWidth = prevMatchViewWidth * normalizedScale;
         float actualWidth = getImageWidth();
         translateMatrixAfterRotate(Matrix.MTRANS_X, transX,
               prevActualWidth, actualWidth, prevViewWidth, viewWidth,
               drawableWidth);

         //         // Height         //         float prevActualHeight = prevMatchViewHeight * normalizedScale;
         float actualHeight = getImageHeight();
         translateMatrixAfterRotate(Matrix.MTRANS_Y, transY,
               prevActualHeight, actualHeight, prevViewHeight, viewHeight,
               drawableHeight);

         // Set the matrix to the adjusted scale and translate values.         //         matrix.setValues(m);
      }
      setImageMatrix(matrix);
   }

   /**    * Set view dimensions based on layout params    *     * @param mode    * @param size    * @param drawableWidth    * @return    */   private int setViewSize(int mode, int size, int drawableWidth) {
      int viewSize;
      switch (mode) {
      case MeasureSpec.EXACTLY:
         viewSize = size;
         break;

      case MeasureSpec.AT_MOST:
         viewSize = Math.min(drawableWidth, size);
         break;

      case MeasureSpec.UNSPECIFIED:
         viewSize = drawableWidth;
         break;

      default:
         viewSize = size;
         break;
      }
      return viewSize;
   }

   /**    * After rotating, the matrix needs to be translated. This function finds    * the area of image which was previously centered and adjusts translations    * so that is again the center, post-rotation.    *     * @param axis    *            Matrix.MTRANS_X or Matrix.MTRANS_Y    * @param trans    *            the value of trans in that axis before the rotation    * @param prevImageSize    *            the width/height of the image before the rotation    * @param imageSize    *            width/height of the image after rotation    * @param prevViewSize    *            width/height of view before rotation    * @param viewSize    *            width/height of view after rotation    * @param drawableSize    *            width/height of drawable    */   private void translateMatrixAfterRotate(int axis, float trans,
         float prevImageSize, float imageSize, int prevViewSize,
         int viewSize, int drawableSize) {
      if (imageSize < viewSize) {
         //         // The width/height of image is less than the view's width/height.         // Center it.         //         m[axis] = (viewSize - (drawableSize * m[Matrix.MSCALE_X])) * 0.5f;

      } else if (trans > 0) {
         //         // The image is larger than the view, but was not before rotation.         // Center it.         //         m[axis] = -((imageSize - viewSize) * 0.5f);

      } else {
         //         // Find the area of the image which was previously centered in the         // view. Determine its distance         // from the left/top side of the view as a fraction of the entire         // image's width/height. Use that percentage         // to calculate the trans in the new view width/height.         //         float percentage = (Math.abs(trans) + (0.5f * prevViewSize))
               / prevImageSize;
         m[axis] = -((percentage * imageSize) - (viewSize * 0.5f));
      }
   }

   private void setState(State state) {
      this.state = state;
   }

   /**    * Gesture Listener detects a single click or long click and passes that on    * to the view's listener.    *     * @author Ortiz    *     */   private class GestureListener extends         GestureDetector.SimpleOnGestureListener {

      @Override      public boolean onSingleTapConfirmed(MotionEvent e) {
         return performClick();
      }

      @Override      public void onLongPress(MotionEvent e) {
         performLongClick();
      }

      @Override      public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
         if (fling != null) {
            //            // If a previous fling is still active, it should be cancelled            // so that two flings            // are not run simultaenously.            //            fling.cancelFling();
         }
         fling = new Fling((int) velocityX, (int) velocityY);
         compatPostOnAnimation(fling);
         return super.onFling(e1, e2, velocityX, velocityY);
      }

      @Override      public boolean onDoubleTap(MotionEvent e) {
         boolean consumed = false;
         if (state == State.NONE) {
            float targetZoom = (normalizedScale == minScale) ? maxScale                  : minScale;
            DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom,
                  e.getX(), e.getY(), false);
            compatPostOnAnimation(doubleTap);
            consumed = true;
         }
         return consumed;
      }
   }

   /**    * Responsible for all touch events. Handles the heavy lifting of drag and    * also sends touch events to Scale Detector and Gesture Detector.    *     * @author Ortiz    *     */   private class TouchImageViewListener implements OnTouchListener {

      //      // Remember last point position for dragging      //      private PointF last = new PointF();

      @Override      public boolean onTouch(View v, MotionEvent event) {
         mScaleDetector.onTouchEvent(event);
         mGestureDetector.onTouchEvent(event);
         PointF curr = new PointF(event.getX(), event.getY());

         if (state == State.NONE || state == State.DRAG || state == State.FLING) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
               last.set(curr);
               if (fling != null)
                  fling.cancelFling();
               setState(State.DRAG);
               break;

            case MotionEvent.ACTION_MOVE:
               if (state == State.DRAG) {
                  float deltaX = curr.x - last.x;
                  float deltaY = curr.y - last.y;
                  float fixTransX = getFixDragTrans(deltaX, viewWidth,
                        getImageWidth());
                  float fixTransY = getFixDragTrans(deltaY, viewHeight,
                        getImageHeight());
                  matrix.postTranslate(fixTransX, fixTransY);
                  fixTrans();
                  last.set(curr.x, curr.y);
               }
               break;

            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
               setState(State.NONE);
               break;
            }
         }

         setImageMatrix(matrix);
         //         // indicate event was handled         //         return true;
      }
   }

   /**    * ScaleListener detects user two finger scaling and scales image.    *     * @author Ortiz    *     */   private class ScaleListener extends         ScaleGestureDetector.SimpleOnScaleGestureListener {
      @Override      public boolean onScaleBegin(ScaleGestureDetector detector) {
         setState(State.ZOOM);
         return true;
      }

      @Override      public boolean onScale(ScaleGestureDetector detector) {
         scaleImage(detector.getScaleFactor(), detector.getFocusX(),
               detector.getFocusY(), true);
         return true;
      }

      @Override      public void onScaleEnd(ScaleGestureDetector detector) {
         super.onScaleEnd(detector);
         setState(State.NONE);
         boolean animateToZoomBoundary = false;
         float targetZoom = normalizedScale;
         if (normalizedScale > maxScale) {
            targetZoom = maxScale;
            animateToZoomBoundary = true;

         } else if (normalizedScale < minScale) {
            targetZoom = minScale;
            animateToZoomBoundary = true;
         }

         if (animateToZoomBoundary) {
            DoubleTapZoom doubleTap = new DoubleTapZoom(targetZoom,
                  viewWidth / 2, viewHeight / 2, true);
            compatPostOnAnimation(doubleTap);
         }
      }
   }

   private void scaleImage(float deltaScale, float focusX, float focusY,
         boolean stretchImageToSuper) {

      float lowerScale, upperScale;
      if (stretchImageToSuper) {
         lowerScale = superMinScale;
         upperScale = superMaxScale;

      } else {
         lowerScale = minScale;
         upperScale = maxScale;
      }

      float origScale = normalizedScale;
      normalizedScale *= deltaScale;
      if (normalizedScale > upperScale) {
         normalizedScale = upperScale;
         deltaScale = upperScale / origScale;
      } else if (normalizedScale < lowerScale) {
         normalizedScale = lowerScale;
         deltaScale = lowerScale / origScale;
      }

      matrix.postScale(deltaScale, deltaScale, focusX, focusY);
      fixScaleTrans();
   }

   /**    * DoubleTapZoom calls a series of runnables which apply an animated zoom    * in/out graphic to the image.    *     * @author Ortiz    *     */   private class DoubleTapZoom implements Runnable {

      private long startTime;
      private static final float ZOOM_TIME = 500;
      private float startZoom, targetZoom;
      private float bitmapX, bitmapY;
      private boolean stretchImageToSuper;
      private AccelerateDecelerateInterpolator interpolator = new AccelerateDecelerateInterpolator();
      private PointF startTouch;
      private PointF endTouch;

      DoubleTapZoom(float targetZoom, float focusX, float focusY,
            boolean stretchImageToSuper) {
         setState(State.ANIMATE_ZOOM);
         startTime = System.currentTimeMillis();
         this.startZoom = normalizedScale;
         this.targetZoom = targetZoom;
         this.stretchImageToSuper = stretchImageToSuper;
         PointF bitmapPoint = transformCoordTouchToBitmap(focusX, focusY,
               false);
         this.bitmapX = bitmapPoint.x;
         this.bitmapY = bitmapPoint.y;

         //         // Used for translating image during scaling         //         startTouch = transformCoordBitmapToTouch(bitmapX, bitmapY);
         endTouch = new PointF(viewWidth / 2, viewHeight / 2);
      }

      @Override      public void run() {
         float t = interpolate();
         float deltaScale = calculateDeltaScale(t);
         scaleImage(deltaScale, bitmapX, bitmapY, stretchImageToSuper);
         translateImageToCenterTouchPosition(t);
         fixScaleTrans();
         setImageMatrix(matrix);

         if (t < 1f) {
            //            // We haven't finished zooming            //            compatPostOnAnimation(this);

         } else {
            //            // Finished zooming            //            setState(State.NONE);
         }
      }

      /**       * Interpolate between where the image should start and end in order to       * translate the image so that the point that is touched is what ends up       * centered at the end of the zoom.       *        * @param t       */      private void translateImageToCenterTouchPosition(float t) {
         float targetX = startTouch.x + t * (endTouch.x - startTouch.x);
         float targetY = startTouch.y + t * (endTouch.y - startTouch.y);
         PointF curr = transformCoordBitmapToTouch(bitmapX, bitmapY);
         matrix.postTranslate(targetX - curr.x, targetY - curr.y);
      }

      /**       * Use interpolator to get t       *        * @return       */      private float interpolate() {
         long currTime = System.currentTimeMillis();
         float elapsed = (currTime - startTime) / ZOOM_TIME;
         elapsed = Math.min(1f, elapsed);
         return interpolator.getInterpolation(elapsed);
      }

      /**       * Interpolate the current targeted zoom and get the delta from the       * current zoom.       *        * @param t       * @return       */      private float calculateDeltaScale(float t) {
         float zoom = startZoom + t * (targetZoom - startZoom);
         return zoom / normalizedScale;
      }
   }

   /**    * This function will transform the coordinates in the touch event to the    * coordinate system of the drawable that the imageview contain    *     * @param x    *            x-coordinate of touch event    * @param y    *            y-coordinate of touch event    * @param clipToBitmap    *            Touch event may occur within view, but outside image content.    *            True, to clip return value to the bounds of the bitmap size.    * @return Coordinates of the point touched, in the coordinate system of the    *         original drawable.    */   private PointF transformCoordTouchToBitmap(float x, float y,
         boolean clipToBitmap) {
      matrix.getValues(m);
      float origW = getDrawable().getIntrinsicWidth();
      float origH = getDrawable().getIntrinsicHeight();
      float transX = m[Matrix.MTRANS_X];
      float transY = m[Matrix.MTRANS_Y];
      float finalX = ((x - transX) * origW) / getImageWidth();
      float finalY = ((y - transY) * origH) / getImageHeight();

      if (clipToBitmap) {
         finalX = Math.min(Math.max(x, 0), origW);
         finalY = Math.min(Math.max(y, 0), origH);
      }

      return new PointF(finalX, finalY);
   }

   /**    * Inverse of transformCoordTouchToBitmap. This function will transform the    * coordinates in the drawable's coordinate system to the view's coordinate    * system.    *     * @param bx    *            x-coordinate in original bitmap coordinate system    * @param by    *            y-coordinate in original bitmap coordinate system    * @return Coordinates of the point in the view's coordinate system.    */   private PointF transformCoordBitmapToTouch(float bx, float by) {
      matrix.getValues(m);
      float origW = getDrawable().getIntrinsicWidth();
      float origH = getDrawable().getIntrinsicHeight();
      float px = bx / origW;
      float py = by / origH;
      float finalX = m[Matrix.MTRANS_X] + getImageWidth() * px;
      float finalY = m[Matrix.MTRANS_Y] + getImageHeight() * py;
      return new PointF(finalX, finalY);
   }

   /**    * Fling launches sequential runnables which apply the fling graphic to the    * image. The values for the translation are interpolated by the Scroller.    *     * @author Ortiz    *     */   private class Fling implements Runnable {

      Scroller scroller;
      int currX, currY;

      Fling(int velocityX, int velocityY) {
         setState(State.FLING);
         scroller = new Scroller(context);
         matrix.getValues(m);

         int startX = (int) m[Matrix.MTRANS_X];
         int startY = (int) m[Matrix.MTRANS_Y];
         int minX, maxX, minY, maxY;

         if (getImageWidth() > viewWidth) {
            minX = viewWidth - (int) getImageWidth();
            maxX = 0;

         } else {
            minX = maxX = startX;
         }

         if (getImageHeight() > viewHeight) {
            minY = viewHeight - (int) getImageHeight();
            maxY = 0;

         } else {
            minY = maxY = startY;
         }

         scroller.fling(startX, startY, (int) velocityX, (int) velocityY,
               minX, maxX, minY, maxY);
         currX = startX;
         currY = startY;
      }

      public void cancelFling() {
         if (scroller != null) {
            setState(State.NONE);
            scroller.forceFinished(true);
         }
      }

      @Override      public void run() {
         if (scroller.isFinished()) {
            scroller = null;
            return;
         }

         if (scroller.computeScrollOffset()) {
            int newX = scroller.getCurrX();
            int newY = scroller.getCurrY();
            int transX = newX - currX;
            int transY = newY - currY;
            currX = newX;
            currY = newY;
            matrix.postTranslate(transX, transY);
            fixTrans();
            setImageMatrix(matrix);
            compatPostOnAnimation(this);
         }
      }
   }

   @TargetApi(VERSION_CODES.JELLY_BEAN)
   private void compatPostOnAnimation(Runnable runnable) {
      if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
         postOnAnimation(runnable);

      } else {
         postDelayed(runnable, 1000 / 60);
      }
   }

   private void printMatrixInfo() {
      matrix.getValues(m);
      Log.d(DEBUG, "Scale: " + m[Matrix.MSCALE_X] + " TransX: "            + m[Matrix.MTRANS_X] + " TransY: " + m[Matrix.MTRANS_Y]);
   }
}


MyApplication.java
==============================
package com.credencys.myapplication;

import android.app.Application;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.preference.PreferenceManager;

import com.credencys.myapplication.api.RestClient;
import com.credencys.myapplication.database.DbHelper;

import java.util.Locale;

/** * Created by manisha on 12/12/16. */
public class MyApplication extends Application{
    public static SharedPreferences myPref;
    public static boolean DISABLE_FRAGMENT_ANIMATION=false;
    RestClient restClient;
    DbHelper dbHelper;

    @Override    public void onCreate() {
        super.onCreate();

        // Initialize preference at application level        myPref = PreferenceManager.getDefaultSharedPreferences(this);

         // Initialize RestClient API class        restClient = new RestClient(this);

        //  Initialize DbHelper class and open database        dbHelper = new DbHelper(this);
        dbHelper.openDatabase();
    }

    public RestClient getRestClient()
    {
        return restClient;
    }

    public DbHelper getDbInstance(){
        return dbHelper;
    }

    @Override    public void onTerminate() {
        super.onTerminate();
        dbHelper.closeDataBase();
    }
}

No comments:

Post a Comment