- login api call implemented

- passing user id to PersonalSpaceActivity
This commit is contained in:
Matan Bar Yosef 2016-07-02 19:27:32 +03:00
parent fe3ffda650
commit 957e4e634b
4 changed files with 148 additions and 118 deletions

View file

@ -31,6 +31,10 @@ import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
@ -41,7 +45,7 @@ import static android.Manifest.permission.READ_CONTACTS;
/** /**
* A login screen that offers login via email/password. * A login screen that offers login via email/password.
*/ */
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> { public class LoginActivity extends AppCompatActivity{ // implements LoaderCallbacks<Cursor> {
/** /**
* Id to identity READ_CONTACTS permission request. * Id to identity READ_CONTACTS permission request.
@ -61,17 +65,17 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
private UserLoginTask mAuthTask = null; private UserLoginTask mAuthTask = null;
// UI references. // UI references.
private AutoCompleteTextView mUsernameView; private EditText mUsernameView;
private AutoCompleteTextView mEmailView; private AutoCompleteTextView mEmailView;
private EditText mPasswordView; private EditText mPasswordView;
private View mProgressView; private View mProgressView;
private View mLoginFormView; private View mLoginFormView;
private final String TAG = "Login Activity"; private final String TAG = "Login Activity";
private final String BASE_URL = "http://thesocialnotework-api.appspot.com/api"; private final String BASE_URL = "http://thesocialnotework-api.appspot.com/api";
private final String REG_PATH = "/register";
private final String LOGIN_PATH = "/login"; private final String LOGIN_PATH = "/login";
private boolean loginSuccess = false; private final String REG_PATH = "/register";
@Override @Override
@ -80,13 +84,13 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
setContentView(R.layout.activity_login); setContentView(R.layout.activity_login);
// Set up the login form. // Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email); // mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete(); // populateAutoComplete();
// mUsernameView = (AutoCompleteTextView) findViewById(R.id.username); // mUsernameView = (AutoCompleteTextView) findViewById(R.id.username);
// populateAutoComplete(); // populateAutoComplete();
// mUsernameView mUsernameView = (EditText) findViewById(R.id.al_username);
mPasswordView = (EditText) findViewById(R.id.password); mPasswordView = (EditText) findViewById(R.id.al_password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override @Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
@ -102,7 +106,7 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
@Override @Override
public void onClick(View view) { public void onClick(View view) {
Log.d(TAG, "Register....... this section under construction"); Log.d(TAG, "Register....... this section under construction");
//attemptLogin(); //attemptRegister(); // TODO : implement
} }
}); });
@ -124,7 +128,7 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
return; return;
} }
getLoaderManager().initLoader(0, null, this); // getLoaderManager().initLoader(0, null, this);
} }
private boolean mayRequestContacts() { private boolean mayRequestContacts() {
@ -168,70 +172,109 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
* If there are form errors (invalid email, missing fields, etc.), the * If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made. * errors are presented and no actual login attempt is made.
*/ */
private boolean isParamsValid(String username, String password) {
Log.d(TAG, "user: " + username);
Log.d(TAG, "pwd: " + password);
if(TextUtils.isEmpty(username) || !isPasswordValid(username) || TextUtils.isEmpty(password) || !isPasswordValid(password)) {
return false;
} else{
return true;
}
}
private void attemptLogin() { private void attemptLogin() {
if (mAuthTask != null) { if (mAuthTask != null) {
return; return;
} }
// Reset errors. // Reset errors.
mEmailView.setError(null); // mEmailView.setError(null);
// mUsernameView.setError(null); // mUsernameView.setError(null);
mPasswordView.setError(null); mPasswordView.setError(null);
// Store values at the time of the login attempt. // Store values at the time of the login attempt.
// String username = mUsernameView.getText().toString();
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false; // String email = mEmailView.getText().toString();
View focusView = null;
// Check for a valid password, if the user entered one. if (isParamsValid(mUsernameView.getText().toString(), mPasswordView.getText().toString())) {
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { String username = mUsernameView.getText().toString();
mPasswordView.setError(getString(R.string.error_invalid_password)); String password = mPasswordView.getText().toString();
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address. boolean cancel = false;
if (TextUtils.isEmpty(email)) { View focusView = null;
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) { // Check for a valid password, if the user entered one.
// There was an error; don't attempt login and focus the first if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
// form field with an error. mPasswordView.setError(getString(R.string.error_invalid_password));
focusView.requestFocus(); focusView = mPasswordView;
} else { cancel = true;
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
// http request register
JSONObject tempJson = new JSONObject();
try {
tempJson.put("email", email);
tempJson.put("password", password);
} catch (Exception e) {
Log.d(TAG, e.toString());
} }
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(username, password); // TODO: RETRIEVE ?
// mAuthTask.execute((Void) null); // TODO: RETRIEVE ?
VolleyUtilSingleton.getInstance(LoginActivity.this).newUser(BASE_URL + LOGIN_PATH, tempJson); // http request register
JSONObject tempJson = new JSONObject();
try {
tempJson.put("username", username);
tempJson.put("password", password);
} catch (Exception e) {
Log.d(TAG, e.toString());
}
Intent personalSpaceActivity = new Intent(LoginActivity.this, PersonalSpaceActivity.class); VolleyUtilSingleton.getInstance(LoginActivity.this).post(BASE_URL + LOGIN_PATH, tempJson, onLoginSuccess, onLoginError);
startActivity(personalSpaceActivity); }
} else {
showProgress(false);
Log.d(TAG, "Invalid params");
} }
// Check for a valid username
// if (TextUtils.isEmpty(username)) {
// mUsernameView.setError(getString(R.string.error_field_required));
// focusView = mUsernameView;
// cancel = true;
// } else if (!isEmailValid(username)) {
// mUsernameView.setError(getString(R.string.error_invalid_email));
// focusView = mUsernameView;
// cancel = true;
// }
} }
Response.Listener<JSONObject> onLoginSuccess = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if(response.get("user") != null) {
Log.e(TAG, "onLoginSuccess => user exist"); // TODO: REMOVE console
Intent personalSpaceActivity = new Intent(LoginActivity.this, PersonalSpaceActivity.class);
Bundle b = new Bundle();
b.putString("user_id", response.getJSONObject("user").getString("id"));
personalSpaceActivity.putExtras(b);
startActivity(personalSpaceActivity);
}
}catch (Exception e) {
Log.e(TAG, "onLoginSuccess:" + e.getMessage());
}
}
};
Response.ErrorListener onLoginError = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onLoginError: msg: " + error.getMessage());
}
};
private boolean isEmailValid(String email) { private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic //TODO: Replace this with your own logic
return email.contains("@") && email.contains("."); return email.contains("@") && email.contains(".");
@ -278,47 +321,47 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
} }
} }
@Override // @Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { // public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this, // return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact. // // Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, // Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // 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);
// }
// Select only email addresses. // @Override
ContactsContract.Contacts.Data.MIMETYPE + // public void onLoaderReset(Loader<Cursor> cursorLoader) {
" = ?", new String[]{ContactsContract.CommonDataKinds.Email //
.CONTENT_ITEM_TYPE}, // }
// Show primary email addresses first. Note that there won't be private void addUsersToAutoComplete(List<String> usernameCollection) {
// 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> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list. //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter = ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this, new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection); android.R.layout.simple_dropdown_item_1line, usernameCollection);
mEmailView.setAdapter(adapter); // mUsernameView.setAdapter(adapter);
} }

View file

@ -122,7 +122,7 @@ public class PersonalSpaceActivity extends AppCompatActivity {
Log.d(TAG, e.toString()); Log.d(TAG, e.toString());
} }
VolleyUtilSingleton.getInstance(PersonalSpaceActivity.this).newUser(BASE_URL + "/note/upsert", noteJson); VolleyUtilSingleton.getInstance(PersonalSpaceActivity.this).post(BASE_URL + "/note/upsert", noteJson, newNoteSuccess, newNoteError);
dialog.dismiss(); dialog.dismiss();
} }
}); });

View file

@ -30,38 +30,24 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:orientation="vertical"> android:orientation="vertical">
<android.support.design.widget.TextInputLayout <EditText
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="@+id/email"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:hint="@string/prompt_email" android:id="@+id/al_username"
android:inputType="textEmailAddress" android:inputType="textPersonName"
android:maxLines="1" android:hint="@string/prompt_username" />
android:singleLine="true" />
</android.support.design.widget.TextInputLayout> <EditText
android:id="@+id/al_password"
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content"> android:layout_height="wrap_content"
android:hint="@string/prompt_password"
<EditText android:imeActionId="@+id/login"
android:id="@+id/password" android:imeActionLabel="@string/action_sign_in_short"
android:layout_width="match_parent" android:imeOptions="actionUnspecified"
android:layout_height="wrap_content" android:inputType="textPassword"
android:hint="@string/prompt_password" android:maxLines="1"
android:imeActionId="@+id/login" android:singleLine="true" />
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<LinearLayout <LinearLayout
android:orientation="horizontal" android:orientation="horizontal"

View file

@ -3,6 +3,7 @@
<!-- Strings related to login --> <!-- Strings related to login -->
<string name="prompt_email">Email</string> <string name="prompt_email">Email</string>
<string name="prompt_username">Username</string>
<string name="prompt_password">Password (optional)</string> <string name="prompt_password">Password (optional)</string>
<string name="action_login">Login</string> <string name="action_login">Login</string>
<string name="action_register">Register</string> <string name="action_register">Register</string>