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.
  • 2
    post some relevant code and describe the problem more clearly – Raghunandan May 17 '13 at 18:31
  • @250Andriod when you are asking some question please show your research efforts done by you to figure out this problem don't just directly ask for codes. Like see this post http://stackoverflow.com/questions/15683952/pop-up-window-over-android-native-incoming-call-screen-like-true-caller-android – Nikhil Agrawal May 17 '13 at 18:34
  • Sorry guys...I posted my code and chatlog. First of all I had no AsyncTask...then I researched and find how to put my code in Asyctask and now it does not work and I get an error as soon as I click the login button. – 250Andriod May 17 '13 at 18:48
  • 1
    You messed up again. You have put in incorrect code. Where is LoginTask.java – Siddharth May 17 '13 at 18:49
  • You've posted your activity code twice, instead of your ASyncTask code – Thiago Moura May 17 '13 at 18:49
  • @Siddharth You should be able to see my AsyncTask code above. – 250Andriod May 17 '13 at 18:54
  • progressDialog.setMessage("Logging in.. ("+(executeCount+1)+"/5)"); you should not update ui from doInbackground() – Raghunandan May 17 '13 at 19:00
  • clearly you are getting the NumberFormatException in your doInBackground() + I agree with @Raghunandan you should not update UI from doInBackground like this, you need to implement onProgressUpdate() method – Robin Chander May 17 '13 at 19:02
  • Thanks Raghunandan for your advice. But I am a new comer to android...Where should I put that line then? – 250Andriod May 17 '13 at 19:02
  • you check the comment by @RobinChander and this id = Integer.parseInt(result);. result is a string not something like "23" it might be a string like "abc". hence the NumberFormatException. Log the result and check – Raghunandan May 17 '13 at 19:04
  • Thanks @Robin can you tell me where I should put the code then. Thanks – 250Andriod May 17 '13 at 19:06
  • I placed a log and it shows a message from my php "Error loggin in 1" from my php ,,,how should then I change this to string,,,but I have a header("status 202 accepted)...how should I return string that it should say you are logged in. Thank you guys..I really want to learn and I thrive to do so but your help and support will help to acomplish this. – 250Andriod May 17 '13 at 19:24
  • Just a shot in the dark, but you used the name "andrioldlogin" in your Php code. Was that a misspelling, or is that really the name of your database? – Edward Falk May 17 '13 at 20:11
  • @Edward, Sorry, I that is my database name and it matches my database name as well. – 250Andriod May 20 '13 at 12:09

1 Answers1

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

Community
  • 1
  • 1
Siddharth
  • 9,349
  • 16
  • 86
  • 148