com.openarc.nirmal.nestle.LoginActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.openarc.nirmal.nestle.LoginActivity.java

Source

/*
 * </summary>
 * Source File   : LoginActivity.java
 * Project      : Nestle
 * Owner      : nirmal
 * </summary>
 *
 * <license>
 * Copyright 2016 Kasun Gunathilaka
 *
 * 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.
 * </license>
 */

package com.openarc.nirmal.nestle;

//region Imported

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.openarc.nirmal.nestle.business.ChangeRequestBusiness;
import com.openarc.nirmal.nestle.business.CoolerInspectionBusiness;
import com.openarc.nirmal.nestle.business.GalleryBusiness;
import com.openarc.nirmal.nestle.business.InspectionBusiness;
import com.openarc.nirmal.nestle.business.OutletBusiness;
import com.openarc.nirmal.nestle.business.ProductBusiness;
import com.openarc.nirmal.nestle.business.ProductInspectionBusiness;
import com.openarc.nirmal.nestle.business.RouteBusiness;
import com.openarc.nirmal.nestle.business.ScheduleBusiness;
import com.openarc.nirmal.nestle.domain.User;
import com.openarc.nirmal.nestle.service.DataDownloadService;
import com.openarc.nirmal.nestle.utils.BroadcastManagerName;
import com.openarc.nirmal.nestle.utils.Session;
import com.openarc.nirmal.nestle.utils.SharedPreferencesName;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpHeaders;
import cz.msebera.android.httpclient.entity.StringEntity;
//endregion

public class LoginActivity extends AppCompatActivity {

    //region Private View Members
    Button bLogin;
    EditText etPassword;
    TextView tvPb;
    AutoCompleteTextView actvUserName;
    TextInputLayout tilUserName, tilPassword;
    RelativeLayout rlLogin, rlPb;
    CheckBox cbLoginRemember;
    AlertDialog noDataAlertDialog;
    int loginUserType;
    //endregion

    //region Private Members
    Session session;
    SharedPreferences sharedPreferences;
    BroadcastReceiver broadcastReceiver;
    //endregion

    //region Private Static Members
    private static int SAME_USER = 1;
    private static int SAME_USER_NEXT_DAY = 2;
    private static int DIFFERENT_USER_SAME_DATE = 3;
    private static int UNKNOWN_USER = 4;
    //endregion

    //region Overridden Methods
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        session = Session.getSession();
        sharedPreferences = getSharedPreferences(SharedPreferencesName.login, 0);
        initialize();

        //region broadcastReceiver
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                switch (intent.getAction()) {
                case "NoData":
                    if (isRunning()) {
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LoginActivity.this,
                                R.style.AlertDialogStyle);
                        alertDialogBuilder.setMessage(getString(R.string.message_no_data));
                        alertDialogBuilder.setPositiveButton(getString(R.string.btn_txt_ok),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        showProgressBar(false);
                                    }
                                });
                        noDataAlertDialog = alertDialogBuilder.create();
                        noDataAlertDialog.show();
                        setDownloadStatus(false);
                    }
                    break;
                case "DownloadFailed":
                    if (isRunning()) {
                        Toast.makeText(LoginActivity.this, "Data Download Failed!", Toast.LENGTH_SHORT).show();
                        setDownloadStatus(false);
                        showProgressBar(false);
                    }
                    break;
                case "DownloadInterrupted":
                    setDownloadStatus(false);
                    startHomeActivity();
                    break;
                case "DownloadFinished":
                    if (isRunning()) {
                        setDownloadStatus(true);
                        startHomeActivity();
                    }
                    break;
                default:
                    showProgressBar(false);
                    break;
                }

            }
        };
        //endregion

        if (sharedPreferences.getBoolean(SharedPreferencesName.autoLogin, false))
            this.automaticLogin();
    }

    @Override
    public void onBackPressed() {
        if (noDataAlertDialog != null && noDataAlertDialog.isShowing()) {
            noDataAlertDialog.dismiss();
            showProgressBar(false);
        } else if (isRunning()) {
            stopService(new Intent(LoginActivity.this, DataDownloadService.class));
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        LocalBroadcastManager.getInstance(LoginActivity.this).registerReceiver((broadcastReceiver),
                new IntentFilter(BroadcastManagerName.downloadFinished));
        LocalBroadcastManager.getInstance(LoginActivity.this).registerReceiver((broadcastReceiver),
                new IntentFilter(BroadcastManagerName.downloadInterrupted));
        LocalBroadcastManager.getInstance(LoginActivity.this).registerReceiver((broadcastReceiver),
                new IntentFilter(BroadcastManagerName.downloadFailed));
        LocalBroadcastManager.getInstance(LoginActivity.this).registerReceiver((broadcastReceiver),
                new IntentFilter(BroadcastManagerName.noData));
    }

    @Override
    protected void onStop() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
        super.onStop();
    }
    //endregion

    //region OnClick Methods
    View.OnClickListener bLogin_OnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //region Onclick
            if (getCurrentFocus() != null) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
            }

            if (validate()) {
                try {
                    hasInternet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //endregion
        }
    };
    //endregion

    //region Private Methods
    private void initialize() {
        bLogin = (Button) findViewById(R.id.bLogin);
        actvUserName = (AutoCompleteTextView) findViewById(R.id.actvUserName);
        etPassword = (EditText) findViewById(R.id.etPassword);
        tilUserName = (TextInputLayout) findViewById(R.id.tilUserName);
        tilPassword = (TextInputLayout) findViewById(R.id.tilPassword);
        cbLoginRemember = (CheckBox) findViewById(R.id.cbLoginRemember);

        rlPb = (RelativeLayout) findViewById(R.id.rlPb);
        tvPb = (TextView) findViewById(R.id.tvPb);

        rlLogin = (RelativeLayout) findViewById(R.id.rlLogin);

        actvUserName.clearFocus();

        bLogin.setOnClickListener(bLogin_OnClick);
        actvUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.length() < 1) {
                    tilUserName.setErrorEnabled(true);
                    tilUserName.setError("Enter User Name");
                } else if (s.length() > 0) {
                    if (tilUserName.getError() != "")
                        tilUserName.setError(null);
                    tilUserName.invalidate();
                    tilUserName.setErrorEnabled(false);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() < 1) {
                    tilPassword.setErrorEnabled(true);
                    tilPassword.setError("Enter Password");
                } else if (s.length() > 0) {
                    if (tilPassword.getError() != "")
                        tilPassword.setErrorEnabled(false);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private boolean validate() {
        if (TextUtils.isEmpty(actvUserName.getText().toString())) {
            tilUserName.setError("User Name cannot be empty");
            return false;
        } else if (TextUtils.isEmpty(etPassword.getText().toString())) {
            tilPassword.setError("Password cannot be empty");
            return false;
        } else {
            return true;
        }
    }

    private void showProgressBar(Boolean show) {
        rlPb.setVisibility(show ? View.VISIBLE : View.GONE);
        tvPb.setText("Logging in. Please wait..");
        rlLogin.setVisibility(show ? View.GONE : View.VISIBLE);
    }

    private void getTokenUser(String token) {
        try {
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.addHeader(HttpHeaders.AUTHORIZATION, "bearer " + token);
            asyncHttpClient.get(LoginActivity.this,
                    "http://openarc-rad-pradeepc9.c9users.io/cola_app/public/api/v1/authenticate/user",
                    new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                            try {
                                JSONObject jsonObject = new JSONObject(new String(responseBody))
                                        .getJSONObject("user");
                                if (setSessionUser(jsonObject)) {
                                    switch (loginUserType) {
                                    case 1:
                                        if (!getDownloadStatus()) {
                                            initiateServerDownload();
                                        } else {
                                            startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                                            finish();
                                        }
                                        break;
                                    default:
                                        initiateServerDownload();
                                        break;
                                    }

                                } else {
                                    showProgressBar(false);
                                    Toast.makeText(LoginActivity.this, "Error occurred, Contact Developer",
                                            Toast.LENGTH_SHORT).show();
                                }

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

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
                                Throwable error) {
                            showProgressBar(false);
                            switch (statusCode) {
                            case 404:
                                Toast.makeText(LoginActivity.this, "Server not Found", Toast.LENGTH_SHORT).show();
                                break;
                            case 500:
                                Toast.makeText(LoginActivity.this, "Server Error", Toast.LENGTH_SHORT).show();
                                break;
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void login(final String username, final String password) {
        try {
            showProgressBar(true);
            JSONObject jSONObject = new JSONObject();
            jSONObject.put("username", username);
            jSONObject.put("password", password);
            StringEntity stringEntity = new StringEntity(jSONObject.toString());
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.post(LoginActivity.this,
                    "http://openarc-rad-pradeepc9.c9users.io/cola_app/public/api/v1/authenticate", stringEntity,
                    "application/json", new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                            try {
                                if (cbLoginRemember.isChecked()) {
                                    setLoginCredential(username, password);
                                }

                                loginUserType = getLoginUserType(username);
                                setLastLoginUserAndDate(username);
                                JSONObject jsonObject = new JSONObject(new String(responseBody));
                                session.setToken(jsonObject.getString("token"));
                                getTokenUser(jsonObject.getString("token"));

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

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody,
                                Throwable error) {
                            showProgressBar(false);
                            switch (statusCode) {
                            case 401:
                                tilUserName.setError("User Name not correct");
                                tilPassword.setError("Password not correct");
                                tilUserName.requestFocus();
                                InputMethodManager imm = (InputMethodManager) getSystemService(
                                        Context.INPUT_METHOD_SERVICE);
                                imm.showSoftInput(tilUserName, 0);
                                break;
                            case 404:
                                Toast.makeText(LoginActivity.this, "Server not Found", Toast.LENGTH_SHORT).show();
                                break;
                            case 500:
                                Toast.makeText(LoginActivity.this, "Server Error", Toast.LENGTH_SHORT).show();
                                break;
                            case 503:
                                Toast.makeText(LoginActivity.this, "Server Offline", Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
                                break;

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

    private boolean setSessionUser(JSONObject jsonObject) {
        User currentUser = new User();
        try {
            currentUser.setId(jsonObject.getInt("id"));
            currentUser.setFirstName(jsonObject.getString("f_name"));
            currentUser.setLastName(jsonObject.getString("l_name"));
            currentUser.setNic(jsonObject.getString("nic"));
            currentUser.setContactNo(jsonObject.getString("contact_no"));
            currentUser.setDesignation(jsonObject.getInt("designation"));
            currentUser.setSupervisor_id(jsonObject.getInt("supervisor_id"));
            session.setCurrentUser(currentUser);
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }

    }

    private void startHomeActivity() {
        if (session.getServerSynced()) {
            startActivity(new Intent(LoginActivity.this, HomeActivity.class));
            finish();
        } else {
            Toast.makeText(LoginActivity.this, "Data Download Interrupted!", Toast.LENGTH_SHORT).show();
            showProgressBar(false);
        }
    }

    private void deleteDataBaseData() {
        ScheduleBusiness scheduleBusiness = new ScheduleBusiness(LoginActivity.this);
        RouteBusiness routeBusiness = new RouteBusiness(LoginActivity.this);
        OutletBusiness outletBusiness = new OutletBusiness(LoginActivity.this);
        ProductInspectionBusiness productInspectionBusiness = new ProductInspectionBusiness(LoginActivity.this);
        CoolerInspectionBusiness coolerInspectionBusiness = new CoolerInspectionBusiness(LoginActivity.this);
        InspectionBusiness inspectionBusiness = new InspectionBusiness(LoginActivity.this);
        ProductBusiness productBusiness = new ProductBusiness(LoginActivity.this);
        GalleryBusiness galleryBusiness = new GalleryBusiness(LoginActivity.this);
        ChangeRequestBusiness changeRequestBusiness = new ChangeRequestBusiness(LoginActivity.this);

        scheduleBusiness.DeleteAll();
        scheduleBusiness.Close();

        routeBusiness.DeleteAll();
        routeBusiness.Close();

        outletBusiness.DeleteAll();
        outletBusiness.Close();

        productInspectionBusiness.DeleteAll();
        productInspectionBusiness.Close();

        coolerInspectionBusiness.DeleteAll();
        coolerInspectionBusiness.Close();

        inspectionBusiness.DeleteAll();
        inspectionBusiness.Close();

        productBusiness.DeleteAll();
        productBusiness.Close();

        galleryBusiness.DeleteAll();
        galleryBusiness.Close();

        changeRequestBusiness.DeleteAll();
        changeRequestBusiness.Close();
    }

    private void initiateServerDownload() {
        deleteDataBaseData();
        startService(new Intent(LoginActivity.this, DataDownloadService.class));
        tvPb.setText("Data Downloading...");
        //        Toast.makeText(LoginActivity.this, String.valueOf(loginUserType), Toast.LENGTH_SHORT).show();
        //        showProgressBar(false);
    }

    private boolean isRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (DataDownloadService.class.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    //endregion

    //region Private Login Methods
    private void setLoginCredential(String username, String password) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(SharedPreferencesName.loginUserName, username);
        editor.putString(SharedPreferencesName.loginPassword, password);
        editor.putBoolean(SharedPreferencesName.autoLogin, true);
        editor.commit();
    }

    private void setLastLoginUserAndDate(String username) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(SharedPreferencesName.previousLoginUserName, username);
        editor.putString(SharedPreferencesName.previousLoginDate,
                Session.getSession().getStingDate(Calendar.getInstance().getTime()));
        editor.commit();
    }

    private boolean isSameLastLoginUser(String newUserName) {
        String previousUserName = sharedPreferences.getString(SharedPreferencesName.previousLoginUserName, "");
        return newUserName.contentEquals(previousUserName)
                || !(!newUserName.contentEquals(previousUserName) && !previousUserName.contentEquals(""));
    }

    private boolean isLastLoginDate() {
        String previousDate = sharedPreferences.getString(SharedPreferencesName.previousLoginDate, "");
        if (!previousDate.contentEquals("")) {
            String today = Session.getSession().getStingDate(Calendar.getInstance().getTime());
            return today.contentEquals(previousDate);
        } else {
            return false;
        }
    }

    private void automaticLogin() {
        String userName = sharedPreferences.getString(SharedPreferencesName.loginUserName, "");
        String password = sharedPreferences.getString(SharedPreferencesName.loginPassword, "");
        if ((!userName.contentEquals("")) && (!password.contentEquals(""))) {
            actvUserName.setText(userName);
            etPassword.setText(password);
            cbLoginRemember.setChecked(true);
            login(userName, password);
        }
    }

    private int getLoginUserType(String userName) throws Exception {
        int userType = UNKNOWN_USER;
        if (isSameLastLoginUser(userName) && isLastLoginDate()) {
            userType = SAME_USER;
        } else if (isSameLastLoginUser(userName) && (!isLastLoginDate())) {
            userType = SAME_USER_NEXT_DAY;
        } else if ((!isSameLastLoginUser(userName)) && isLastLoginDate()) {
            userType = DIFFERENT_USER_SAME_DATE;
        } else if ((!isSameLastLoginUser(userName)) && (!isLastLoginDate())) {
            userType = SAME_USER_NEXT_DAY; // same scenario to different user same date
        }
        return userType;
    }

    private boolean getDownloadStatus() {
        return sharedPreferences.getBoolean(SharedPreferencesName.downloadStatus, false);
    }

    private void setDownloadStatus(boolean downloaded) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(SharedPreferencesName.downloadStatus, downloaded);
        editor.commit();
    }

    private boolean isConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnected();
    }

    private void hasInternet() {
        if (isConnected()) {
            showProgressBar(true);
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            asyncHttpClient.get(LoginActivity.this, "http://google.lk", new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    if (isSameLastLoginUser(actvUserName.getText().toString())) {
                        login(actvUserName.getText().toString(), etPassword.getText().toString());
                    } else {
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(LoginActivity.this,
                                R.style.AlertDialogStyle);
                        alertDialogBuilder.setMessage(getString(R.string.warning_new_user_login));
                        alertDialogBuilder.setPositiveButton(getString(R.string.btn_txt_yes),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        login(actvUserName.getText().toString(), etPassword.getText().toString());
                                        dialog.dismiss();
                                    }
                                });
                        alertDialogBuilder.setNegativeButton(getString(R.string.btn_txt_no),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        noDataAlertDialog = alertDialogBuilder.create();
                        noDataAlertDialog.show();
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    showProgressBar(false);
                    noWarningDialog();
                }
            });
        } else {
            showProgressBar(false);
            noWarningDialog();
        }
    }

    private void noWarningDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this, R.style.AlertDialogStyle);
        builder.setMessage(getString(R.string.warning_internet_disable)).setCancelable(false)
                .setPositiveButton(R.string.btn_txt_yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
                    }
                }).setNegativeButton(R.string.btn_txt_no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    }
    //endregion

}