I am trying to create a native login screen, where the username and password boxes slide off the screen while the request is being processed (and slide back up if the login is unsuccessful).
In order to achieve that, I have defined my animation (DropDownAnimation) and I assign it to my LinearLayout (footer). When the user clicks the Login button, I start the animation, and then call a function (tryLogin()) which starts an AsyncTask. The AsyncTask handles all the work of creating and sending the login request, and getting the JSONObject response.
However, my problem is that the slideDown animation doesn't start until after the AsyncTask has completed. This doesn't look so bad on a successful login, but on a failed login it means that the LinearLayout never slides down - it jumps to the bottom of the screen, to begin the slideUp animation back to its original position.
This seems like a similar problem to this question, but I'm not doing using bindService() and all my non-UI code seems (to me) to be contained in the AsyncTask already. LogCat tells me:
06-24 04:37:35.141: I/Choreographer(5347): Skipped 137 frames! The application may be doing too much work on its main thread.
I assume those are the frames where the footer would be sliding down - but I can't figure out where it is that I'm executing things on the main thread. Here's my code for LoginPage and LoginTask.
LoginPage.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
login = (Button) findViewById(R.id.login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
footer = (LinearLayout) findViewById(R.id.footer);
// We must wait for the layout to be finalised before trying to find heights.
ViewTreeObserver vto = footer.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
initAnimations();
}
});
loading = (TextView) findViewById(R.id.loading);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
// Neither of these two things happen until after LoginTask is done.
footer.startAnimation(slideDown);
loading.setVisibility(TextView.VISIBLE);
tryLogin(mUsername, mPassword);
}
});
}
protected void tryLogin(String mUsername, String mPassword) {
Exception e;
String loginUrl = getString(R.string.login_url);
String clientId = getString(R.string.client_id);
String clientSecret = getString(R.string.client_secret);
LoginTask loginTask = (LoginTask) new LoginTask().execute(mUsername, mPassword, loginUrl, clientId, clientSecret);
if ((e = loginTask.getException()) != null) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
} else {
JSONObject response;
try {
response = loginTask.get();
Log.d("login", response.toString());
if (!response.has("access_token")) {
loading.setVisibility(TextView.INVISIBLE);
footer.startAnimation(slideUp);
Toast.makeText(this, "Login error", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(this, FullscreenWebView.class);
i.putExtra("accessToken", response.get("access_token").toString());
startActivity(i);
overridePendingTransition(0, 0);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
Thread.currentThread().interrupt();
} catch (ExecutionException e1) {
e1.printStackTrace();
} catch (JSONException e1) {
e1.printStackTrace();
throw new RuntimeException(e);
}
}
}
LoginTask.java
class LoginTask extends AsyncTask<String, Void, JSONObject> {
private Exception exception;
#Override
protected JSONObject doInBackground(String... params) {
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
JSONObject response = null;
String parameters = "grant_type=password&username="+params[0]+"&password="+params[1]+"&client_id="+params[3]+"&client_secret="+params[4];
try {
url = new URL(params[2]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
// username or password is probably wrong
Log.d("login", ""+connection.getResponseCode());
if (connection.getResponseCode() != 200) {
return new JSONObject();
}
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("login", sb.toString());
response = new JSONObject(sb.toString());
isr.close();
reader.close();
} catch (Exception e) {
this.exception = e;
}
return response;
}
}
I've also tried making LoginTask be a member class of LoginPage, and starting the animation in the onPreExecute() method, but that didn't change anything.
Any help is much appreciated!
When you use AsyncTask.get(), you are blocking the UI thread. As the animation runs on the UI thread, it appears as if it is not running (while in fact it is blocked by your long running tryLogin method).
Instead, you should move the code that relies on the result from the LoginTask to its onPostExecute method:
protected void tryLogin(String mUsername, String mPassword) {
String loginUrl = getString(R.string.login_url);
String clientId = getString(R.string.client_id);
String clientSecret = getString(R.string.client_secret);
new LoginTask().execute(mUsername, mPassword,
loginUrl, clientId, clientSecret);
}
LoginTask.java
class LoginTask extends AsyncTask<String, Void, JSONObject> {
private Exception exception;
#Override
protected JSONObject doInBackground(String... params) {
// Unchanged
}
public void onPostExecute(JSONObject response) {
if (exception != null) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
} else {
Log.d("login", response.toString());
if (!response.has("access_token")) {
loading.setVisibility(TextView.INVISIBLE);
footer.startAnimation(slideUp);
Toast.makeText(this, "Login error", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(this, FullscreenWebView.class);
i.putExtra("accessToken", response.get("access_token").toString());
startActivity(i);
overridePendingTransition(0, 0);
}
}
}
}
Related
I am new in Android development and I need some help with HttpURLConnection.
What I want to do is to send http get request (by clicking button) and then check the response (to check response I added TextView to my main Activity).
My code:
public class MainActivity extends AppCompatActivity {
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendGetRequest(View View) {
new GetClass(this).execute();
}
private class GetClass extends AsyncTask<String, Void, Void> {
private final Context context;
public GetClass(Context c){
this.context = c;
}
protected void onPreExecute(){
progress= new ProgressDialog(this.context);
progress.setMessage("Loading");
progress.show();
}
#Override
protected Void doInBackground(String... params) {
String dataUrl = "http://myurl.com";
String dataUrlParameters = "email="+"pp#gmail.com"+"&name="+"priyabrat";
URL url;
HttpURLConnection connection = null;
try {
final TextView outputView = (TextView) findViewById(R.id.showOutput);
url = new URL(dataUrl);
connection = (HttpURLConnection) url.openConnection();
String urlParameters = "fizz=buzz";
connection.setRequestMethod("GET");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
int responseCode = connection.getResponseCode();
final StringBuilder output = new StringBuilder("Request URL " + url);
output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
output.append(System.getProperty("line.separator") + "Type " + "GET");
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
outputView.setText(output);
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
The problem is, when I run my app and click the button "Send GET Request", application is stopping with message "Application Was stopped"
Have a look at some Networking Librarys for Android, they will handle the async stuff for you:
Volley (https://developer.android.com/training/volley/index.html)
Retrofit makes(HTTP API into a Java interface.)(http://square.github.io/retrofit/)
OkHTTP(Retrofit works with it)https://github.com/square/okhttp/wiki/Recipes
If you would do it for your own, have a look at the doku from Async Task (
https://developer.android.com/reference/android/os/AsyncTask.html) and use the Function:
onPostExecute(String output)
invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
And instead of:
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
outputView.setText(output);
progress.dismiss();
}
});
make this:
return output;
This is my Asyntask code which is not firing the onPostExecute() Any one has any idea why this might be happening???
EDIT: The Asyntask is called this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
.
.
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUp.class);
startActivity(intent);
}
});
textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Feedback.class);
startActivity(intent);
}
});
fbLoginButton = (LoginButton) findViewById(R.id.login_button);
fbLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
token=loginResult.getAccessToken().getToken().toString();
Log.v("tag", "Token:\n" + token);
try {
get_profile();
}catch (Exception ex) {
String error = ex.getMessage();
}
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login cancelled by user!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
#Override
public void onError(FacebookException e) {
Toast.makeText(MainActivity.this, "Login unsuccessful!", Toast.LENGTH_LONG).show();
System.out.println("Facebook Login failed!!");
}
});
}
The get_profile(); method is defined like this
//Method to get profile details
public void get_profile() throws UnsupportedEncodingException {
try {
// Calling async task to get json
new FetchOperation().execute();
} catch (Exception e) {
e.printStackTrace();
}
}
This is inside the Main class too
//Asynctask to get Getting fb profile details
private class FetchOperation extends AsyncTask<Void, Void, String> {
String fb_token;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
fb_token = token;
}
#Override
protected String doInBackground(Void... params) {
String response = "";
String Urls = "https://graph.facebook.com/me?access_token=";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(Urls +token);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
httpResponse = httpclient.execute(httpget);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("Response", "Hi From e1 : " + e.toString());
} catch (IOException e) {
e.printStackTrace();
}
try {
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Log.v("Response", "Hi From 2 : "+response.toString());
return response;
} catch (IOException e) {
e.printStackTrace();
Log.v("Response", "Hi From e2 : " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String jsonStr) {
super.onPostExecute(jsonStr);
Log.v("tag", "Result:" + jsonStr);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
String email = jsonObj.getString("email");
String firstName = jsonObj.getString("first_name");
String lastName = jsonObj.getString("last_name");
String gender = jsonObj.getString("gender");
String country = jsonObj.getString("locale");
id = jsonObj.getString("id");
user = firstName.concat(" ");
user = user.concat(lastName);
image = "http://graph.facebook.com/" + id + "/picture?type=large";
Log.v("Fb name", "Bla bla Name : " + user);
new UploadOperation().execute();
}
catch (JSONException e) {
e.printStackTrace();
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
}
This is the last lines of the logcat
06-29 14:30:49.927 2091-2091/com.example.kmi_dev.fbloginsample V/tag﹕ Token:
CA****************************************************************xr
06-29 14:30:50.697 2091-2135/com.example.kmi_dev.fbloginsample V/Response﹕ Hi From 2 : {"id":"910***********6","first_name":"Shivanshu","gender":"male","last_name":"Verma","link":"https:\/\/www.facebook.com\/app_scoped_user_id\/910***********6\/","locale":"en_GB","name":"Shivanshu Verma","timezone":5.5,"updated_time":"2015-06-22T04:17:39+0000","verified":true}
06-29 14:31:23.827 2091-2098/com.example.kmi_dev.fbloginsample W/art﹕ Suspending all threads took: 10ms
I intend to fire another asyntask which will then save the data fetched by this asyntask into the database.
Make these changes, it will work -
private class FetchOperation extends AsyncTask<Void, Void, String>
change to - private class FetchOperation extends AsyncTask<Void, String, String> , because, you are trying to return String.
response = EntityUtils.toString(httpEntity);
change to - response = EntityUtils.toString(httpEntity).toString();
at the next line of this you have actually done it.
At the very end of doInBackground method where return null;
change to - return response;
4.No need to call super in onPostExecute()
5.Inside onPostExecute() check jsonStr is null or not and do whatever you want to do if null and if contains json data.
Your JSONObject does not contain a JSONString "email", so it is falling over at line
String email = jsonObj.getString("email");
and going straight to catch block.
I am trying to make a request to a server to a php script which will check to see if a user exists in a database. Currently I just want to make sure I am receiving some sort of response. I try to output the value of responseString when the user presses the login button but every time it comes back as null. Does anyone know why??
This is my MainActivity
public class MainActivity extends Activity {
EditText username;
EditText password;
Button loginBtn;
LinearLayout loginform;
String passwordDetail;
String usernameDetail;
String url = "http://www.mysite.com/example/checklogin.php";
String responseString = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide the Action Bar
ActionBar ab;
ab = this.getActionBar();
ab.hide();
//Get references to XML
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
loginBtn = (Button)findViewById(R.id.loginBtn);
loginform = (LinearLayout)findViewById(R.id.loginform);
//Animation
final AlphaAnimation fadeIn = new AlphaAnimation(0.0f , 1.0f );
AlphaAnimation fadeOut = new AlphaAnimation( 1.0f , 0.0f ) ;
fadeIn.setDuration(1200);
fadeIn.setFillAfter(true);
fadeOut.setDuration(1200);
fadeOut.setFillAfter(true);
fadeOut.setStartOffset(4200+fadeIn.getStartOffset());
//Run thread after 2 seconds to start Animation
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run() {
//display login form
loginform.startAnimation(fadeIn);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//display();
Toast.makeText(getApplicationContext(), "Checking login details...", Toast.LENGTH_SHORT).show();
if(checkLoginDetails()){
//OPENS NEW ACTIVITY
//Close splash screen
//finish();
//start home screen
Intent intent = new Intent(v.getContext(), SectionsActivity.class);
//startActivity(intent);
//creates fade in animation between two activities
overridePendingTransition(R.anim.fade_in, R.anim.splash_fade_out);
Toast.makeText(getApplicationContext(), "Login Successful" + responseString, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Login Unsuccessful", Toast.LENGTH_SHORT).show();
}
}
});
}
}, 2000);
}
//Check the login details before proceeding.
public boolean checkLoginDetails(){
usernameDetail = username.getText().toString();
passwordDetail = password.getText().toString();
new RequestTask().execute(url, usernameDetail, passwordDetail);
return true;
}
This is the php script I'm requesting - At moment I've hard coded details I know to exist in db and just want to focus on getting back a response to say user exists.
<?php
mysql_connect("xxx.xxx.xxx.xxx", "username", "password") or die("Couldn't select database.");
mysql_select_db("databasename") or die("Couldn't select database.");
//$username = $_POST['username'];
//$password = $_POST['password'];
$pwdMD5 = md5(123);
$sql = "SELECT * FROM membership WHERE Username = 'user1' AND Password = '$pwdMD5' ";
$result = mysql_query($sql) or die(mysql_error());
$numrows = mysql_num_rows($result);
if($numrows > 0)
{
echo 'user found';
return true;
}
else
{
echo 'user not found';
return false;
}
?>
This is my AsyncTask.
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
responseString = null;
try {
response = httpclient.execute(new HttpPost(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
It is null because you execute the code asynchronously. You Toast the result while the HTTP request is not yet finished executing your PHP script.
Try putting your Toast to onPostExecute(String result) method in your AsyncTask class.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Toast result.
}
You are not getting something from the respose but putting in it... use ByteArrayInputStream instead of output stream.....
I'm trying to make a login system for my application. Currently the user can create an account online and download the app. They are then prompted for their username and password.
When they press the login button I want to make a request to a php script on the server to check the results and return true if the user does exist and false if they do not exist.
I am a little bit confused about how I should implement this?
I am trying to create a seperate class that extends AsyncTask.
This is my MainActivity
EditText username;
EditText password;
Button loginBtn;
LinearLayout loginform;
String passwordDetail;
String usernameDetail;
String url = "http://www.jdiadt.com/example/checklogindetails.php";
HttpTask httptask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Hide the Action Bar
ActionBar ab;
ab = this.getActionBar();
ab.hide();
//Get references to XML
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
loginBtn = (Button)findViewById(R.id.loginBtn);
loginform = (LinearLayout)findViewById(R.id.loginform);
//Animation
final AlphaAnimation fadeIn = new AlphaAnimation(0.0f , 1.0f );
AlphaAnimation fadeOut = new AlphaAnimation( 1.0f , 0.0f ) ;
fadeIn.setDuration(1200);
fadeIn.setFillAfter(true);
fadeOut.setDuration(1200);
fadeOut.setFillAfter(true);
fadeOut.setStartOffset(4200+fadeIn.getStartOffset());
//Run thread after 2 seconds to start Animation
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
public void run() {
//display login form
loginform.startAnimation(fadeIn);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//display();
Toast.makeText(getApplicationContext(), "Checking login details...", Toast.LENGTH_SHORT).show();
if(checkLoginDetails()){
//OPENS NEW ACTIVITY
//Close splash screen
finish();
//start home screen
Intent intent = new Intent(v.getContext(), SectionsActivity.class);
startActivity(intent);
//creates fade in animation between two activities
overridePendingTransition(R.anim.fade_in, R.anim.splash_fade_out);
}
else{
}
}
});
}
}, 2000);
}
//Check the login details before proceeding.
public boolean checkLoginDetails(){
usernameDetail = username.getText().toString();
passwordDetail = password.getText().toString();
httptask = new HttpTask();
httptask.execute(url, usernameDetail, passwordDetail);
//if exists return true
//else return false
return false;
}
}
This is my HttpTask
public class HttpTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
String url = params[0];
String username = params[1];
String password = params[2];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
try {
httpClient.execute(httpPost);
return true;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my php script on my webserver checklogindetails.php
require_once 'db_connect.php';
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$pwdMD5 = md5($password);
$sql = "SELECT * FROM users WHERE username = '$username' AND password='$pwdMD5'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1){
echo "Log in successful";
//RETURN TRUE
}
else{
echo "Wrong username or password";
//RETURN FALSE
}
I guess the place I'm most confused about is how to constuct the php script to check the login details and how I can decide what to do based on it returning true or false.
I'd appreciate any advice or help on this subject! Many thanks
The above code looks good except that you are missing the last step.
Returning something from the PHP and then reading it in the app.
I would suggest changing the output of the PHP to something easier to parse/maintain like "OK" and "ERROR"
Then add the following code to the HttpTask.
final HttpResponse response = httpClient.execute(httpPost, localContext);
if (response != null)
{
// parse response
final HttpEntity entity = response.getEntity();
if (entity == null)
{
// response is empty, this seems an error in your use case
if (BuildConfig.DEBUG)
{
Log.d(HttpClient.TAG, "Response has no body"); //$NON-NLS-1$
}
}
else
{
try
{
// convert response to string
this.mResponseAsString = EntityUtils.toString(entity);
if (BuildConfig.DEBUG)
{
Log.d(HttpClient.TAG, "Response: " + this.mResponseAsString); //$NON-NLS-1$
}
// parse the string (assuming OK and ERROR as possible responses)
if (this.mResponseAsString != null && this.mResponseAsString.equals("OK")
{
// add happy path code here
}
else
{
// add sad path here
}
}
catch (final ParseException e)
{
Log.e(HttpClient.TAG, e.getMessage(), e);
}
catch (final IOException e)
{
Log.e(HttpClient.TAG, e.getMessage(), e);
}
}
this.mResponseCode = response.getStatusLine().getStatusCode();
}
Personally I would also refactor the "OK" in the HttpTask to a constant (for easy reading and maintaining) and also refactor most the HTTP based code to some kind of base class or utility class so you can reuse it.
I'm creating a AsyncTask to login user to a server.
The login works fine, but the ProgressDialog does not show until the end of the process.
As soon as the user taps the button, the UI freezes, and my dialog does not show up.
I appreciate any help. Here's my code.
public class MyApp extends Activity {
private ProgressDialog dialogo = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button loginButton = (Button) findViewById(R.id.btnLogin);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String webAddress = preferencias.getString("webAddress", "");
if (webAddress.isEmpty()) {
Toast.makeText(getBaseContext(), "Please, configure a Web Address.", Toast.LENGTH_LONG).show();
} else {
EditText edtUsername = (EditText) findViewById(R.id.edtUsername);
EditText edtPassword = (EditText) findViewById(R.id.edtPassword);
HashMap<String, String> parametros = new HashMap<String, String>();
parametros.put("username", edtUsername.getText().toString());
parametros.put("password", edtPassword.getText().toString());
Requisicao requisicao = new Requisicao(parametros);
AsyncTask<String, Void, String> resposta = requisicao.execute(webAddress + "/login");
try {
Toast.makeText(getBaseContext(), resposta.get(), Toast.LENGTH_LONG).show();
} catch (InterruptedException e) {
Toast.makeText(getBaseContext(), "InterruptedException (login)", Toast.LENGTH_LONG).show();
} catch (ExecutionException e) {
Toast.makeText(getBaseContext(), "ExecutionException (login)", Toast.LENGTH_LONG).show();
}
}
}
});
ImageView engrenagem = (ImageView) findViewById(R.id.imgEngrenagem);
engrenagem.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent preferenciasActivity = new Intent(getBaseContext(), Preferencias.class);
startActivity(preferenciasActivity);
}
});
}
public class Requisicao extends AsyncTask<String, Void, String> {
private final HttpClient clienteHttp = new DefaultHttpClient();
private String resposta;
private HashMap<String, String> parametros = null;
public Requisicao(HashMap<String, String> params) {
parametros = params;
}
#Override
protected void onPreExecute() {
dialogo = new ProgressDialog(MyApp.this);
dialogo.setMessage("Aguarde...");
dialogo.setTitle("Comunicando com o servidor");
dialogo.setIndeterminate(true);
dialogo.setCancelable(false);
dialogo.show();
}
#Override
protected String doInBackground(String... urls) {
byte[] resultado = null;
HttpPost post = new HttpPost(urls[0]);
try {
ArrayList<NameValuePair> paresNomeValor = new ArrayList<NameValuePair>();
Iterator<String> iterator = parametros.keySet().iterator();
while (iterator.hasNext()) {
String chave = iterator.next();
paresNomeValor.add(new BasicNameValuePair(chave, parametros.get(chave)));
}
post.setEntity(new UrlEncodedFormEntity(paresNomeValor, "UTF-8"));
HttpResponse respostaRequisicao = clienteHttp.execute(post);
StatusLine statusRequisicao = respostaRequisicao.getStatusLine();
if (statusRequisicao.getStatusCode() == HttpURLConnection.HTTP_OK) {
resultado = EntityUtils.toByteArray(respostaRequisicao.getEntity());
resposta = new String(resultado, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
} catch (Exception e) {
}
return resposta;
}
#Override
protected void onPostExecute(String param) {
dialogo.dismiss();
}
}
}
Try to comment out resposta.get() call in the button listener. I guess it just blocks the main UI thread untill the task is finished.
Couple things. First of all, don't make an instance for ASyncClass because you can only ever call it once, as per the android documentation. So execute like this: new Requisicao().execute(webAddress + "/login");
Also, instead of calling requisicao.get(), which will, again according to documentation "Waits if necessary for the computation to complete, and then retrieves its result" (also known as blocking), from within your async class add an override:
protected void onProgressUpdate(Long... progress) {
CallBack(progress[0]); // for example
}
Where CallBack is a function in your UI thread which will handle processing your progress long, or string, or whatever else you want to throw back. Mind you, your ASync class will have to be defined within the UI class instead of separately.
move your
private ProgressDialog dialogo = null;
into the AsyncTask's fields as you did it with HTTPClient because you don't
seem to use it anywhere and
try to create your dialog in the constructor
public Requisicao(HashMap<String, String> params) {
parametros = params;
dialogo = new ProgressDialog(MyApp.this);
}
in postExecute
if (dialogo .isShowing()) {
dialogo .dismiss();
}
hope it helps.