Cleaned Login + Register

Removed useless code - Minifyed + Loading spinner
This commit is contained in:
Sagi Dayan 2016-07-06 17:15:16 +03:00
parent d85693d54f
commit 219368175f
5 changed files with 119 additions and 334 deletions

View file

@ -1,89 +1,38 @@
package com.android_app.matan.ara.sagi.thesocialnotework;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import static android.Manifest.permission.READ_CONTACTS;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity{ // implements LoaderCallbacks<Cursor> {
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher{
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello", "bar@example.com:world"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private EditText mUsernameView;
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
private TextView mRegisterButton;
private Button mLoginButton;
private final String TAG = "Login Activity";
private final String TAG = "[TSN/LoginActivity]";
private final String BASE_URL = "http://thesocialnotework-api.appspot.com/api";
private final String LOGIN_PATH = "/login";
private LoginActivity self;
private LoginActivity self; //this
protected LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -91,92 +40,27 @@ public class LoginActivity extends AppCompatActivity{ // implements LoaderCallba
setContentView(R.layout.activity_login);
this.self = this;
this.layout = (LinearLayout) findViewById(R.id.layout);
mUsernameView = (EditText) findViewById(R.id.al_username);
mPasswordView = (EditText) findViewById(R.id.al_password);
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
showProgress(false);
this.mUsernameView = (EditText) findViewById(R.id.al_username);
this.mUsernameView.addTextChangedListener(this);
this.mPasswordView = (EditText) findViewById(R.id.al_password);
this.mPasswordView.addTextChangedListener(this);
removeFocuse();
this.mRegisterButton = (TextView) findViewById(R.id.al_register_button);
this.mRegisterButton.setOnClickListener(this);
this.mLoginButton = (Button) findViewById(R.id.al_login_button);
this.mLoginButton.setOnClickListener(this);
this.mLoginButton.setEnabled(false);
}
private void removeFocuse() {
// Remove Auto Focus from the Text Fields
mUsernameView.clearFocus();
mPasswordView.clearFocus();
layout.setFocusable(true);
layout.setFocusableInTouchMode(true);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mRegisterButton = (TextView) findViewById(R.id.al_register_button);
mRegisterButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "going to Register...page");
Intent registerActivity = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerActivity);
}
});
mLoginButton = (Button) findViewById(R.id.al_login_button);
mLoginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "Login.......");
showProgress(false);
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
// getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
@ -197,21 +81,14 @@ public class LoginActivity extends AppCompatActivity{ // implements LoaderCallba
}
}
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
showProgress(true);
MainActivity.showLoadingDialog(this, "Connecting", "Authenticating data");
mPasswordView.setError(null);
if (isParamsValid(mUsernameView.getText().toString(), mPasswordView.getText().toString())) {
String username = mUsernameView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// http request register
JSONObject tempJson = new JSONObject();
try {
@ -220,10 +97,9 @@ public class LoginActivity extends AppCompatActivity{ // implements LoaderCallba
} catch (Exception e) {
Log.d(TAG, e.toString());
}
VolleyUtilSingleton.getInstance(LoginActivity.this).post(BASE_URL + LOGIN_PATH, tempJson, onLoginSuccess, onLoginError);
} else {
showProgress(false);
MainActivity.dismissLoadingDialog();
Log.d(TAG, "Invalid params - make sure username exist & password is 4 characters or more");
}
@ -239,10 +115,17 @@ public class LoginActivity extends AppCompatActivity{ // implements LoaderCallba
Bundle loginUserBundle = new Bundle();
loginUserBundle.putString("user_id", response.getJSONObject("user").getString("id"));
personalSpaceActivity.putExtras(loginUserBundle);
MainActivity.dismissLoadingDialog();
startActivity(personalSpaceActivity);
} else {
showProgress(false);
MainActivity.dismissLoadingDialog();
Toast.makeText(self, "Username or Password are incorrect", Toast.LENGTH_LONG).show();
self.mUsernameView.getText().clear();
self.mPasswordView.getText().clear();
self.removeFocuse();
((TextView)findViewById(R.id.textView2)).setVisibility(View.INVISIBLE);
Log.d(TAG, "No such user, " + response.get("user"));
}
}catch (Exception e) {
Log.e(TAG, "onLoginSuccess:" + e.getMessage());
@ -253,8 +136,13 @@ public class LoginActivity extends AppCompatActivity{ // implements LoaderCallba
Response.ErrorListener onLoginError = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
showProgress(false);
MainActivity.dismissLoadingDialog();
Toast.makeText(self , "Username Or Password Incorrect", Toast.LENGTH_LONG).show();
//Clean texts
self.mUsernameView.getText().clear();
self.mPasswordView.getText().clear();
self.removeFocuse();
Log.d(TAG, "onErrorResponse: setting text to ''");
Log.d(TAG, "onLoginError: msg: " + error.getMessage());
}
};
@ -268,151 +156,43 @@ public class LoginActivity extends AppCompatActivity{ // implements LoaderCallba
return password.length() > 3;
}
/**
* 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);
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.al_login_button:
//Do Login
Log.d(TAG, "Login.......");
attemptLogin();
break;
case R.id.al_register_button:
//Do Register
Log.d(TAG, "going to Register...page");
Intent registerActivity = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(registerActivity);
break;
}
}
// @Override
// public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
// return new CursorLoader(this,
// // Retrieve data rows for the device user's 'profile' contact.
// Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
// ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
//
// // Select only email addresses.
// ContactsContract.Contacts.Data.MIMETYPE +
// " = ?", new String[]{ContactsContract.CommonDataKinds.Email
// .CONTENT_ITEM_TYPE},
//
// // Show primary email addresses first. Note that there won't be
// // a primary email address if the user hasn't specified one.
// ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
// }
//
// @Override
// public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
// List<String> users = new ArrayList<>();
// cursor.moveToFirst();
// while (!cursor.isAfterLast()) {
// emails.add(cursor.getString(ProfileQuery.ADDRESS));
// cursor.moveToNext();
// }
//
// addUsersToAutoComplete(users);
// }
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// @Override
// public void onLoaderReset(Loader<Cursor> cursorLoader) {
//
// }
private void addUsersToAutoComplete(List<String> usernameCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, usernameCollection);
// mUsernameView.setAdapter(adapter);
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if(isParamsValid(mUsernameView.getText().toString(), mPasswordView.getText().toString())) {
((TextView)findViewById(R.id.textView2)).setVisibility(View.INVISIBLE);
mLoginButton.setEnabled(true);
}
else{
((TextView)findViewById(R.id.textView2)).setVisibility(View.VISIBLE);
mLoginButton.setEnabled(false);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
@Override
public void afterTextChanged(Editable editable) {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}

View file

@ -1,5 +1,7 @@
package com.android_app.matan.ara.sagi.thesocialnotework;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
@ -22,6 +24,7 @@ public class MainActivity extends AppCompatActivity
protected String userId;
private GPSUtils gpsUtils;
private boolean locationPermission;
public static ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -129,4 +132,23 @@ public class MainActivity extends AppCompatActivity
public static void showLoadingDialog(Context context, String title, String msg) {
progress = new ProgressDialog(context);
progress.setTitle(title);
progress.setMessage(msg);
progress.setCanceledOnTouchOutside(false);
progress.show();
}
public static void dismissLoadingDialog() {
if (progress != null && progress.isShowing()) {
progress.dismiss();
}
}
}

View file

@ -10,12 +10,9 @@ import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONObject;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -40,22 +37,21 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mUsernameView = (EditText) findViewById(R.id.ra_username);
mPasswordView = (EditText) findViewById(R.id.ra_password);
mEmailView = (EditText) findViewById(R.id.ra_email);
this.mUsernameView = (EditText) findViewById(R.id.ra_username);
this.mPasswordView = (EditText) findViewById(R.id.ra_password);
this.mEmailView = (EditText) findViewById(R.id.ra_email);
this.self = this;
this.layout = (RelativeLayout) findViewById(R.id.ra_layout);
// Remove Auto Focus from the Text Fields
layout.setFocusable(true);
layout.setFocusableInTouchMode(true);
testBtn = (Button) findViewById(R.id.btn_cancel);
testBtn.setOnClickListener(this);
registerButton = (Button) findViewById(R.id.ra_register_button);
registerButton.setOnClickListener(this);
this.layout.setFocusable(true);
this.layout.setFocusableInTouchMode(true);
// Buttons And Listeners
this.testBtn = (Button) findViewById(R.id.btn_cancel);
this.testBtn.setOnClickListener(this);
this.registerButton = (Button) findViewById(R.id.ra_register_button);
this.registerButton.setOnClickListener(this);
}
@ -68,17 +64,9 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
private boolean isEmailValid(String email) {
if(TextUtils.isEmpty(email))
return false;
// boolean isValid = false;
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
// if (matcher.matches()) {
// isValid = true;
// }
// Log.d(TAG, "isValid: " + isValid);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
@ -87,19 +75,13 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
}
private void attemptRegister() {
// showProgress(true);
MainActivity.showLoadingDialog(this, "Registering", "Please Wait...");
Log.d(TAG, "in attemptRegister: Registering..");
if (isParamsValid(mUsernameView.getText().toString(), mPasswordView.getText().toString(), mEmailView.getText().toString())) {
Log.d(TAG, "params are valid");
String username = mUsernameView.getText().toString();
String password = mPasswordView.getText().toString();
String email = mEmailView.getText().toString();
boolean cancel = false;
View focusView = null;
// http request register
JSONObject tempJson = new JSONObject();
try {
@ -110,10 +92,9 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
Log.d(TAG, e.toString());
}
Log.d(TAG,"JSON: "+tempJson.toString());
VolleyUtilSingleton.getInstance(RegisterActivity.this).post(BASE_URL + REG_PATH, tempJson, onRegisterSuccess, onRegisterError);
} else {
// showProgress(false);
MainActivity.dismissLoadingDialog();
Log.d(TAG, "Invalid params - make sure username exist, password is 4 characters or more & email is valid");
Toast.makeText(this, "Make Sure tou have entered a valid email. password at least 4 chars", Toast.LENGTH_LONG).show();
}
@ -122,17 +103,15 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
Response.Listener<JSONObject> onRegisterSuccess = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG,"reposne: "+ response.toString());
Log.d(TAG,"response: "+ response.toString());
MainActivity.dismissLoadingDialog();
try {
if(response.getString("message").equals("created")) {
Log.d(TAG, "onRegisterSuccess => user created"); // TODO: REMOVE console
Intent loginActivity = new Intent(RegisterActivity.this, LoginActivity.class);
Toast.makeText(self, "You are now a social notework member - You May Login...", Toast.LENGTH_LONG).show();
startActivity(loginActivity);
} else {
// showProgress(false);
Toast.makeText(self , "Username is already taken. maybe: " + mUsernameView.getText().toString()+"_666 ? :)", Toast.LENGTH_LONG).show();
Log.d(TAG, "Cannot create user, " + response.getString("message"));
}
@ -146,7 +125,7 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
Response.ErrorListener onRegisterError = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// showProgress(false);
MainActivity.dismissLoadingDialog();
Toast.makeText(self , "Username is already taken. maybe: " + mUsernameView.getText().toString()+"_666 ? :)", Toast.LENGTH_LONG).show();
Log.d(TAG, "onRegisterError: msg: " + error.getMessage());
}
@ -159,7 +138,6 @@ public class RegisterActivity extends AppCompatActivity implements View.OnClickL
attemptRegister();
break;
case R.id.btn_cancel:
returnToLogin();
break;
}

View file

@ -17,15 +17,6 @@
android:paddingRight="24dp"
android:id="@+id/layout">
<!-- Login progress -->
<ProgressBar
android:id="@+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ImageView
android:layout_width="match_parent"
android:layout_height="80dp"
@ -61,7 +52,17 @@
android:hint="Password"/>
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="@string/login_err_message_invalid"
android:id="@+id/textView2"
android:layout_gravity="center_horizontal"
android:textColor="#820000"
android:visibility="invisible" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/al_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
@ -69,8 +70,11 @@
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Login"
android:textColor="#ffffff"
android:clickable="true"
android:enabled="false"
android:background="@color/colorPrimary"
android:textColor="#ffffff" />
android:elegantTextHeight="false" />
<TextView android:id="@+id/al_register_button"
android:layout_width="fill_parent"

View file

@ -36,5 +36,6 @@
<!-- TODO: Remove or change this placeholder text -->
<string name="hello_blank_fragment">Hello blank fragment</string>
<string name="login_err_message_invalid">Password should be at least 4 chars long</string>
</resources>