-->

How to Connect To PHP Server Using Application Android + Source Code Project Android

In this tutorial we will try to make Connect To PHP Server using Android. Android is an open source so developers find it easy to develop and expand new features. It's used in some gadgets like smartphones, tablets, and even television. It also provides an adaptive framework that allows developers to develop applications in a simpler way. So let's do the encoding

Getting Started :

First you must download & install Android Development IDE (Android Studio or Eclipse). Android Studio is an open source development feel free to develop your stuff.

Here is the link for Android Studio https://developer.android.com/studio/index.html.



Then you must download & install XAMPP or any local server running PHP scripts. Here is the link for the XAMPP server https://www.apachefriends.org/index.html.

How to Connect To PHP Server Using Application Android + Source Code Project Android




Create a database


Open your web server database then create a database name in it db_contact, then click Import then search the database file in the application folder then click ok

How to Connect To PHP Server Using Application Android + Source Code Project Android



Creating the database Connection

$conn = new mysqli("localhost", "root", "", "db_contact");
if(!$conn){
die("Fatal Error: Connect Error!");
}
?>


Creating PHP Main Script

This code contains the main function of the php server. This code will try to access the php server to get the data from the server base on the data that has been inputed. To do that open any kind of text editor(notepadd++, etc..), then copy it inside the text editor and save it as index.php


require_once "conn.php";

$username = $_POST['username'];
$password = $_POST['password'];

$query = $conn->query("SELECT * FROM `member` WHERE `username` = '$username' && `password` = '$password'");

$row = $query->num_rows;

if($row > 0){
echo "Login Successful";
}else{
echo "Error Login!";
}
?>

Once done with PHP, then we need to create an application to run php server on Android Platform.

Android Manifest File



The Android Manifest file provides important information about your app to the Android system where the system should be required before running the code. It describes the overall information about the app. It contains some of the libraries needed to access some of the in-app methods.

" rel="nofollow">http://schemas.android.com/apk/res/android"
    package="com.razormist.connecttophpserver">
   
   
        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">
       
            android:configChanges="orientation"
            android:screenOrientation="portrait">
           
               

               
           
       
   


Layout Design


We will now create a design for the application, first locate a layout file named activity_main.xml, this is the default name when creating a new activity. Then write these codes inside your layout file.

" rel="nofollow">http://schemas.android.com/apk/res/android"
    xmlns:app="
" rel="nofollow">http://schemas.android.com/apk/res-auto"
    xmlns:tools="
" rel="nofollow">http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.razormist.connecttophpserver.MainActivity">


   
        android:id="@+id/et_username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="120dp"
        android:ems="10"
        android:inputType="text"
        android:hint="Username" />


   
        android:id="@+id/et_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:ems="10"
        android:layout_below="@+id/et_username"
        android:inputType="textPassword"
        android:hint="Password" />

   
        android:id="@+id/btn_login"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:layout_below="@+id/et_password"
        android:text="Login"/>





Creating a Server Handler


This code contains the handler to access the PHP server. This code will try to create url to access php server by sending POST data in android app. To do that create a new class then call it as ServerHandler. And write this block of code in it to generate the url link to the server.

public class ServerHandler extends AsyncTask {
    Context context;
    AlertDialog.Builder builder;

    ServerHandler(Context context){
        this.context = context;
    }

    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String main_url = "
" rel="nofollow">http://192.168.137.157/Connect%20to%20PHP%20server/index.php";
        if(type.equals("login")){
            try{
                String username = params[1];
                String password = params[2];
                URL url = new URL(main_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("username", "UTF-8")+"="+URLEncoder.encode(username, "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() {
        builder = new AlertDialog.Builder(context);
        builder.setTitle("System Information");

    }

    @Override
    protected void onPostExecute(String result) {
        builder.setMessage(result);
        builder.setCancelable(false);
        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //do things
            }
        });



        AlertDialog alert = builder.create();
        alert.show();
    }



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

Note: To access localhost server make sure you change
main_url is the same as your local computer's IP address.



The main function

This code contains the main function of the application. This code will send user information to the PHP server when the button is clicked. To get started by first locating your MainActivity java file and open it, then write this variable in the MainActivity class

EditText et_username, et_password;
Button btn_login;

Finally, initialize the necessary methods in the onCreate method to run the application.

 et_username = (EditText)findViewById(R.id.et_username);
        et_password = (EditText)findViewById(R.id.et_password);
        btn_login = (Button)findViewById(R.id.btn_login);




        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = et_username.getText().toString();
                String password = et_password.getText().toString();

                if(!username.equals("") ||  !password.equals("")){
                    String condition = "login";
                    ServerHandler serverHandler = new ServerHandler(MainActivity.this);
                    serverHandler.execute(condition, username, password);
                    et_username.setText("");
                    et_password.setText("");
                }else{
                    Toast.makeText(MainActivity.this, "Required Field!", Toast.LENGTH_SHORT).show();
                }



            }
        });

Try running the app and see if it works.


There you have it we have made Connect To PHP Server using Android. I hope this tutorial helps you for what you are looking for.

NEXT ARTICLE Next Post
PREVIOUS ARTICLE Previous Post
NEXT ARTICLE Next Post
PREVIOUS ARTICLE Previous Post
 

Delivered by FeedBurner

-->