1

I followed a youtube tutorial about connecting a MyQSL DB which runs using wamp server (on windows) to Android app. (The video link is: https://www.youtube.com/watch?v=eldh8l8yPew )

In my Android Studio code , I made a class (named "BackgroundWorker") that extends AsyncTask and should handle the communication to a PHP file that connect to the DB.

in order to open a writing channel to the DB I used BufferedWriter and OutputStream that connects to a httpURLConnection object which has the URL of my relevant php script that sits in my www folder of WAMPSERVER.

After this long itroduction , my problem is that I get IOException when trying to execute the following line:

OutputStream outputStream = httpURLConnection.getOutputStream();

I've prety much copied the whole code from the video tutorial so I doubt that there is any problem with it. I'm thinking more to the direction of the URL setting - my URL object gets the the String that have the address:

String loginURL = "http://10.0.2.2/login.php";

where "login.php" is my php script that sits in the www folder of wamp server. I understood that 10.0.0.2 is kind of a default address that represnts localhost in Android Emulators , how ever I'm using Genymotion Emulator so maybe this isn't the right address? I also tried to put all the other IP adresses that I saw when running IPCONFIG but none change the result.

I'm not so good in dubugging so I used Toasts and PublishProgress method of AsyncTask in order to find and isolate the IOException.

Here is parts of my code which I think that might be relevant to the IOException:

My BackgroundWorker class (That extends AsyncTask):

public class BackgroundWorker extends AsyncTask <String , Integer , String> {
    Context context;
    AlertDialog alertDialog;
    public BackgroundWorker(Context userContext) {
        this.context = userContext;
    }

    @Override
    protected String doInBackground(String... params) {
        // Reading the arguments in the order I sent them in MainActivity
        String username = params[0];
        String pass = params[1];
        String type = params[2];

        // Making structure for updating during the wat using Toasts (and showing the first one
        int progressValue = 0;          // Before if
        publishProgress(progressValue);
        // Initial String that will hold the text to read from server
        String result = "";
        // Initial the URL String , the IP address if standart for Android LocalHost
        String loginURL = "http://10.0.2.2/login.php";
        if (type.equals("login")) {

            progressValue++;    //1
            publishProgress(progressValue);

            try {
                URL url = new URL(loginURL);

                progressValue++;    //2
                publishProgress(progressValue);

                // Building the HttpUrlConnection object
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                progressValue++;    //3
                publishProgress(progressValue);

                // Building the writing infrastructure
                // IOException occurs after the commit of the next line
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));

                progressValue++;    //4
                publishProgress(progressValue);

                // Building the message to the PHP script
                String post_data = URLEncoder.encode("user_name" , "UTF-8") + "=" + URLEncoder.encode(username , "UTF-8")
                        + "&" + URLEncoder.encode("user_pass" , "UTF-8") + "=" + URLEncoder.encode(pass , "UTF-8");

                progressValue++;    //5
                publishProgress(progressValue);

                // Writing the data
                bufferedWriter.write(post_data);

                progressValue++;    //6
                publishProgress(progressValue);

                // Closing all writing structures
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                // Building the Reading Infrastructure
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream , "iso-8859-1"));

                // Reading the data
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
                // Closing all reading structures
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();


            } catch (MalformedURLException e) {
                e.printStackTrace();
                progressValue = 10;
                publishProgress(progressValue);
            } catch (IOException e) {
                progressValue = 11;
                publishProgress(progressValue);
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        int progressValue = values[0];
        // Before IF statement
        if (progressValue == 0) Toast.makeText(this.context , "Before if" , Toast.LENGTH_SHORT).show();
        // After IF statement
        if (progressValue == 1) Toast.makeText(this.context , "After if" , Toast.LENGTH_SHORT).show();
        // After URL statement
        if (progressValue == 2) Toast.makeText(this.context , "After URL Setting" , Toast.LENGTH_SHORT).show();
        // Before Writing data
        if (progressValue == 3) Toast.makeText(this.context , "After making HTML" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 4) Toast.makeText(this.context , "After making writing infra" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 5) Toast.makeText(this.context , "Before Writing data" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 6) Toast.makeText(this.context , "After Writing data" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 10) Toast.makeText(this.context , "First exception" , Toast.LENGTH_SHORT).show();
        // After Writing data
        if (progressValue == 11) Toast.makeText(this.context , "IO Exception" , Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {
        alertDialog.setMessage(result);
        alertDialog.show();
    }
}

and here is my login.php code:

<?php
require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["user_pass"];
$mysql_qry = "select * from employee_data where user like '$user_name' and password like '$user_pass';";
$result = mysqli_query($conn ,$mysql_qry);
if(mysqli_num_rows($result) > 0) {
    echo "login success";
}
else {
    echo "login not seccess";
}
?>

the conn.php is another scripit that just make the connection the DB. When I'm running my login.php script directly through the broswer - it works fine.

Thank you very much, I hope you can understand the problem, Noam

Noam
  • 1,640
  • 4
  • 26
  • 55
  • FYI, your PHP login script is insecure beyond belief. Please learn [how to bind parameters in PHP](http://stackoverflow.com/a/14110189/3012385). – DaSourcerer May 15 '16 at 12:57
  • Thank you for your comment. It was made only for POC and not for any real world usage. – Noam May 16 '16 at 14:12
  • Yes, I was already under the impression this were not a script intended for public use. Nonetheless I found it important to point out. And yes, I am pushing a bit of a personal agenda: I am incredibly alert when it comes to injection attacks :/ – DaSourcerer May 16 '16 at 14:30
  • Alright man, feel free to push your personal agenda in any of my posts – Noam May 16 '16 at 15:27

1 Answers1

0

I've solved it myself. The IP adress was incorrect , since I use Genymotion Emulator I had to change the IP to 192.168.56.1 Now everything work.

Noam
  • 1,640
  • 4
  • 26
  • 55