Connect To PHP Server Using Android

View: 583    Dowload: 0   Comment: 0   Post by: daii   Category: Mobile applications   Fields: Game - Entertainment

Download  connect-to-php-server-using.zip (383.58 KB)

You need to Sign In to download the file connect-to-php-server-using.zip
If you do not have an account then Sign up for free here

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="<a href="http://schemas.android.com/apk/res/android"
  3. " rel="nofollow">http://schemas.android.com/apk/res/android"
  4. </a> package="com.razormist.connecttophpserver">
  5. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
  6. <application
  7. android:allowBackup="true"
  8. android:icon="@mipmap/ic_launcher"
  9. android:label="@string/app_name"
  10. android:roundIcon="@mipmap/ic_launcher_round"
  11. android:supportsRtl="true"
  12. android:theme="@style/AppTheme">
  13. <activity android:name=".MainActivity"
  14. android:configChanges="orientation"
  15. android:screenOrientation="portrait">
  16. <intent-filter>
  17. <action android:name="android.intent.action.MAIN" />
  18.  
  19. <category android:name="android.intent.category.LAUNCHER" />
  20. </intent-filter>
  21. </activity>
  22. </application>
  23.  
  24. </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="<a href="http://schemas.android.com/apk/res/android"
  3. " rel="nofollow">http://schemas.android.com/apk/res/android"
  4. </a> xmlns:app="<a href="http://schemas.android.com/apk/res-auto"
  5. " rel="nofollow">http://schemas.android.com/apk/res-auto"
  6. </a> xmlns:tools="<a href="http://schemas.android.com/tools"
  7. " rel="nofollow">http://schemas.android.com/tools"
  8. </a> android:layout_width="match_parent"
  9. android:layout_height="match_parent"
  10. tools:context="com.razormist.connecttophpserver.MainActivity">
  11.  
  12.  
  13. <EditText
  14. android:id="@+id/et_username"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:layout_centerHorizontal="true"
  18. android:layout_marginTop="120dp"
  19. android:ems="10"
  20. android:inputType="text"
  21. android:hint="Username" />
  22.  
  23.  
  24. <EditText
  25. android:id="@+id/et_password"
  26. android:layout_width="wrap_content"
  27. android:layout_height="wrap_content"
  28. android:layout_centerHorizontal="true"
  29. android:layout_marginTop="30dp"
  30. android:ems="10"
  31. android:layout_below="@+id/et_username"
  32. android:inputType="textPassword"
  33. android:hint="Password" />
  34.  
  35. android:id="@+id/btn_login"
  36. android:layout_height="wrap_content"
  37. android:layout_width="wrap_content"
  38. android:layout_centerHorizontal="true"
  39. android:layout_marginTop="30dp"
  40. android:layout_below="@+id/et_password"
  41. android:text="Login"/>
  42.  
  43.  
  44. </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 = "<a href="http://192.168.137.157/Connect%20to%20PHP%20server/index.php";
  13. " rel="nofollow">http://192.168.137.157/Connect%20to%20PHP%20server/index.php";
  14. </a> if(type.equals("login")){
  15. try{
  16. String username = params[1];
  17. String password = params[2];
  18. URL url = new URL(main_url);
  19. HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
  20. httpURLConnection.setRequestMethod("POST");
  21. httpURLConnection.setDoOutput(true);
  22. httpURLConnection.setDoInput(true);
  23. OutputStream outputStream = httpURLConnection.getOutputStream();
  24. BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
  25. String post_data = URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
  26. bufferedWriter.write(post_data);
  27. bufferedWriter.flush();
  28. bufferedWriter.close();
  29. outputStream.close();
  30. InputStream inputStream = httpURLConnection.getInputStream();
  31. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
  32. String result="";
  33. String line;
  34. while((line = bufferedReader.readLine()) != null){
  35. result += line;
  36. }
  37. bufferedReader.close();
  38. inputStream.close();
  39. httpURLConnection.disconnect();
  40. return result;
  41.  
  42. } catch (MalformedURLException e) {
  43. e.printStackTrace();
  44. }catch (IOException e){
  45. e.printStackTrace();
  46. }
  47.  
  48. }
  49. return null;
  50. }
  51.  
  52. @Override
  53. protected void onPreExecute() {
  54. builder = new AlertDialog.Builder(context);
  55. builder.setTitle("System Information");
  56.  
  57. }
  58.  
  59. @Override
  60. protected void onPostExecute(String result) {
  61. builder.setMessage(result);
  62. builder.setCancelable(false);
  63. builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
  64. public void onClick(DialogInterface dialog, int id) {
  65. //do things
  66. }
  67. });
  68.  
  69. AlertDialog alert = builder.create();
  70. alert.show();
  71. }
  72.  
  73. @Override
  74. protected void onProgressUpdate(Void... values) {
  75. super.onProgressUpdate(values);
  76. }
  77. }

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!!!

Connect To PHP Server Using Android

Learn on how 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.

Posted on 09-05-2018 

Comment:

To comment you must be logged in members.

Files with category

  • Flap the Bird

    Flap the Bird

    View: 6    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Tap your screen to make the bird fly. While you are flying there are destruction that will stop you. Avoid hitting the floor and flying to high this will deduct your life. You can collect coins and life along the way. For more mobile games and...

  • Bad Santa

    Bad Santa

    View: 11    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    This is a simple shooting game where the Bad Santa is shooting the bad snowman and reindeer. You can collect coins and life along the way. For more mobile games and tutorials you can visit this site.

  • Flappy Halloween Game

    Flappy Halloween Game

    View: 6    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    Flappy Halloween is a simple game, tap the screen to move the player. Shoot the pumpkin in the ring to gain score. Avoid hitting the flying destructions and falling from the ground. Since the Halloween is coming this game is really perfect to play...

  • Tilt Ball Game

    Tilt Ball Game

    View: 6    Download: 0   Comment: 0

    Category: Android     Fields: Game - Entertainment

    This game is simple you need to tilt your device to make the ball move in your own desired direction. Reach the finish line before the time ends and move to the next level.

  • Sky Rise 3D Game

    Sky Rise 3D Game

    View: 26    Download: 0   Comment: 0

    Category: Mobile applications     Fields: Game - Entertainment

    Stack up the blocks as high as you can to build a tower. Align the blocks on top of each other. If you manage to place the block exactly on the one before it, it will not lose size. Sloppy placement on the other hand will cut off the blocks and...

  • Flappy Bird Game

    Flappy Bird Game

    View: 26    Download: 0   Comment: 0

    Category: Mobile applications     Fields: Game - Entertainment

    The game is very simple, you have to navigate the bird to past the obstacles. You need to tap the screen to make the bird flies. Don’t fly too high because it will die. This game is not 100% cloned from the original Flappy Bird game only the...

  • Motocross Dirt Racing Game

    Motocross Dirt Racing Game

    View: 14    Download: 0   Comment: 0

    Category: Mobile applications     Fields: Game - Entertainment

    Motocross Dirt Racing is an action packed form of off road racing. Unlike the real motocross races, in this game there’s no risk of injury. Finish the race as fast as you can.This game is very exciting and challenging like the other extreme sports....

  • Android - Color Switcher Game

    Android - Color Switcher Game

    View: 9    Download: 0   Comment: 0

    Category: Mobile applications     Fields: Game - Entertainment

    Color Switcher is a game that needs focus every time you are passing the obstacles. This game is fun and very challenging if you are looking for a game that is amusing then this game is perfect for you. If you touch the obstacle which has the...

 
File suggestion for you
File top downloads
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd