0

I've a login in android & I've mentioned Code for it. This is the PHP function file that is written in the IIS server. I get the login success as 1 which indicates login works. But, I can't go the next activity after login.

<?php

require("config.inc.php");

if (!empty($_POST)) {

    $query = "SELECT * FROM bpusers WHERE Email= :email ";

    $query_params = array( ':email' => $_POST['email']   );

    try {
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {

        $response["success"] = 0;
        $response["message"] = "Database Error. Please Try Again!";
        die(json_encode($response));
    }

    $validated_info = false;

    //fetching all the rows from the query
    $row = $stmt->fetch();
    if ($row) {

        if ($_POST['password'] === $row['Password']) {

        try {
            $login_ok = true;
        }
        catch (PDOException $ex) {

            $response["success"] = 0;
            $response["message"] = "Cannot register with GCM". $ex->getMessage();
            die(json_encode($response));

            }
        }
    }

    if ($login_ok) {
        $response["success"] = 1;
        $response["message"] = "Login successful to php!";

        $response["email"] = $row[Email];
            //$response["phone"] = $row[Phone_No];
            //$response["nic"] = $row[NIC];

        die(json_encode($response));
    } else {
        $response["success"] = 0;
        $response["message"] = "Invalid Credentials!". $ex->getMessage();;
        die(json_encode($response));
    }
} 
?> 

login.java file.

package cdap.park;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.RequestParams;

import cdap.billpark.dbconn.JSONParser;
import android.R.string;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements View.OnClickListener {

    private EditText emailField, passwordField;
    private Button btnlogin;
    private Button btnforgotPwd;
    private ProgressDialog pDialog;
    String dbemail;
    String passengerID;
    JSONParser jsonParser = new JSONParser();
    private static final String LOGIN_URL = "http://192.168.1.4/park/passengerLogin.php";
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";

    public Login() {
    }

    RequestParams params1 = new RequestParams();

    Context applicationContext;

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    AsyncTask<Void, Void, String> createRegIdTask;

    public static final String EMAIL_ID = "emailId";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        SharedPreferences pref = getApplicationContext().getSharedPreferences(  "Location", 0);
        pref.edit().clear().commit();

        SharedPreferences prefBook = getApplicationContext().getSharedPreferences("BookLocation", 0);
        prefBook.edit().clear().commit();

        btnlogin = (Button) findViewById(R.id.button);
        // btnlogin.setOnClickListener(this);

        btnlogin.setOnClickListener((OnClickListener) this);
        applicationContext = getApplicationContext();
        // getSupportActionBar().hide();

        emailField = (EditText) findViewById(R.id.editTextEmail);
        passwordField = (EditText) findViewById(R.id.editTextPassword);
        // btnforgotPwd = (Button)findViewById(R.id.button2);

        /*
         * btnforgotPwd.setOnClickListener(new View.OnClickListener() {
         * 
         * @Override public void onClick(View v) { Intent intent = new
         * Intent(Login.this, ResetPassword.class); startActivity(intent); } });
         */
        emailField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (emailField.getText().length() == 0) {

                    emailField.setError("Email Field Cannot be empty");

                }

                // int x = email.indexOf("@");
                // int y = email.indexOf(".");

            }
        });

        passwordField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                String email = emailField.getText().toString();
                if (!(email.matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+"))) {

                    emailField.setError("Email is incorrect");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (passwordField.getText().length() == 0) {

                    passwordField.setError("Password Cannot be empty");
                }

                if (passwordField.getText().length() <= 2) {

                }
            }
        });
    }

    class PassengerLogin extends AsyncTask<String, String, String> {

        boolean failure = false;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        private boolean isValidPassword(String pass) {
            if (pass != null && pass.length() >= 2) {
                return true;
            }
            return false;
        }

        @Override
        protected String doInBackground(String... args) {

            int success;

            String email = emailField.getText().toString();
            String password = passwordField.getText().toString();

            String msg = "";

            try {

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("email", email));
                params.add(new BasicNameValuePair("password", password));

                Log.d("request!", "starting");

                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",     params);

                //Log.d("Login attempt", json.toString());

                success = json.getInt(TAG_SUCCESS);


                if (success == 1) {

                    dbemail = json.getString("email");
                    //Log.d("Login Successful!", json.toString());
                    Intent intent = new Intent(getApplicationContext(),     Welcome.class);
                    // Create a bundle object
                    Bundle b = new Bundle();
                    // Inserts a String value into the mapping of this Bundle
                    b.putString("email", email);
                    b.putString("password", password);
                    // Add the bundle to the intent.
                    intent.putExtras(b);
                    // start the DisplayActivity
                    startActivity(intent);
                    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                    SharedPreferences.Editor editor = pref.edit();

                    editor.putString("email", dbemail);
                    editor.commit();
                    Log.e("email", dbemail);
                    Intent i = new Intent(Login.this, Welcome.class);
                    i.putExtra("email", dbemail);
                    finish();
                    startActivity(i);
                    return json.getString(TAG_MESSAGE);
                } else {

                    Log.d("Login Failure!", json.getString(TAG_MESSAGE));

                    return json.getString(TAG_MESSAGE);

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
            if (file_url != null) {
                Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
            }

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        case R.id.button:

            new PassengerLogin().execute();
            break;
        }
    }

}

I get the following in the log cat.

11-12 01:09:43.058: D/json string(24238): Connected successfully
11-12 01:09:43.058: D/json string(24238): {"success":1,"message":"Login successful to php!","email":"ndp@gmail.com"}
11-12 01:09:43.058: E/JSON Parser(24238): Error parsing data org.json.JSONException: Value Connected of type java.lang.String cannot be converted to JSONObject
11-12 01:09:43.088: W/dalvikvm(24238): threadid=11: thread exiting with uncaught exception (group=0x41689e18)
11-12 01:09:43.118: E/AndroidRuntime(24238): FATAL EXCEPTION: AsyncTask #1
11-12 01:09:43.118: E/AndroidRuntime(24238): Process: cdap.park, PID: 24238
11-12 01:09:43.118: E/AndroidRuntime(24238): java.lang.RuntimeException: An error occured while executing doInBackground()
11-12 01:09:43.118: E/AndroidRuntime(24238):    at android.os.AsyncTask$3.done(AsyncTask.java:300)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at java.lang.Thread.run(Thread.java:864)
11-12 01:09:43.118: E/AndroidRuntime(24238): Caused by: java.lang.NullPointerException
11-12 01:09:43.118: E/AndroidRuntime(24238):    at cdap.park.Login$PassengerLogin.doInBackground(Login.java:189)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at cdap.park.Login$PassengerLogin.doInBackground(Login.java:1)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
11-12 01:09:43.118: E/AndroidRuntime(24238):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
11-12 01:09:43.118: E/AndroidRuntime(24238):    ... 4 more
11-12 01:09:43.689: D/HardwareRenderer(24238): startTrimMemory(level >=TRIM_MEMORY_COMPLETE)
11-12 01:09:43.779: E/WindowManager(24238): android.view.WindowLeaked: Activity cdap.park.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e1cb58 V.E..... R......D 0,0-684,192} that was originally added here
11-12 01:09:43.779: E/WindowManager(24238):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:393)
11-12 01:09:43.779: E/WindowManager(24238):     at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
11-12 01:09:43.779: E/WindowManager(24238):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
11-12 01:09:43.779: E/WindowManager(24238):     at android.app.Dialog.show(Dialog.java:291)
11-12 01:09:43.779: E/WindowManager(24238):     at cdap.park.Login$PassengerLogin.onPreExecute(Login.java:157)
11-12 01:09:43.779: E/WindowManager(24238):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
11-12 01:09:43.779: E/WindowManager(24238):     at android.os.AsyncTask.execute(AsyncTask.java:535)
11-12 01:09:43.779: E/WindowManager(24238):     at cdap.park.Login.onClick(Login.java:258)
11-12 01:09:43.779: E/WindowManager(24238):     at android.view.View.performClick(View.java:4480)
11-12 01:09:43.779: E/WindowManager(24238):     at android.view.View$PerformClick.run(View.java:18686)
11-12 01:09:43.779: E/WindowManager(24238):     at android.os.Handler.handleCallback(Handler.java:733)
11-12 01:09:43.779: E/WindowManager(24238):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-12 01:09:43.779: E/WindowManager(24238):     at android.os.Looper.loop(Looper.java:157)
11-12 01:09:43.779: E/WindowManager(24238):     at android.app.ActivityThread.main(ActivityThread.java:5872)
11-12 01:09:43.779: E/WindowManager(24238):     at java.lang.reflect.Method.invokeNative(Native Method)
11-12 01:09:43.779: E/WindowManager(24238):     at java.lang.reflect.Method.invoke(Method.java:515)
11-12 01:09:43.779: E/WindowManager(24238):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
11-12 01:09:43.779: E/WindowManager(24238):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
11-12 01:09:43.779: E/WindowManager(24238):     at dalvik.system.NativeStart.main(Native Method)
Harindra Singh
  • 371
  • 2
  • 6
  • 17

1 Answers1

1

Like the NullPointerException says, your getInt fails. You should simulate the request by hand and look at the response JSON to see what's wrong.

On a somewhat related note; you are trying to start the new activity in your doInBackground method. This method is not intended for this, as activities can only be started from the main thread. You should do the start your activity in the onPostExecute method.

And finally, it looks like you save your passwords in plain text in your database. This is generally a bad idea, as an attacker could discover all passwords, should they gain access. This answer provides a clear description of how you should do it.

Community
  • 1
  • 1
Bert Peters
  • 1,505
  • 13
  • 30