Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.custofeed.app.feedback.activity;
- import android.animation.Animator;
- import android.animation.AnimatorListenerAdapter;
- import android.annotation.TargetApi;
- import android.content.Context;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.os.AsyncTask;
- import android.os.Build;
- import android.os.Bundle;
- import android.support.v7.app.AppCompatActivity;
- import android.text.TextUtils;
- import android.view.KeyEvent;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.inputmethod.EditorInfo;
- import android.widget.AutoCompleteTextView;
- import android.widget.Button;
- import android.widget.CheckBox;
- import android.widget.EditText;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.android.volley.Request;
- import com.android.volley.RequestQueue;
- import com.android.volley.Response;
- import com.android.volley.VolleyError;
- import com.android.volley.toolbox.StringRequest;
- import com.android.volley.toolbox.Volley;
- import com.custofeed.app.feedback.R;
- import com.custofeed.app.feedback.model.DatabaseHandler;
- import com.custofeed.app.feedback.network.URLS;
- import com.custofeed.app.feedback.utils.SharedPreference;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * A login screen that offers login via username/password.
- */
- public class LoginActivity extends AppCompatActivity{
- /**
- * Keep track of the login task to ensure we can cancel it if requested.
- */
- private UserLoginTask mAuthTask = null;
- // UI references.
- private AutoCompleteTextView mUsernameView;
- private EditText mPasswordView;
- private View mProgressView;
- private View mLoginFormView;
- private Boolean loginResult = false;
- private SharedPreferences sharedPref;
- DatabaseHandler mydb;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- mydb = new DatabaseHandler(this);
- sharedPref = getSharedPreferences("data", MODE_PRIVATE);
- //Check if user is already logged in
- Boolean isLogged = sharedPref.getBoolean(SharedPreference.Account.IS_LOGGED, false);
- if(isLogged) {
- //Check if Login Expired
- long expires = sharedPref.getLong(SharedPreference.Account.SESSION_EXPIRE, 0);
- if(System.currentTimeMillis() < expires){
- nextActivity(true);
- }
- }
- // Set up the login form.
- mUsernameView = (AutoCompleteTextView) findViewById(R.id.username);
- mPasswordView = (EditText) findViewById(R.id.password);
- mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
- @Override
- public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
- ConnectivityManager connMgr = (ConnectivityManager)
- getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
- if (networkInfo != null && networkInfo.isConnected()) {
- if (id == R.id.login || id == EditorInfo.IME_NULL) {
- attemptLogin();
- return true;
- }
- } else {
- Toast.makeText(LoginActivity.this,
- "No network connection available", Toast.LENGTH_SHORT).show();
- }
- return false;
- }
- });
- //Autofill form if Details Exist
- String remUsername = sharedPref.getString(SharedPreference.Account.USERNAME, null);
- String remPassword = sharedPref.getString(SharedPreference.Account.PASSWORD, null);
- if(remUsername != null && remPassword != null){
- mUsernameView.setText(remUsername);
- mPasswordView.setText(remPassword);
- }
- Button mSignInButton = (Button) findViewById(R.id.sign_in_button);
- mSignInButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View view) {
- ConnectivityManager connMgr = (ConnectivityManager)
- getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
- if (networkInfo != null && networkInfo.isConnected()) {
- attemptLogin();
- } else {
- Toast.makeText(LoginActivity.this,
- "No network connection available", Toast.LENGTH_SHORT).show();
- }
- }
- });
- mLoginFormView = findViewById(R.id.login_form);
- mProgressView = findViewById(R.id.login_progress);
- }
- protected void setReturn(Boolean result){
- loginResult = result;
- }
- private void loginUser(){
- final String username = mUsernameView.getText().toString().trim();
- final String password = mPasswordView.getText().toString().trim();
- StringRequest stringRequest = new StringRequest(Request.Method.POST, URLS.POST_LOGIN,
- new Response.Listener<String>() {
- @Override
- public void onResponse(String response) {
- try {
- JSONObject jsonObject = new JSONObject(response);
- if(jsonObject.has("key")){
- SharedPreferences.Editor prefEditor = sharedPref.edit();
- prefEditor.putString(SharedPreference.Account.AUTH_TOKEN, jsonObject.optString("key"));
- prefEditor.apply();
- Toast.makeText(LoginActivity.this,
- "Logging In",Toast.LENGTH_SHORT).show();
- nextActivity(false);
- setReturn(true);
- }else{
- Toast.makeText(LoginActivity.this,
- "Invalid Credentials",Toast.LENGTH_SHORT).show();
- setReturn(false);
- }
- } catch (JSONException e) {
- Toast.makeText(LoginActivity.this,
- "Invalid Credentials",Toast.LENGTH_SHORT).show();
- setReturn(false);
- }
- }
- },
- new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- Toast.makeText(LoginActivity.this,
- "Invalid Credentials",Toast.LENGTH_SHORT).show();
- setReturn(false);
- }
- }){
- @Override
- protected Map<String,String> getParams(){
- Map<String,String> params = new HashMap<>();
- params.put(SharedPreference.Account.USERNAME, username);
- params.put(SharedPreference.Account.PASSWORD,password);
- return params;
- }
- };
- RequestQueue requestQueue = Volley.newRequestQueue(this);
- requestQueue.add(stringRequest);
- }
- /**
- * Attempts to sign in or register the account specified by the login form.
- * If there are form errors (invalid username, missing fields, etc.), the
- * errors are presented and no actual login attempt is made.
- */
- private void attemptLogin() {
- if (mAuthTask != null) {
- return;
- }
- // Reset errors.
- mUsernameView.setError(null);
- mPasswordView.setError(null);
- // Store values at the time of the login attempt.
- String username = mUsernameView.getText().toString();
- String password = mPasswordView.getText().toString();
- boolean cancel = false;
- View focusView = null;
- // Check for a valid password, if the user entered one.
- if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
- mPasswordView.setError(getString(R.string.error_invalid_password));
- focusView = mPasswordView;
- cancel = true;
- }
- // Check for a valid username address.
- if (TextUtils.isEmpty(username)) {
- mUsernameView.setError(getString(R.string.error_field_required));
- focusView = mUsernameView;
- cancel = true;
- }
- // Check for a valid password, if the user entered one.
- if (!isUsernameValid(username)) {
- mPasswordView.setError(getString(R.string.error_invalid_username));
- focusView = mPasswordView;
- cancel = true;
- }
- if (cancel) {
- // There was an error; don't attempt login and focus the first
- // form field with an error.
- focusView.requestFocus();
- } else {
- // Show a progress spinner, and kick off a background task to
- // perform the user login attempt.
- showProgress(true);
- mAuthTask = new UserLoginTask();
- mAuthTask.execute((Void) null);
- }
- }
- private boolean isUsernameValid(String username) {
- return username.length() > 0;
- }
- private boolean isPasswordValid(String password) {
- return password.length() > 4;
- }
- /**
- * Shows the progress UI and hides the login form.
- */
- @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
- private void showProgress(final boolean show) {
- // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
- // for very easy animations. If available, use these APIs to fade-in
- // the progress spinner.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
- int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- mLoginFormView.animate().setDuration(shortAnimTime).alpha(
- show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- });
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mProgressView.animate().setDuration(shortAnimTime).alpha(
- show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- }
- });
- } else {
- // The ViewPropertyAnimator APIs are not available, so simply show
- // and hide the relevant UI components.
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- }
- /**
- * Represents an asynchronous login/registration task used to authenticate
- * the user.
- */
- public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
- UserLoginTask() {}
- @Override
- protected Boolean doInBackground(Void... params) {
- try {
- loginUser();
- if(!loginResult){
- Toast.makeText(LoginActivity.this,
- "Invalid Login Credentials",Toast.LENGTH_LONG).show();
- }
- return loginResult;
- } catch(Exception e) {
- return false;
- }
- }
- @Override
- protected void onPostExecute(final Boolean success) {
- mAuthTask = null;
- showProgress(true);
- }
- @Override
- protected void onCancelled() {
- mAuthTask = null;
- showProgress(false);
- }
- }
- protected void nextActivity(Boolean isLogged){
- if(!isLogged){
- //Set User Logged in state
- SharedPreferences.Editor prefEditor = sharedPref.edit();
- prefEditor.putLong(SharedPreference.Account.SESSION_EXPIRE, System.currentTimeMillis() + URLS.SESSION_EXPIRE_TIME);
- prefEditor.putBoolean(SharedPreference.Account.IS_LOGGED,true);
- CheckBox rememberMe = (CheckBox) findViewById(R.id.rememberCheckBox);
- if(rememberMe.isChecked()){
- prefEditor.putString(SharedPreference.Account.USERNAME, mUsernameView.getText().toString().trim());
- prefEditor.putString(SharedPreference.Account.PASSWORD, mPasswordView.getText().toString().trim());
- }else{
- prefEditor.putString(SharedPreference.Account.USERNAME,null);
- prefEditor.putString(SharedPreference.Account.PASSWORD, null);
- }
- prefEditor.apply();
- }
- nextActivity();
- }
- protected void nextActivity(){
- finish();
- Intent myIntent = new Intent(this,PinActivity.class);
- this.startActivity(myIntent);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement