0

What should be the URL format in 'Android Studio java code' to connect to MYSQL server through php using wamp, while running the app on real device instead of emulator?

MainActivity.java

package com.example.connection;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    EditText UsernameEt, PasswordEt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        UsernameEt = (EditText)findViewById(R.id.etUserName);
        PasswordEt = (EditText)findViewById(R.id.etPassword);
    }

    public void OnLogin(View view) {
        String username = UsernameEt.getText().toString();
        String password = PasswordEt.getText().toString();
        String type = "login";
        BackgroundWorker backgroundWorker = new BackgroundWorker(this);
        backgroundWorker.execute(type, username, password);
    }

}

BckgroundWorker.java

package com.example.connection;

import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by ProgrammingKnowledge on 1/5/2016.
 */
public class BackgroundWorker extends AsyncTask<String,Void,String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx) {
        context = ctx;
    }
    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "http://192.168.0.8:80/login.php";
        if(type.equals("login")) {
            try {
                String user_name = params[1];
                String password = params[2];
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
                        +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");

                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
                String result="";
                String line="";
                while((line = bufferedReader.readLine())!= null) {
                    result += line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @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();
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.connection">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:id="@+id/etUserName"
    android:layout_alignParentTop="true"
    android:layout_marginTop="47dp" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:id="@+id/etPassword"
    android:layout_below="@+id/etUserName"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Login"
    android:id="@+id/btnLogin"
    android:layout_below="@+id/etPassword"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="48dp"
    android:layout_marginStart="48dp"
    android:layout_marginTop="50dp"
    android:onClick="OnLogin"/>

login.php

<?php
require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["password"];
$mysql_qry = "select * from employee where Name like '$user_name' and Pass like '$user_pass";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0)
{
    echo "login successful!!!!!!!!!!!!!";
}
else
{
    echo "login unsuccessful";
}

conn.php

<?php
$db_name = "try_one";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$conn=mysqli_connect($server_name, $mysql_username, $mysql_password, $db_name, "3308");
?>

The dialog box appears to be empty and doesn't show any text. As I had checked the code, the program execution transfers to IOException catch block from 'OutputStream outputStream = httpURLConnection.getOutputStream();' this line in BackgroundWorker.java file.

  • Your app can't connect directly to MYSQL, you'll need to create an API. A quick search on Google brings up articles like this https://www.skysilk.com/blog/2018/how-to-connect-an-android-app-to-a-mysql-database/ which shows how you can create an API with php and then request data from your android app. Also it sounds like you've already started on something so some code would be helpful. – Luke.T May 03 '20 at 19:54
  • https://stackoverflow.com/questions/41408113/android-app-is-not-connected-to-mysql-database -I have an almost similar code as provided in this link. Also I have edited the http.conf and httpd-vhosts.cof file in wamp, and changed 'Require local' to 'Require all granted'. I have also created a new inbound rule in Windows firewall advanced settings granting access to httpd application in apache folder to use TCP protocol and port number 80. Also, my phone and laptop connected to the same network.......Can't really figure out the problem. – divyansh191 May 04 '20 at 09:30
  • Ahh okay I see what you mean what url are you currently using? It would really help if you could put your code on here though. Keep in mind it could just be one slight thing you've changed that could cause it not to work. – Luke.T May 04 '20 at 09:37
  • I have added all the code – divyansh191 May 04 '20 at 10:14
  • Does the url http://192.168.0.8:80/login.php work in your browser on both your phone and pc? If not try http://192.168.0.8/login.php – Luke.T May 04 '20 at 10:22
  • Neither of these work on my pc and mobile – divyansh191 May 04 '20 at 10:31
  • Right this is more related to your Wamp setup then, check that 192.168.0.8 is the correct ip. If it is then double check that your Wamp setup is allowing connections on your local network this question might help https://stackoverflow.com/questions/24005828/how-to-enable-local-network-users-to-access-my-wamp-sites – Luke.T May 04 '20 at 10:38
  • Actually, I could connect to the database through localhost/conn.php or localhost/login.php. And it didn't raise any objection then. – divyansh191 May 04 '20 at 10:45
  • Well it's good that localhost is working but that obviously won't work on your external device. The url you should be using for your app is http://your_computer_ip/login.php. If that isn't working your wamp server must not be setup correctly for LAN connections. – Luke.T May 04 '20 at 11:08
  • I have followed up the link which you had provided in the comments. I am able to access the http://192.168.0.8/login.php from my phone and pc. But the dialog box in my app didn't bring any result from the outputstream. As I had mentioned, the program goes to IOException from the 'OutputStream outputStream = httpURLConnection.getOutputStream();' this line in BackgroundWorker.java file. – divyansh191 May 04 '20 at 11:46
  • I do believe that is now a different question to the one you've asked above but what is the result of your e.printStackTrace();. There should be more error information? – Luke.T May 04 '20 at 11:52

0 Answers0