Skip to content

Instantly share code, notes, and snippets.

@mbarcia
Created January 31, 2014 17:17
Show Gist options
  • Save mbarcia/8736997 to your computer and use it in GitHub Desktop.
Save mbarcia/8736997 to your computer and use it in GitHub Desktop.
Handle login event using MyApi Request factory, a "custom" listener and an error listener. Part of http://develop-for-android.blogspot.com.es/2014/01/using-volley-in-your-application_31.html
// ...
/**
* Handles onClick event on the Submit button. Sends username/password to
* the server for authentication.
*
* @param view The Submit button for which this method is invoked
*/
public void handleLogin(View view) {
if(((EditText) findViewById(R.id.username)).getText() == null ||
((EditText) findViewById(R.id.username)).getText().toString().
trim().length()
< 1) {
Toast.makeText(this, "Please enter a Username",
Toast.LENGTH_LONG).show();
return;
}
if(((EditText) findViewById(R.id.password)).getText() == null ||
((EditText) findViewById(R.id.password)).getText().toString().
trim().length()
< 1) {
Toast.makeText(this, "Please enter a Password",
Toast.LENGTH_LONG).show();
return;
}
if (mRequestNewAccount) {
mUsername = mUsernameEdit.getText().toString();
}
mPassword = mPasswordEdit.getText().toString();
showProgress();
// Start authenticating...
MyApi api = new MyApi(this);
api.newLoginRequest(
mUsername,
mPassword,
this.loginSuccessfulListener(),
this.loginFailedListener()
);
}
private Response.Listener<LoginResponse> loginSuccessfulListener() {
return new Response.Listener<LoginResponse> () {
/**
* @param loginResponse DAO object with the session token
*/
@Override
public void onResponse(LoginResponse loginResponse) {
// Provide feedback - hide the mProgress dialog
dismissProgress();
// execute the business logic to actually create a user session
finishLogin(loginResponse.getSessionToken());
}
};
}
private Response.ErrorListener loginFailedListener() {
return new Response.ErrorListener () {
@Override
public void onErrorResponse(VolleyError error) {
// execute business logic related to a failed login attempt
// ...
// Provide feedback
dismissProgress();
new AlertDialog.Builder(AuthenticatorActivity.this).
setTitle(R.string.login_failed).
setNeutralButton(R.string.ok, null).
show();
}
};
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment