1

I use the codes in this page, just change some variables and if else condition. I didn't change the JSONParser, though. How to implement Login with HttpURLConnection and PHP server in Android

//these are the codes i use

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;


public class Startup_Activity extends Activity {

    EditText patid1, patpw1;
    Button patli1;
    TextView patfp1;
    String patientID, patientPass;

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

        patid1 = (EditText) findViewById(R.id.pat_id);
        patpw1 = (EditText) findViewById(R.id.pat_pw);
        patli1 = (Button) findViewById(R.id.pat_li);
        patfp1 = (TextView) findViewById(R.id.pat_fp);
    }

    public void login(View x) {
        patientID = patid1.getText().toString();
        patientPass = patpw1.getText().toString();
        LoginOperation loginOperation = new LoginOperation();
        loginOperation.execute();
    }

    public void forgot_password(View y) {
        Intent fp = new Intent(this, Forgotpassword_Activity.class);
        startActivity(fp);
    }

    private class LoginOperation extends AsyncTask<String, String, JSONObject> {

        JSONParser jsonParser = new JSONParser();
        ProgressDialog pd = new ProgressDialog(Startup_Activity.this);

        private static final String LOGIN_URL = "http://localhost/dc/patient_login.php";

        private static final String TAG_SUCCESS = "success";
        private static final String TAG_MESSAGE = "message";

        @Override
        protected void onPreExecute() {
            pd.setMessage("Logging in");
            pd.show();
        }

        Boolean result = false;

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

            try {

                HashMap<String, String> params = new HashMap<>();
                params.put("patientID", args[0]);
                params.put("patientPass", args[1]);

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

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

                if (json != null) {
                    Log.d("JSON result", json.toString());

                    return json;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject json) {

            int success = 0;
            String message = "";

            if (pd != null && pd.isShowing()) {
                pd.dismiss();
            }

            if (json != null) {
                Toast.makeText(Startup_Activity.this, json.toString(),
                        Toast.LENGTH_LONG).show();

                try {
                    success = json.getInt(TAG_SUCCESS);
                    message = json.getString(TAG_MESSAGE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if (success == 2) {
                Log.d("Success!", message);
                Intent x = new Intent(this, Securityquestion_Activity.class);
                 finish();
                 startActivity(x);

            }
            else if (success == 1) {
                Log.d("Success!", message);
                Intent x = new Intent(this, Home_Activity.class);
                 finish();
                 startActivity(x);
            else{
                Log.d("Failure", message);
            }
        }
    }


}




//for JSONParser
package com.example.edmar.drgilgarciadentalclinic;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

Log.d("JSON Parser", "result: " + result.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

        conn.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jObj;
    }
}

these are the exceptions and system errors:

02-29 22:18:05.047    1507-1507/com.example.edmar.drgilgarciadentalclinic D/dalvikvm﹕ Late-enabling CheckJNI
02-29 22:18:05.911    1507-1507/com.example.edmar.drgilgarciadentalclinic D/libEGL﹕ loaded /system/lib/egl/libEGL_genymotion.so
02-29 22:18:05.935    1507-1507/com.example.edmar.drgilgarciadentalclinic D/﹕ HostConnection::get() New Host Connection established 0xb9624ff8, tid 1507
02-29 22:18:05.963    1507-1507/com.example.edmar.drgilgarciadentalclinic D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_genymotion.so
02-29 22:18:05.971    1507-1507/com.example.edmar.drgilgarciadentalclinic D/libEGL﹕ loaded /system/lib/egl/libGLESv2_genymotion.so
02-29 22:18:06.143    1507-1507/com.example.edmar.drgilgarciadentalclinic W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
02-29 22:18:06.155    1507-1507/com.example.edmar.drgilgarciadentalclinic E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache
02-29 22:18:06.183    1507-1507/com.example.edmar.drgilgarciadentalclinic E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
02-29 22:18:06.187    1507-1507/com.example.edmar.drgilgarciadentalclinic D/OpenGLRenderer﹕ Enabling debug mode 0
02-29 22:18:27.471    1507-1507/com.example.edmar.drgilgarciadentalclinic D/dalvikvm﹕ GC_FOR_ALLOC freed 136K, 11% free 2805K/3124K, paused 6ms, total 7ms
02-29 22:18:27.499    1507-1507/com.example.edmar.drgilgarciadentalclinic D/dalvikvm﹕ GC_FOR_ALLOC freed 4K, 11% free 2899K/3224K, paused 3ms, total 13ms
02-29 22:18:27.579    1507-1507/com.example.edmar.drgilgarciadentalclinic I/dalvikvm-heap﹕ Grow heap (frag case) to 4.080MB for 1127532-byte allocation
02-29 22:18:27.587    1507-1516/com.example.edmar.drgilgarciadentalclinic D/dalvikvm﹕ GC_FOR_ALLOC freed <1K, 8% free 4000K/4328K, paused 9ms, total 9ms
02-29 22:18:27.647    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
02-29 22:18:27.739    1507-1507/com.example.edmar.drgilgarciadentalclinic W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
02-29 22:18:27.843    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at com.example.edmar.drgilgarciadentalclinic.Startup_Activity$LoginOperation.doInBackground(Startup_Activity.java:74)
02-29 22:18:27.875    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at com.example.edmar.drgilgarciadentalclinic.Startup_Activity$LoginOperation.doInBackground(Startup_Activity.java:50)
02-29 22:18:27.887    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-29 22:18:27.919    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-29 22:18:27.947    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-29 22:18:27.987    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-29 22:18:27.987    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-29 22:18:27.987    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
02-29 22:18:28.195    1507-1507/com.example.edmar.drgilgarciadentalclinic D/Failure﹕ [ 02-29 22:18:28.287   411:  802 W/InputMethodManagerService ]
    Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@529e327c attribute=null, token = android.os.BinderProxy@5294e9f4

Server Side PHP:

<?php

include 'connection.php';
header('Content-Type: application/json');

    if(isset($_POST['patientID'], $_POST['patientPass'])){
    $patient_id = $_POST['patientID'];
    $patient_pass = $_POST['patientPass'];


    if(!empty($patient_id) && !empty($patient_pass))
    {
        //$encrypted_pass = md5($patient_pass);

        $query = "Select * From patients Where patientid='$patient_id' and patientpassword='$patient_pass'"; 
        $result = $db->query($query);

        if(mysqli_num_rows($result)>0){
            $security_check = mysqli_fetch_array($result,MYSQLI_ASSOC);
            if($security_check['patientsecurity'] == NULL || $security_check['patientanswer'] == NULL){
                $json['success'] = 2;
                $json['message'] = 'Your account will be confirmed with your security question and answer.';
                echo json_encode($json);
                mysqli_close($db);
            }
            else{
                $json['success'] = 1;
                $json['message'] = 'Successfully logged in.';
                echo json_encode($json);
                mysqli_close($db);
            }
        }
        else{
            $json['success'] = 0;
            $json['message'] = 'Incorrect Patient ID or Password.';
            echo json_encode($json);
            mysqli_close($db);

        }
    }
    else
    {
        $json['message']="You must complete all required fields.";
        echo json_encode($json);
        mysqli_close($db);
    }

}
?>
Community
  • 1
  • 1
Elle
  • 15
  • 6

3 Answers3

0

Here is your culprit

02-29 22:18:27.647    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ java.lang.ArrayIndexOutOfBoundsException: length=0; index=0

And the only arrays I could find in the code are

params.put("patientID", args[0]);
params.put("patientPass", args[1]);

And based on this stack trace, now I did not count the line number but am pretty sure

02-29 22:18:27.739    1507-1507/com.example.edmar.drgilgarciadentalclinic W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
02-29 22:18:27.843    1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at com.example.edmar.drgilgarciadentalclinic.Startup_Activity$LoginOperation.doInBackground(Startup_Activity.java:74)

Should direct you to the same two lines. Put a break point and debug.

And going farther back

loginOperation.execute();

which should pass the args has nothing in it, leading to the cause of the error.

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

It never received the args.

I wanted you to figure it out first.

loginOperation.execute(arg1, arg2)

Should resolve it.

Khanal
  • 788
  • 6
  • 14
  • Thanks for your response @Khanal. So, you mean I should type it like this: loginOperation.execute(patientID, patientPass); ? – Elle Mar 01 '16 at 05:14
  • And yes sorry just saw it. Gotta make the stack trace your bff. :) – Khanal Mar 01 '16 at 05:23
  • Thank you so much! But there's still System errors about http connection. – Elle Mar 01 '16 at 05:27
  • Could you update the question with the stack trace, we will figure it out. – Khanal Mar 01 '16 at 05:28
  • `03-01 00:16:37.547 10945-10964/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 80) after 15000ms: isConnected failed: ECONNREFUSED (Connection refused)` – Elle Mar 01 '16 at 05:28
  • Your server is not running. Open a browser and go to localhost/ - what do you see? – Khanal Mar 01 '16 at 05:29
  • when i typed localhost, localhost/dashboard/ that says 'welcome to xampp' appeared. – Elle Mar 01 '16 at 05:31
  • ok are you using a virtual android device? This will be out of scope for this topic but I can give you some pointers. – Khanal Mar 01 '16 at 05:33
  • yes, i'm using genymotion. please give me some pointers, thanks a lot. – Elle Mar 01 '16 at 05:34
  • What you need to do is find the ip address for your computer that is running the server. You need to use the local ip something along the lines of 192.168.1.1 Then you need to replace localhost with that ip address on your urls. Since Genymotion uses virtual box, it should work. Let me know if that works. – Khanal Mar 01 '16 at 05:40
  • Here is more detail on it http://stackoverflow.com/questions/20257266/how-to-access-localhost-from-a-genymotion-android-emulator also I assumed that you only had to type in localhost and and localhost:[port]. If you had to type in the port on the browser, the same would still apply to the web request. – Khanal Mar 01 '16 at 05:42
  • Haha! I did it! THANK YOU SO MUCH!^^ – Elle Mar 01 '16 at 07:39
0

You have encounter ArrayIndexOutOfBoundsException because you may have not pass second argument

java.lang.ArrayIndexOutOfBoundsException: length=0; index=0

Make sure your arguments not exceed length of array.

Here, make sure you array of length 2.

params.put("patientID", args[0]);
params.put("patientPass", args[1]);
mubeen
  • 813
  • 2
  • 18
  • 39
0

Change login method in your code.You have to pass parameters with the Async task execute call. Then only you will able to get those value in the doInbackground method of Async call.

public void login(View x) {
        patientID = patid1.getText().toString();
        patientPass = patpw1.getText().toString();
        String[] args = {patientID ,patientPass };
        LoginOperation loginOperation = new LoginOperation();
        loginOperation.execute(args);
    }

Check like this buddy! Happy coding

Sreejin
  • 151
  • 7