Login does not work with AsyncTask in Android

0

I am sitting an small Android app to check the user login information. I have been working on this with no luck. I appreciate if someone can help me with this. Thanks in advance. I am getting this error login_invalid_error with an okay button under.

this is my php.

    <?php 
    $emailAddress;
    $password;

    // Change the following settings based on your db
    // Im assuming your are using MySQL
    $dbHost = "localhost";

    $dbUser = "root";
    $dbPassword = "123456";
    $userTableName = "tb_users";

    // check if params 'emailAddress' and 'password' are set.
    if (isset($_REQUEST['emailAddress']) &&
        isset($_REQUEST['password']))
    {
        $con =  mysql_connect($dbHost ,$dbUser,$dbPassword);
        if(!$con) die('Error ' . mysqli_connect_error);

        mysql_select_db("andrioldlogin",$con) or die("can't select the database");
        $emailAddress = $_REQUEST['emailAddress'];
        // Compares passwords based on md5 encryption.
        $password = $_REQUEST['password'];



        // SQL statement assuming your user table has fields 
        // "email_address" and "password"
        $sql =  "SELECT id FROM tb_users WHERE email_address = '$emailAddress' AND password = '$password'";
        $result = mysql_query($sql);

        if($result)
        {
            $row = mysql_num_rows($result);
            if($row == 1)
            {
                // 202 header code response if there is a matching row.
                header("Status: 202 Accepted");
                // $row[0] will be id from user logging in
                die($row[0]);           
            }
            else
            {
                header("Status: 401 Unauthorized");
                echo "Error logging in 1.";
            }
        }
        else
        {
            header("Status: 401 Unauthorized");
            echo "Error logging in 2.";
        }
    }
    // if values are unset
    else
    {
        header("Status: 401 Unauthorized");
        echo "Invalid Data.";
    }

this is my MainActivity.java

public class MainActivity extends Activity {
    protected static final int LOGIN_REQUEST_CODE = 0;
    protected static final int RECOVER_REQUEST_CODE = 1;
    protected static final int REGISTER_REQUEST_CODE = 2;
    public static final int LOGOUT_RESULT_CODE = 2;

    SharedPreferences sharedPreferences;
    private EditText etEmailAddress;
    private EditText etPassword;
    private Button bLogin;

    private final Class<?> LOGIN_DESTINATION = DestinationActivity.class; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sharedPreferences = getPreferences(MODE_PRIVATE);

        super.onCreate(savedInstanceState);

        // check if user is logged in already
        if( sharedPreferences.getBoolean("user_logged_in", false))
        {
            // user is logged in, bypass activity
            startActivityForResult(
                new Intent(MainActivity .this, LOGIN_DESTINATION), 
                LOGIN_REQUEST_CODE);
        }

        setContentView(R.layout.activity_main);
        bLogin = (Button) findViewById(R.id.button1);
        etEmailAddress = (EditText) findViewById(R.id.editText1); 
        etPassword = (EditText) findViewById(R.id.editText2);

        bLogin.setOnClickListener(loginOnClickListener);

     }

    protected OnClickListener loginOnClickListener = new OnClickListener()
    {
        public void onClick(View v) 
        {
            ProgressDialog progressDialog = new ProgressDialog(MainActivity .this);
            progressDialog.setMessage("Logging in...");
            progressDialog.setCancelable(false);

            LoginTask loginTask = new LoginTask(MainActivity.this, progressDialog);
            loginTask.execute(
                etEmailAddress.getText().toString(), 
                etPassword.getText().toString());
        }
    };

    public void showLoginError(String result)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setMessage(R.string.login_invalid_error);
        AlertDialog alert = builder.create();
        alert.setCancelable(false);
        alert.show();
    }

    // do some stuff after user logs in
        public void login(int id)
        {
            sharedPreferences.edit().putBoolean("user_logged_in", true).commit();
            startActivityForResult(
                new Intent(MainActivity.this, LOGIN_DESTINATION), 
                LOGIN_REQUEST_CODE);
        }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

LoginTask.java

    package com.example.loginwithasynctask;

    import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

    import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

    import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

    public class LoginTask extends AsyncTask<String, Void, Integer> {

        private ProgressDialog progressDialog;
        private MainActivity  activity;
        private String id = "";

        public LoginTask(MainActivity  activity, ProgressDialog progressDialog)
        {
            this.activity = activity;
            this.progressDialog = progressDialog;
        }

        @Override
        protected void onPreExecute()
        {
            progressDialog.show();
        }

        @Override
        protected Integer doInBackground(String... arg0) 
        {
            String result = "";
            int responseCode = 0;
            try 
            {
                HttpClient client = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://192.168.1.139/loginwithasynctask.php");

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("emailAddress", arg0[0]));
                    nameValuePairs.add(new BasicNameValuePair("password", arg0[1]));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                int executeCount = 0;
                HttpResponse response;
                do
                {
                    //progressDialog.setMessage("Logging in.. ("+(executeCount+1)+"/5)");
                    // Execute HTTP Post Request
                    executeCount++;
                    response = client.execute(httppost);
                    responseCode = response.getStatusLine().getStatusCode();                        
                    // If you want to see the response code, you can Log it
                    // out here by calling:
                    Log.d("Sabawon You are here bro", "statusCode: " + responseCode);
                } while (executeCount < 5 && responseCode == 408);

                BufferedReader rd = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));

                String line;
                while ((line = rd.readLine()) != null)
                {
                    result = line.trim();
                     Log.d("result is ", result);
                }
                id = result;
            }
            catch (Exception e) {
                responseCode = 408;

            }
            return responseCode;
        }

        @Override
        protected void onPostExecute(Integer headerCode)
        {
            try{
            int executeCount = 0;
            progressDialog.setMessage("Logging in.. ("+(executeCount+1)+"/5)");

            //Log.d("Sabawon You are here bro", "statusCode: " + responseCode);
            progressDialog.dismiss();
            }
            catch (Exception e) {

                e.printStackTrace();
            }

            if(headerCode == 202)
                activity.login((Integer.parseInt(id)));
            else
                activity.showLoginError("");
        }
    }

This is my LogCat....

05-17 14:18:34.626: D/InputEventConsistencyVerifier(1644): KeyEvent: ACTION_UP but key was not down.
05-17 14:18:34.626: D/InputEventConsistencyVerifier(1644): android.widget.EditText@41203828

05-17 14:18:34.626: D/InputEventConsistencyVerifier(1644):  0: sent at 15560804000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_M, scanCode=50, metaState=0, flags=0x8, repeatCount=0, eventTime=15560804, downTime=15560804, deviceId=0, source=0x101 }

05-17 14:18:34.736: D/InputEventConsistencyVerifier(1644): KeyEvent: ACTION_UP but key not down.
05-17 14:18:34.736: D/InputEventConsistencyVerifier(1644): android.widget.EditText@41203828

05-17 14:18:34.736: D/InputEventConsistencyVerifier(1644):   0: sent at 15560942000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=15560942, downTime=15560804, deviceId=0, source=0x101 }

05-17 14:18:34.736: D/InputEventConsistencyVerifier(1644):   -- recent events --
05-17 14:18:34.736: D/InputEventConsistencyVerifier(1644):   1: sent at 15560804000000, (unhandled) KeyEvent { action=ACTION_UP, keyCode=KEYCODE_M, scanCode=50, metaState=0, flags=0x80000008, repeatCount=0, eventTime=15560804, downTime=15560804, deviceI source=0x101 }
05-17 14:18:44.369: D/dalvikvm(1644): GC_CONCURRENT freed 263K, 5% free 8168K/8519K, paused 135ms+82ms, total 348ms
05-17 14:18:46.867: D/Sabawon You are here bro(1644): statusCode: 200
05-17 14:18:46.927: W/System.err(1644): java.lang.NumberFormatException: Invalid int: ""
05-17 14:18:46.927: W/System.err(1644): java.lang.Integer.invalidInt(Integer.java:138)
05-17 14:18:46.937: W/System.err(1644):at java.lang.Integer.parseInt(Integer.java:359)
05-17 14:18:46.937: W/System.err(1644): at java.lang.Integer.parseInt(Integer.java:332)
05-17 14:18:46.937: W/System.err(1644):com.example.loginwithasynctask.LoginTask.doInBackground(LoginTask.java:75)
05-17 14:18:46.937: W/System.err(1644):atcom.example.loginwithasynctask.LoginTask.doInBackground(LoginTask.jav:1)
05-17 14:18:46.937: W/System.err(1644): at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-17 14:18:46.937: W/System.err(1644):at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-17 14:18:46.937: W/System.err(1644): at java.util.concurrent.FutureTask.run(FutureTask.java:137)05-17 14:18:46.998: W/System.err(1644):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-17 14:18:46.998: I/Choreographer(1644): Skipped 31 frames!  The application may be doing too much work on its main thread.

05-17 14:18:47.007: W/System.err(1644): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)

05-17 14:18:47.067: W/System.err(1644): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)

05-17 14:18:47.067: W/System.err(1644): at java.lang.Thread.run(Thread.java:856)
05-17 14:18:47.147: I/Choreographer(1644): Skipped 35 frames!  The application may be doing too much work on its main thread.

05-17 14:18:47.477: I/Choreographer(1644): Skipped 82 frames!  The application may be doing too much work on its main thread.

05-17 14:18:47.807: I/Choreographer(1644): Skipped 84 frames!  The application may be doing too much work on its main thread.
java
php
android
asked on Stack Overflow May 17, 2013 by 250Andriod • edited May 23, 2013 by 250Andriod

1 Answer

0

In doInBackground you cannot update any UI (basic Async fundamentals). So these lines progressDialog.setMessage("Logging in.. ("+(executeCount+1)+"/5)"); and Log.d("Sabawon You are here bro", "statusCode: " + responseCode); and e.printStackTrace(); need to go into a doProgressUpdate or a doPostExecute

Please read up here and here

answered on Stack Overflow May 18, 2013 by Siddharth • edited May 23, 2017 by Community

User contributions licensed under CC BY-SA 3.0