Trying to get around this Webservice call from Android using AsycTask
Posted
by
Kevin Rave
on Stack Overflow
See other posts from Stack Overflow
or by Kevin Rave
Published on 2012-09-06T03:35:31Z
Indexed on
2012/09/06
3:38 UTC
Read the original article
Hit count: 168
I am a fairly beginner in Android Development. I am developing an application that extensively relays on Webservice calls. First screen takes username and password and validates the user by calling the Webservice. If U/P is valid, then I need to fire up the 2nd activity. In that 2nd activity, I need to do 3 calls. But I haven't gotten to the 2nd part yet. In fact, I haven't completed the full coding yet. But I wanted to test if the app is working as far as I've come through.
When calling webserivce, I am showing alert dialog. But the app is crashing somewhere. The LoginActivity shows up. When I enter U/P and press Login Button, it crashes.
My classes:
TaskHandler.java
public class TaskHandler {
private String URL;
private User userObj;
private String results;
private JSONDownloaderTask task; ;
public TaskHandler( String url, User user) {
this.URL = url;
this.userObj = user;
}
public String handleTask() {
Log.d("Two", "In the function");
task = new JSONDownloaderTask();
Log.d("Three", "In the function");
task.execute(URL);
return results;
}
private class JSONDownloaderTask extends AsyncTask<String, Void, String> {
private String username;// = userObj.getUsername();
private String password; //= userObj.getPassword();
public HttpStatus status_code;
public JSONDownloaderTask() {
Log.d("con", "Success");
this.username = userObj.getUsername();
this.password = userObj.getPassword();
Log.d("User" + this.username , " Pass" + this.password);
}
private AsyncProgressActivity progressbar = new AsyncProgressActivity();
@Override
protected void onPreExecute() {
progressbar.showLoadingProgressDialog();
}
@Override
protected String doInBackground(String... params) {
final String url = params[0]; //getString(R.string.api_staging_uri) + "Authenticate/";
// Populate the HTTP Basic Authentitcation header with the username and password
HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
try {
// Make the network request
Log.d(this.getClass().getName(), url);
ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), Message.class);
status_code = response.getStatusCode();
return response.getBody().toString();
} catch (HttpClientErrorException e) {
status_code = e.getStatusCode();
return new Message(0, e.getStatusText(), e.getLocalizedMessage(), "error").toString();
} catch ( Exception e ) {
Log.d(this.getClass().getName() ,e.getLocalizedMessage());
return "Unknown Exception";
}
}
@Override
protected void onPostExecute(String result) {
progressbar.dismissProgressDialog();
switch ( status_code ) {
case UNAUTHORIZED:
result = "Invalid username or passowrd"; break;
case ACCEPTED:
result = "Invalid username or passowrd" + status_code; break;
case OK:
result = "Successful!"; break;
}
}
}
}
AsycProgressActivity.java
public class AsyncProgressActivity extends Activity {
protected static final String TAG = AsyncProgressActivity.class.getSimpleName();
private ProgressDialog progressDialog;
private boolean destroyed = false;
@Override
protected void onDestroy() {
super.onDestroy();
destroyed = true;
}
public void showLoadingProgressDialog() {
Log.d("Here", "Progress");
this.showProgressDialog("Authenticating...");
Log.d("Here", "afer p");
}
public void showProgressDialog(CharSequence message) {
Log.d("Here", "Message");
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setIndeterminate(true);
}
Log.d("Here", "Message 2");
progressDialog.setMessage(message);
progressDialog.show();
}
public void dismissProgressDialog() {
if (progressDialog != null && !destroyed) {
progressDialog.dismiss();
}
}
}
LoginActivity.java
public class LoginActivity extends AsyncProgressActivity implements OnClickListener {
Button login_button;
HttpStatus status_code;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
login_button = (Button) findViewById(R.id.btnLogin);
login_button.setOnClickListener(this);
ViewServer.get(this).addWindow(this);
}
public void onDestroy() {
super.onDestroy();
ViewServer.get(this).removeWindow(this);
}
public void onResume() {
super.onResume();
ViewServer.get(this).setFocusedWindow(this);
}
public void onClick(View v) {
if ( v.getId() == R.id.btnLogin ) {
User userobj = new User();
String result;
userobj.setUsername( ((EditText) findViewById(R.id.username)).getText().toString());
userobj.setPassword(((EditText) findViewById(R.id.password)).getText().toString() );
TaskHandler handler = new TaskHandler(getString(R.string.api_staging_uri) + "Authenticate/", userobj);
Log.d(this.getClass().getName(), "One");
result = handler.handleTask();
Log.d(this.getClass().getName(), "After two");
Utilities.showAlert(result, LoginActivity.this);
}
}
Utilities.java
public class Utilities {
public static void showAlert(String message, Context context) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Login");
alertDialogBuilder.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.dismiss();
//dialog.cancel();
}
});
alertDialogBuilder.setIcon(drawable.ic_dialog_alert);
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
© Stack Overflow or respective owner