Skip to content

Instantly share code, notes, and snippets.

@cami7ord
Created June 2, 2015 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cami7ord/270b07d44088bcc7c840 to your computer and use it in GitHub Desktop.
Save cami7ord/270b07d44088bcc7c840 to your computer and use it in GitHub Desktop.
AsyncTask GET Android
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private Context mContext;
private final String mEmail;
private final String mPassword;
UserLoginTask(Context context, String email, String password) {
mContext = context.getApplicationContext();
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
Log.e("LoginActivity", "Login");
// Simulate network access.
//Thread.sleep(2000);
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(Constants.API_URL + Constants.VHS_USER + mEmail + "/" + mPassword);
//request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
// write response to log
if (response.getStatusLine().getStatusCode() == 200)
{
Log.e("LoginActivity", "RESPONSE: 200");
String sampleXml = EntityUtils.toString(response.getEntity());
Log.e("LoginActivity", "Sample:" + sampleXml);
JSONObject jsonObj = null;
try {
Log.e("LoginActivity", "Converting:" + sampleXml);
jsonObj = XML.toJSONObject(sampleXml);
} catch (JSONException e) {
Log.e("JSON exception", e.getMessage());
e.printStackTrace();
}
Log.d("XML", sampleXml);
Log.d("JSON", jsonObj.toString());
JSONObject myObject = new JSONObject(jsonObj.toString());
JSONObject vhsUser = myObject.getJSONObject("vhsUser");
userName = vhsUser.getString("fullName");
userEmail = vhsUser.getString("mail");
userPassword = vhsUser.getString("password");
userId = vhsUser.getInt("userId");
return true;
} else {
Log.e("Login", "ERROR");
}
//} catch (InterruptedException e) {
// return false;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
session = new SessionManager(getApplicationContext());
session.createLoginSession(userName, userEmail, userPassword, userId);
startActivity(new Intent(mContext, MainActivity.class));
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment