Skip to content

Instantly share code, notes, and snippets.

@fhereduardo90
Created November 20, 2014 15:00
Show Gist options
  • Save fhereduardo90/aed24dc5ae0e9ed84769 to your computer and use it in GitHub Desktop.
Save fhereduardo90/aed24dc5ae0e9ed84769 to your computer and use it in GitHub Desktop.
ejemplo de asynctask
private class UpdateUserAsyncTask extends AsyncTask<Void, String, Integer>{
@Override
protected Integer doInBackground(Void... voids) {
HttpURLConnection urlConnection = null;
OutputStream output = null;
int code = 0;
user.setFirstName(textFirstName.getText().toString());
user.setLastName(textLastName.getText().toString());
try {
URL url = new URL("http://192.168.0.108:3000/users/" + userId);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("Content-Type","application/json");
output = urlConnection.getOutputStream();
JSONObject joData = new JSONObject();
JSONObject joParent = new JSONObject();
joData.put("first_name", user.getFirstName());
joData.put("last_name", user.getLastName());
joData.put("gender", user.getGender());
joParent.put("user", joData);
joParent.put("id", userId);
output.write(joParent.toString().getBytes("UTF-8"));
output.close();
urlConnection.connect();
code = urlConnection.getResponseCode();
} catch (Exception e) {
// TODO Auto-generated catch block
}finally {
urlConnection.disconnect();
}
return code;
}
@Override
protected void onPostExecute(Integer code) {
if(code == 422){
Toast.makeText(getApplicationContext(),
"The user can not be updated", Toast.LENGTH_SHORT).show();
}else if(code == 204){
Toast.makeText(getApplicationContext(),
"The user has been updated", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),
"An error has ocurred", Toast.LENGTH_SHORT).show();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment