ie.ucd.www.bee.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for ie.ucd.www.bee.MainActivity.java

Source

package ie.ucd.www.bee;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;

import java.io.IOException;

import cn.pedant.SweetAlert.SweetAlertDialog;
import de.psdev.licensesdialog.LicensesDialog;
import de.psdev.licensesdialog.model.Notice;
import de.psdev.licensesdialog.model.Notices;
import ie.ucd.www.bee.lisense.WarningLisense;
import ie.ucd.www.bee.service.UserSignInService;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import ie.ucd.www.bee.lisense.TermsAndConditionsLicense;

public class MainActivity extends AppCompatActivity {

    final private int INTERNET_REQUEST_CODE = 101;
    final private int ACCESS_NETWORK_STATE_REQUEST_CODE = 102;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.INTERNET },
                    INTERNET_REQUEST_CODE);
        }

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_NETWORK_STATE },
                    ACCESS_NETWORK_STATE_REQUEST_CODE);
        }

        EditText username = (EditText) findViewById(R.id.user_name);
        EditText password = (EditText) findViewById(R.id.user_password);
        CheckBox rememberMe = (CheckBox) findViewById(R.id.remember_me);

        SharedPreferences userInfoKeep = getSharedPreferences("user_info_keep", MODE_PRIVATE);
        SharedPreferences.Editor userInfoEditor = userInfoKeep.edit();
        Boolean ifRemember = userInfoKeep.getBoolean("remember_me", false);

        if (ifRemember) {
            String usernameKeep = userInfoKeep.getString("username", "");
            String passwordKeep = userInfoKeep.getString("password", "");
            username.setText(usernameKeep);
            password.setText(passwordKeep);
            rememberMe.setChecked(true);
        }

        // if (userInfoKeep.getBoolean("first_start", true) {
        if (true) {
            final Notices notices = new Notices();
            notices.addNotice(new Notice("Terms and Conditions", "", "Please read and agree before continue.",
                    new TermsAndConditionsLicense()));
            notices.addNotice(
                    new Notice("Warning", "", "Please read and agree before continue.", new WarningLisense()));

            new LicensesDialog.Builder(this).setCloseText("Agree").setTitle(R.string.notice_title)
                    .setNotices(notices).setThemeResourceId(R.style.LisenseStyle).build().show();

            userInfoEditor.putBoolean("first_start", false);
            userInfoEditor.commit();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == INTERNET_REQUEST_CODE || requestCode == ACCESS_NETWORK_STATE_REQUEST_CODE)
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted

            } else {
                // Permission Denied
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE).setTitleText("Warning")
                        .setContentText("You must authorize BeeBia the necessary permissions.")
                        .setConfirmText("Exit")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                                Intent intent = new Intent(Intent.ACTION_MAIN);
                                intent.addCategory(Intent.CATEGORY_HOME);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            }
                        }).show();
            }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            Log.e("KEY_EVENT", "KeyEvent.KEYCODE_BACK");
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            break;
        }

        return super.onKeyDown(keyCode, event);
    }

    public void signin(View view) {
        final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.setTitleText("Sign in...");
        pDialog.show();

        final String SERVER_URL = getString(R.string.server_url);
        EditText username = (EditText) findViewById(R.id.user_name);
        EditText password = (EditText) findViewById(R.id.user_password);
        final CheckBox rememberMe = (CheckBox) findViewById(R.id.remember_me);

        final String userName = username.getText().toString();
        final String userPassword = password.getText().toString();

        final Context thisContext = this;
        final Intent homeIntent = new Intent(this, HomeActivity.class);

        Retrofit retrofit = new Retrofit.Builder().baseUrl(SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create()).build();

        UserSignInService userSignInService = retrofit.create(UserSignInService.class);

        String encodingAuth = "Basic "
                + Base64.encodeToString(String.format("%s:%s", userName, userPassword).getBytes(), Base64.NO_WRAP);

        Call<ResponseBody> call = userSignInService.userSignIn(encodingAuth);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        pDialog.dismiss();
                        SharedPreferences userInfoKeep = getSharedPreferences("user_info_keep", MODE_PRIVATE);
                        SharedPreferences.Editor userInfoEditor = userInfoKeep.edit();
                        String token = response.body().string();
                        homeIntent.putExtra("token", extractMessage(token));
                        homeIntent.putExtra("username", userName);
                        if (rememberMe.isChecked()) {
                            userInfoEditor.putBoolean("remember_me", true);
                            userInfoEditor.putString("username", userName);
                            userInfoEditor.putString("password", userPassword);
                            userInfoEditor.commit();
                        } else {
                            userInfoEditor.putBoolean("remember_me", false);
                            userInfoEditor.remove("username");
                            userInfoEditor.remove("password");
                            userInfoEditor.commit();
                        }
                        new SweetAlertDialog(thisContext, SweetAlertDialog.SUCCESS_TYPE).setTitleText("Success")
                                .setContentText("Welcome to BeeBia").setConfirmText("Continue")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismissWithAnimation();
                                        startActivity(homeIntent);
                                    }
                                }).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    pDialog.dismiss();
                    try {
                        String errorMessage = response.errorBody().string();
                        new SweetAlertDialog(thisContext, SweetAlertDialog.ERROR_TYPE).setTitleText("Error")
                                .setContentText(extractMessage(errorMessage)).setConfirmText("Try again").show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                pDialog.dismiss();
                new SweetAlertDialog(thisContext, SweetAlertDialog.ERROR_TYPE).setTitleText("Sorry")
                        .setContentText("There are some errors of the web service, please try again later.")
                        .setConfirmText("return").show();
                String result = throwable.toString();
                Log.e("SignInResult", result);
            }
        });
    }

    public void signup(View view) {
        Intent userRegisterIntent = new Intent(this, UserRegisterActivity.class);
        startActivity(userRegisterIntent);
    }

    public String extractMessage(String message) {
        for (int i = message.length() - 4; i > 0; i--) {
            if (message.charAt(i) == '\"') {
                return message.substring(i + 1, message.length() - 3);
            }
        }
        return message;
    }
}