Connect To PHP Server Using Android

Operating System

In this tutorial we will try to create a Connect To PHP Server using Android. Android is an open source so that developer find it easy to develop and expand new features. It used in several gadget like smartphone, tablet, and even television. It also provide an adaptive framework that allow the developer to develop an apps in a simpler way. So let's do the coding..

Getting Started:

First you will have to download & install the Android Development IDE (Android Studio or Eclipse). Android Studio is an open source development feel free to develop your things. Here's the link for the Android Studio https://developer.android.com/studio/index.html. Then you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html.

Creating the database

Open your database web server then create a database name in it db_contact, after that click Import then locate the database file inside the folder of the application then click ok. tut1

Creating the database connection

Open your any kind of text editor(notepadd++, etc..). Then just copy/paste the code below then name it conn.php.
  1. <?php
  2. $conn = new mysqli("localhost", "root", "", "db_contact");
  3. if(!$conn){
  4. die("Fatal Error: Connect Error!");
  5. }
  6. ?>

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
  1. <?php
  2. require_once "conn.php";
  3.  
  4. $username = $_POST['username'];
  5. $password = $_POST['password'];
  6.  
  7. $query = $conn->query("SELECT * FROM `member` WHERE `username` = '$username' && `password` = '$password'");
  8.  
  9. $row = $query->num_rows;
  10.  
  11. if($row > 0){
  12. echo "Login Successful";
  13. }else{
  14. echo "Error Login!";
  15. }
  16. ?>
Now that we're done with PHP, next is we will need to create the application to run the php server in the Android Platform.

Android Manifest File

The Android Manifest file provides essential information about your app to the Android system in which the system must required before running the code. It describe the overall information about the application. It contains some libraries that needed to access the several method within the app.
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.razormist.connecttophpserver">
  4. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  5. <application
  6. android:allowBackup="true"
  7. android:icon="@mipmap/ic_launcher"
  8. android:label="@string/app_name"
  9. android:roundIcon="@mipmap/ic_launcher_round"
  10. android:supportsRtl="true"
  11. android:theme="@style/AppTheme">
  12. <activity android:name=".MainActivity"
  13. android:configChanges="orientation"
  14. android:screenOrientation="portrait">
  15. <intent-filter>
  16. <action android:name="android.intent.action.MAIN" />
  17.  
  18. <category android:name="android.intent.category.LAUNCHER" />
  19. </intent-filter>
  20. </activity>
  21. </application>
  22.  
  23. </manifest>

Layout Design

We will now create the design for the application, first locate the layout file called activity_main.xml, this is the default name when create a new activity. Then write these codes inside your layout file.
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context="com.razormist.connecttophpserver.MainActivity">
  8.  
  9.  
  10. <EditText
  11. android:id="@+id/et_username"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:layout_centerHorizontal="true"
  15. android:layout_marginTop="120dp"
  16. android:ems="10"
  17. android:inputType="text"
  18. android:hint="Username" />
  19.  
  20.  
  21. <EditText
  22. android:id="@+id/et_password"
  23. android:layout_width="wrap_content"
  24. android:layout_height="wrap_content"
  25. android:layout_centerHorizontal="true"
  26. android:layout_marginTop="30dp"
  27. android:ems="10"
  28. android:layout_below="@+id/et_username"
  29. android:inputType="textPassword"
  30. android:hint="Password" />
  31.  
  32. android:id="@+id/btn_login"
  33. android:layout_height="wrap_content"
  34. android:layout_width="wrap_content"
  35. android:layout_centerHorizontal="true"
  36. android:layout_marginTop="30dp"
  37. android:layout_below="@+id/et_password"
  38. android:text="Login"/>
  39.  
  40.  
  41. </RelativeLayout>

Creating the Server Handler

This code contains the handler for accessing the PHP server. This code will try to create a url to access the php server by sending a POST data within the android application.To do that create a new class then called it as ServerHandler. And write these block of codes inside it to be able to generate a url link to the server.
  1. public class ServerHandler extends AsyncTask<String, Void, String> {
  2. Context context;
  3. AlertDialog.Builder builder;
  4.  
  5. ServerHandler(Context context){
  6. this.context = context;
  7. }
  8.  
  9. @Override
  10. protected String doInBackground(String... params) {
  11. String type = params[0];
  12. String main_url = "http://192.168.137.157/Connect%20to%20PHP%20server/index.php";
  13. if(type.equals("login")){
  14. try{
  15. String username = params[1];
  16. String password = params[2];
  17. URL url = new URL(main_url);
  18. HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
  19. httpURLConnection.setRequestMethod("POST");
  20. httpURLConnection.setDoOutput(true);
  21. httpURLConnection.setDoInput(true);
  22. OutputStream outputStream = httpURLConnection.getOutputStream();
  23. BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
  24. String post_data = URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
  25. bufferedWriter.write(post_data);
  26. bufferedWriter.flush();
  27. bufferedWriter.close();
  28. outputStream.close();
  29. InputStream inputStream = httpURLConnection.getInputStream();
  30. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
  31. String result="";
  32. String line;
  33. while((line = bufferedReader.readLine()) != null){
  34. result += line;
  35. }
  36. bufferedReader.close();
  37. inputStream.close();
  38. httpURLConnection.disconnect();
  39. return result;
  40.  
  41. } catch (MalformedURLException e) {
  42. e.printStackTrace();
  43. }catch (IOException e){
  44. e.printStackTrace();
  45. }
  46.  
  47. }
  48. return null;
  49. }
  50.  
  51. @Override
  52. protected void onPreExecute() {
  53. builder = new AlertDialog.Builder(context);
  54. builder.setTitle("System Information");
  55.  
  56. }
  57.  
  58. @Override
  59. protected void onPostExecute(String result) {
  60. builder.setMessage(result);
  61. builder.setCancelable(false);
  62. builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
  63. public void onClick(DialogInterface dialog, int id) {
  64. //do things
  65. }
  66. });
  67.  
  68. AlertDialog alert = builder.create();
  69. alert.show();
  70. }
  71.  
  72. @Override
  73. protected void onProgressUpdate(Void... values) {
  74. super.onProgressUpdate(values);
  75. }
  76. }
Note:To access the localhost server make sure you change the main_url same as your machine local IP address.

The Main Function

This code contains the main function of the application. This code will send the information of user to the PHP server when the button is clicked. To start with first locate your MainActivity java file and open it, then write these variable inside the MainActivity class.
  1. EditText et_username, et_password;
  2. Button btn_login;
Finally, initialize the require methods inside the onCreate method to run the application.
  1. et_username = (EditText)findViewById(R.id.et_username);
  2. et_password = (EditText)findViewById(R.id.et_password);
  3. btn_login = (Button)findViewById(R.id.btn_login);
  4.  
  5.  
  6. btn_login.setOnClickListener(new View.OnClickListener() {
  7. @Override
  8. public void onClick(View view) {
  9. String username = et_username.getText().toString();
  10. String password = et_password.getText().toString();
  11.  
  12. if(!username.equals("") || !password.equals("")){
  13. String condition = "login";
  14. ServerHandler serverHandler = new ServerHandler(MainActivity.this);
  15. serverHandler.execute(condition, username, password);
  16. et_username.setText("");
  17. et_password.setText("");
  18. }else{
  19. Toast.makeText(MainActivity.this, "Required Field!", Toast.LENGTH_SHORT).show();
  20. }
  21.  
  22. }
  23. });
Try to run the app and see if it worked. There you have it we have created a Connect To PHP Server using Android. I hope that this tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!!

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Submitted byAsim Malik (not verified)on Fri, 03/15/2019 - 22:19

Nice Post @razormist sir please give more tutorial on android like this

Add new comment