@Module
public class NetModule {

    //get retrofit instance
    @Singleton
    @Provides
    public RestService getRestService() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(getOkHttpClient())
                .build();

        return retrofit.create(RestService.class);
    }

    //get OkHttp instance
    @Singleton
    @Provides
    public OkHttpClient getOkHttpClient() {

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.interceptors().add(httpLoggingInterceptor);
        builder.readTimeout(60, TimeUnit.SECONDS);
        builder.connectTimeout(60, TimeUnit.SECONDS);
        return builder.build();
    }
} public interface RestService {

    //LOGIN API
    @POST(ApiConstants.LOGIN)
    Observable<LoginResponse> login(@Body LoginRequest loginRequest);

} public interface ApiConstants {
    int STATUS_SUCCESS = 200;
    String STATUS_SESSION_EXPIRE = "203";
    String BASE_URL = "http://abc.com/";
    String CONTROLLER = "/index.php/webController";
    String LOGIN = CONTROLLER + "/apilogin";

} public interface ValueConstants {

    String LOCATION_PERMISSION = android.Manifest.permission.ACCESS_FINE_LOCATION;
    int REQUEST_CAMERA = 1001;
    int REQUEST_Gallery = 1002;
    int REQUEST_LOCATION = 1003;
    String DEVICE_TYPE = "android";
    String NEW_THREAD = "newThread";
    String MAIN_THREAD = "mainThread";
    String DATE_INPUT_FORMAT = "yyyy-MM-dd HH:mm:ss";
    String DATE_OUTPUT_FORMAT = "EEEE, h:mm a";

    // type check for error during login
    @IntDef({ValidationType.VALID, ValidationType.USER_NAME_INVALID, ValidationType.PASSWORD_INVALID})
    @Retention(RetentionPolicy.SOURCE)
    @interface ValidationType {
        int VALID = 0, USER_NAME_INVALID = 1, PASSWORD_INVALID = 2;
    }

    // type of dialog opened in MainActivity
    @IntDef({DialogType.DIALOG_DENY, DialogType.DIALOG_NEVER_ASK})
    @Retention(RetentionPolicy.SOURCE)
    @interface DialogType {
        int DIALOG_DENY = 0, DIALOG_NEVER_ASK = 1;
    }
} public class LoginRequest {

    String username;
    String password;
    String platform;
    String deviceid;

    public LoginRequest(@NonNull String username, @NonNull String password,
                        @NonNull String platform, @NonNull String deviceid) {
        this.username = username;
        this.password = password;
        this.platform = platform;
        this.deviceid = deviceid;
    }
} public class LoginResponse {
    /**
     * result : 1
     * resultText : Success
     * errorMSG : Success.
     * user_id : 20
     * phone : 1234567890
     * first_name : saveen
     * last_name : null
     * email : saveendhiman@gmail.com
     * role : 1
     * avatar :
     */

    private ResponseBean Response;

    public ResponseBean getResponse() {
        return Response;
    }

    public void setResponse(ResponseBean Response) {
        this.Response = Response;
    }

    public static class ResponseBean {
        private int result;
        private String resultText;
        private String errorMSG;
        private int user_id;
        private String phone;
        private String first_name;
        private Object last_name;
        private String email;
        private int role;
        private String avatar;

        public int getResult() {
            return result;
        }

        public void setResult(int result) {
            this.result = result;
        }

        public String getResultText() {
            return resultText;
        }

        public void setResultText(String resultText) {
            this.resultText = resultText;
        }

        public String getErrorMSG() {
            return errorMSG;
        }

        public void setErrorMSG(String errorMSG) {
            this.errorMSG = errorMSG;
        }

        public int getUser_id() {
            return user_id;
        }

        public void setUser_id(int user_id) {
            this.user_id = user_id;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getFirst_name() {
            return first_name;
        }

        public void setFirst_name(String first_name) {
            this.first_name = first_name;
        }

        public Object getLast_name() {
            return last_name;
        }

        public void setLast_name(Object last_name) {
            this.last_name = last_name;
        }

        public String getEmail() {
            return email;
        }

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

        public int getRole() {
            return role;
        }

        public void setRole(int role) {
            this.role = role;
        }

        public String getAvatar() {
            return avatar;
        }

        public void setAvatar(String avatar) {
            this.avatar = avatar;
        }
    }
} public class BasePresenter<T extends MvpView> implements Presenter<T> {

    private T mMvpView;

    @Override
    public void attachView(T mvpView) {
        mMvpView = mvpView;
    }

    @Override
    public void detachView() {
        mMvpView = null;
    }

    public boolean isViewAttached() {
        return mMvpView != null;
    }

    public T getMvpView() {
        return mMvpView;
    }

    public void checkViewAttached() {
        if (!isViewAttached()) throw new MvpViewNotAttachedException();
    }

    public static class MvpViewNotAttachedException extends RuntimeException {
        public MvpViewNotAttachedException() {
            super("Please call Presenter.attachView(MvpView) before" +
                    " requesting data to the Presenter");
        }
    }
} public class AppUtils {

    private Context mContext;

    public AppUtils(Context context) {
        this.mContext = context;
    }

    /**
     * Description : Check if user is online or not
     *
     * @return true if online else false
     */
    public boolean isOnline(View v) {
        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        showSnackBar(v, mContext.getString(R.string.toast_network_not_available));
        return false;
    }


    /**
     * Description : Hide the soft keyboard
     *
     * @param view : Pass the current view
     */
    public void hideSoftKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * Show snackbar
     *
     * @param view view clicked
     * @param text text to be displayed on snackbar
     */
    public void showSnackBar(View view, String text) {
//        Snackbar.make(view, text, Snackbar.LENGTH_SHORT).show();
    }

    /**
     * Show snackbar
     *
     * @param text text to be displayed on Toast
     */
    public void showToast(String text) {
        Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * send email via. intent
     *
     * @param email to whom you want to send email
     */
    public void sendEmail(Context context, String email) {
        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_EMAIL, email);
        try {
            context.startActivity(Intent.createChooser(i, context.getResources().getString(R.string.send_mail)));
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(context, context.getResources().getString(R.string.no_email_client), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * To open a website in phone browser
     *
     * @param address valid email link
     */
    public void openBrowser(String address) {
        try {
            if (!address.startsWith("http://") && !address.startsWith("https://")) {
                address = "http://" + address;
            }
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(address));
            mContext.startActivity(browserIntent);
        } catch (Exception e) {
            showToast(mContext.getResources().getString(R.string.warning_invalid_link));
        }
    }

    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    public boolean checkPlayServices() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(mContext);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog((Activity) mContext, resultCode, 9000)
                        .show();
            } else {
                showToast(mContext.getResources().getString(R.string.warning_play_services));
            }
            return false;
        }
        return true;
    }

    /**
     * redirect user to your application settings in device
     */
    public void redirectToAppSettings() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", mContext.getPackageName(), null);
        intent.setData(uri);
        mContext.startActivity(intent);
    }

    /**
     * check if user has enabled Gps of device
     *
     * @return true or false depending upon device Gps status
     */
    public boolean isGpsEnabled() {
        final LocationManager manager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * Redirect user to enable GPS
     */
    public void goToGpsSettings() {
        Intent callGPSSettingIntent = new Intent(
                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        mContext.startActivity(callGPSSettingIntent);
    }

} public class PreferenceManager {

    private static Context context1;

    public PreferenceManager(Context context) {
        PreferenceManager.context1 = context;
    }

    //get shared pref
    private SharedPreferences getPreferences() {
        return context1.getSharedPreferences(PrefernceConstants.PREFERENCE_NAME, Context.MODE_PRIVATE);
    }


    //save data of current logged in user
    public void setUserData(String userData) {
        getPreferences().edit().putString(PrefernceConstants.USER_DATA, userData).commit();
    }

    //get user data as string
    private String getUserDataFromPref() {
        return getPreferences().getString(PrefernceConstants.USER_DATA, null);
    }

    //get saved data of current user as an object
    public UserData.ResponseBean.AuthBean getUserData() {
        UserData.ResponseBean.AuthBean userData = null;
        if (getUserDataFromPref() != null) {
            userData = new Gson().fromJson(getUserDataFromPref(), UserData.ResponseBean.AuthBean.class);
        }
        return userData;
    }

    //returns true when user is logged in
    public void setUserLoggedIn(boolean isLogin) {
        getPreferences().edit().putBoolean(PrefernceConstants.IS_LOGIN, isLogin).commit();
    }

    //set true when user is logegd in else false
    public boolean isUserLoggedIn() {
        return getPreferences().getBoolean(PrefernceConstants.IS_LOGIN, false);
    }

    //clear user shared preferences
    public void clearPrefrences() {
        getPreferences().edit().clear().commit();
    }

} @Module
public class UtilsModule {

    private Context mContext;

    public UtilsModule(Context context) {
        this.mContext = context;
    }

    // get AppUtils instance
    @Provides
    @Singleton
    public AppUtils getAppUtils() {
        return new AppUtils(mContext);
    }

    // get DateTimeUtils instance
    @Provides
    @Singleton
    public DateTimeUtils getDateTimeUtils() {
        return new DateTimeUtils();
    }

    // get ProgressBarHandler instance
    @Provides
    @Singleton
    public ProgressBarHandler getProgressBar() {
        return new ProgressBarHandler(mContext);
    }

    //get dialog utils
    @Provides
    @Singleton
    public DialogsUtil getDialogUtils() {
        return new DialogsUtil(mContext);
    }

    //get new thread
    @Provides
    @Singleton
    @Named(ValueConstants.NEW_THREAD)
    public Scheduler getNewThread() {
        return Schedulers.io();
    }

    //get main thread
    @Provides
    @Singleton
    @Named(ValueConstants.MAIN_THREAD)
    public Scheduler getMainThread() {
        return AndroidSchedulers.mainThread();
    }

    //get Preference Manager
    @Provides
    @Singleton
    public PreferenceManager getPreferences() {
        return new PreferenceManager(mContext);
    }

    //get Fragment utils
    @Provides
    @Singleton
    public FragmentUtils getFragUtils() {
        return new FragmentUtils();
    }

    //get location helper methods
    @Provides
    @Singleton
    public LocationHelper getLocationUtils() {
        return new LocationHelper(mContext);
    }

    //get location tracker
    @Provides
    @Singleton
    public LocationTracker getLocationTrackerOF() {
        return new LocationTracker(mContext);
    }

    //get image utils
    @Provides
    @Singleton
    public ImageUtility getImageUtils() {
        return new ImageUtility(mContext);
    }

}
import android.content.Context;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.gson.Gson;
import com.sampleapp.api.NetModule;
import com.sampleapp.api.RestService;
import com.sampleapp.constants.ApiConstants;
import com.sampleapp.constants.ValueConstants;
import com.sampleapp.model.request.LoginRequest;
import com.sampleapp.model.response.LoginResponse;
import com.sampleapp.mvpbase.BasePresenter;
import com.sampleapp.utils.AppUtils;
import com.sampleapp.utils.PreferenceManager;
import com.sampleapp.utils.UtilsModule;
import javax.inject.Inject;
import javax.inject.Named;
import rx.Scheduler;
package com.sampleapp.module.login;





/**
 * Created by saveen_dhiman on 05-November-16.
 * Presenter class for LoginActivity
 * Contains all the business logic for main activity
 */
public class LoginPresenter extends BasePresenter<LoginView> {

    @Inject
    @Named(ValueConstants.MAIN_THREAD)
    Scheduler mMainThread;

    @Inject
    @Named(ValueConstants.NEW_THREAD)
    Scheduler mNewThread;

    @Inject
    RestService mRestService;

    @Inject
    PreferenceManager mprefs;

    @Inject
    AppUtils mUtils;

    public LoginPresenter(Context context) {
        //create component
        DaggerLoginPresenterComponent.builder()
                .netModule(new NetModule())
                .utilsModule(new UtilsModule(context)).build().inject(this);
    }

    //login user api method
    public void loginUser(String userName, String password) {

        getMvpView().showProgress();

        LoginRequest request = new LoginRequest(userName, password,
                ValueConstants.DEVICE_TYPE, FirebaseInstanceId.getInstance().getToken());

        mRestService.login(request).
                subscribeOn(mNewThread).
                observeOn(mMainThread).
                subscribe(loginResponse -> {
                    if (isViewAttached()) {
                        getMvpView().hideProgress();
                        if (loginResponse.getResponse().getResult() == ApiConstants.STATUS_SUCCESS) {
                            mprefs.setUserLoggedIn(true);
                            LoginResponse.ResponseBean response = loginResponse.getResponse();