Setup a free mysql and php host site for Android

Step 1

Signup

https://www.000webhost.com/free-website-sign-up


Step 2 : Verify your email

Step 3: Create Database






Step 4: Create Read.php and Insert.php

 Create a Read.php with a note pad

<?php
$return_arr = array();
$conn=mysqli_connect("localhost","id4388354_mdaduser","mdad2301","id4388354_mdad");


// Check connection
if (mysqli_connect_errno())
{
          echo "Failed to connect to MySQL: " .   
          mysqli_connect_error();
}
 

$sql ="select * from  Example";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
 //fetch data from mysql and put into $row
 while($row = $result->fetch_assoc())
 {
              
  $rows['name'] = $row["name"];
  $rows['age'] = $row["age"];
  $rows['email'] = $row["email"];
  array_push($return_arr,$rows);
 }
}
else
{
 echo "0 results";
}
$conn->close();

//print out the results to android/browser

$Details['result'] = $return_arr;
echo json_encode($Details);

 
//MDAD17.EPIZY.COM/Read.php
?> 



Insert.php
<?php
$name=$_POST['name'];
$age=$_POST['age'];
$email=$_POST['email'];


 
$conn=mysqli_connect("localhost","id4388354_mdaduser","mdad2301","id4388354_mdad");
// Check connection
//$conn=mysqli_connect("localhost","root","","test");
$sql = "INSERT INTO Example(name,age,email) VALUES('$name','$age','$email')";
if ($conn->query($sql) === TRUE) 
{echo"Success";} 
else{echo "Fail";}
$conn->close(); 
?>



Step5 : Upload to server






Step 6 : Test out your php file

https://mdad.000webhostapp.com/Read.php






If you have successfully get Step 6 to work, Congratulation! 

Step 7 : Now let's continue with the android side
for reading and inserting data from/to mysql db

Download the complete code and test it on your phone




APK






Read data from PHP

package com.example.getphonedbexample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.getphonedbexample.MainActivity.insertDATA;

import android.app.Activity;
import android.content.Intent;
 
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class SecondActivity extends Activity {
ListView ListView;

 
 String url = "";
 String name;
 String age;
 String email;
 HashMap<String, String> map;
 ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
 //static String TAG_sensor_id = "sensor_id";
 static String TAG_name = "name";
 static String TAG_age = "age";
 static String TAG_email = "email";
 Button btnInsert,btnRead;
 
 
 SecondReadActivity DisplayListItem ;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_second);

     

  btnInsert = (Button) findViewById(R.id.btnInsert);
     //Setting up the on click listener
  btnInsert.setOnClickListener (new View.OnClickListener() {
           InputStream is = null;
      @Override
   public void onClick(View v) {
       // TODO Auto-generated method stub
        
   Intent intent = new Intent(SecondActivity.this, MainActivity.class);
    startActivity(intent);
  }
      
});  
         
         
         
btnRead = (Button) findViewById(R.id.btnRead);
//Setting up the on click listener
btnRead.setOnClickListener (new View.OnClickListener() {
 InputStream is = null;
 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
        
 String p_nric="test";
    items.clear();
 DisplayListItem = new SecondReadActivity(getBaseContext(), R.layout.activity_second_read,items);
                      
 ListView = (ListView) findViewById(R.id.listView);
         
 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy);
         
 HttpClient httpclient = new DefaultHttpClient();
 HttpPost httppost = new HttpPost("https://mdad.000webhostapp.com/Read.php");
 httppost.setHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36");
          
try {
 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 HttpResponse responsePOST = httpclient.execute(httppost);
    HttpEntity entity = responsePOST.getEntity(); 
 String response=EntityUtils.toString(entity); // content will be consume only once

 System.out.println("Response " + response);
                 
           
JSONObject detailsObject = new JSONObject(response);
JSONArray detailsArray = detailsObject.getJSONArray("result");

Log.v("DETAILS", detailsArray.toString() );
Log.v("Length", detailsArray.length()+"");


for(int i = 0; i<detailsArray.length(); i++)
{
 JSONObject object = detailsArray.getJSONObject(i);
 Log.v("OBJECT", object.toString());


        //Get the data from the server 
 name = object.getString("name");
 age = object.getString("age");
 email = object.getString("email");
            
 

        //put each row of data into map (dynamic array)               
        map = new HashMap<String, String>();
 map.put(TAG_name, name);
 map.put(TAG_age, age);
 map.put(TAG_email, email);
 items.add(map); //put Hashmap into ArrayList


        //Add the data to the ListView for Display
 DisplayListItem.notifyDataSetChanged();
 ListView.setAdapter(DisplayListItem); //set Adapter to ListView
                 
}
                   
} 
               
 catch (Exception e) {System.out.println("Error " + e);
 }
 }
      
});  
 
 }
 


}



Insert data
package com.example.getphonedbexample;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

 EditText etName, etAge, etEmail;
 Button bSubmit;
 String name = "";
 String age = "";
 String email = ""; 
 @SuppressLint("NewApi") 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  //Setup the strictmode policy
 // StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 // StrictMode.setThreadPolicy(policy);
  
 
  etName = (EditText) findViewById(R.id.editName);
  etAge = (EditText) findViewById(R.id.editAge);
   etEmail = (EditText) findViewById(R.id.editEmail);  
   bSubmit = (Button) findViewById(R.id.submitBtn);
 
  bSubmit.setOnClickListener (new View.OnClickListener() {
   InputStream is = null;
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    //Storing the values inside the editTexts inside the string variables
     name = ""+etName.getText().toString();
     age = ""+etAge.getText().toString();
     email = ""+etEmail.getText().toString();
     new insertDATA().execute("");

   }
   
  });
  
  
  
  
 }
 class insertDATA extends AsyncTask<String, String, String> {

  @Override
  protected String doInBackground(String... arg0) {
   // TODO Auto-generated method stub
   
   System.out.println("3");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://mdad.000webhostapp.com/Insert.php");
System.out.println("4");
httppost.setHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();


 System.out.println("5");
 System.out.println(name);
 System.out.println(age);
 System.out.println(email);


  nameValuePairs.add(new BasicNameValuePair("name", name));
  nameValuePairs.add(new BasicNameValuePair("age", age));
  nameValuePairs.add(new BasicNameValuePair("email", email));


 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 HttpResponse responsePOST = httpclient.execute(httppost);


  System.out.println(nameValuePairs);
  System.out.println("6");
HttpEntity resEntity = responsePOST.getEntity(); 
String response=EntityUtils.toString(resEntity); // content will be consume only once

Log.e("XXX",response);

if (response.equalsIgnoreCase("Success"))
{
 System.out.println("Successfully Inserted");
}
else

{
 System.out.println("Unable to Insert");
 
}
//HealthDAO.getInstance(frame).updateCompare(Cid, "Updated");
} catch (Exception e) {
System.out.println("Error " + e);
}

   return null;
  }
 }

}