Android With Webserver PHP

  •  android
  •  php
  • Membuat aplikasi android dengan webserver menggunakan php.

    1 Buat Database test_android.

    2 Buat Table users(username, fullname).

    3 Buat file php :

    (input_data.php) download
    <?php
    //http://localhost:8080/sample1/webservice2.php?json={%22UserName%22:1,%22FullName%22:2}
    //$json=$_GET ['json'];
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    
    //echo $json;
    
    
    //Save
    $con = mysql_connect('localhost','root','admin') or die('Cannot connect to the DB');
    mysql_select_db('test_android',$con);
    
      /* grab the posts from the db */
      //$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
    mysql_query("INSERT INTO users (username, fullname)
    VALUES ('".$obj->{'username'}."', '".$obj->{'fullname'}."')");
    
    mysql_close($con);
    //
      //$posts = array($json);
      $posts = array(1);
        header('Content-type: application/json');
        echo json_encode(array('posts'=>$posts));
    
    ?>
    
    (select_table.php) download
    <?php
    /* require the user as the parameter */
    //http://localhost:8080/sample1/webservice1.php?user=1
    if(isset($_GET['user']) && intval($_GET['user'])) {
    
    
      /* soak in the passed variable or set our own */
      $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
      $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
      //$user_id = intval($_GET['user']); //no default
    
      /* connect to the db */
      $link = mysql_connect('localhost','root','admin') or die('Cannot connect to the DB');
      mysql_select_db('test_android',$link) or die('Cannot select the DB');
    
      /* grab the posts from the db */
      //$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
      $query = "SELECT * FROM users;";
      $result = mysql_query($query,$link) or die('Errant query:  '.$query);
    
      /* create one master array of the records */
      $posts = array();
      if(mysql_num_rows($result)) {
        while($post = mysql_fetch_assoc($result)) {
          $posts[] = array('post'=>$post);
        }
      }
    
      /* output in necessary format */
      if($format == 'json') {
        header('Content-type: application/json');
        echo json_encode(array('posts'=>$posts));
      }
      else {
        header('Content-type: text/xml');
        echo '<posts>';
        foreach($posts as $index => $post) {
          if(is_array($post)) {
            foreach($post as $key => $value) {
              echo '<',$key,'>';
              if(is_array($value)) {
                foreach($value as $tag => $val) {
                  echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
                }
              }
              echo '</',$key,'>';
            }
          }
        }
        echo '</posts>';
      }
    
      /* disconnect from the db */
      @mysql_close($link);
    }
     ?> 
    

    4 Buat android project.

    5 MainActivity.java.

    (MainActivity.java) download
    package com.ivans.php;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ByteArrayEntity;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.NameValuePair;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;
    import org.json.JSONArray;
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.View;
    import android.widget.Toast;
    
    
    
    
    public class MainActivity extends Activity {
      /** Called when the activity is first created. */
      int TIMEOUT_MILLISEC = 10000; // = 10 seconds
    
      @Override
      public void onCreate(Bundle savedInstanceState) {
          try {
    
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              
              StrictMode.ThreadPolicy policy = new
              StrictMode.ThreadPolicy.Builder().permitAll().build();
              StrictMode.setThreadPolicy(policy);
    
          } catch (Throwable t) {
              Toast.makeText(this, "Request failed: " + t.toString(),
                      Toast.LENGTH_LONG).show();
          }
      }
    
      public void clickbuttonSent(View v) {
          try {
              JSONObject json = new JSONObject();
              json.put("username", "ivans");
              json.put("fullname", "ivans ganteng");
              HttpParams httpParams = new BasicHttpParams();
              HttpConnectionParams.setConnectionTimeout(httpParams,
                      TIMEOUT_MILLISEC);
              HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
              HttpClient client = new DefaultHttpClient(httpParams);
              //
              //String url = "http://10.0.2.2:8080/sample1/webservice2.php?json={\"UserName\":1,\"FullName\":2}";
              String url = "http://192.168.0.103/webservice2.php";
    
              HttpPost request = new HttpPost(url);
              request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                      "UTF8")));
              request.setHeader("json", json.toString());
              HttpResponse response = client.execute(request);
              HttpEntity entity = response.getEntity();
              // If the response does not enclose an entity, there is no need
              if (entity != null) {
                  InputStream instream = entity.getContent();
    
                  String result = StreamConverter.convertStreamToString(instream);
                  Log.i("Read from server", result);
                  Toast.makeText(this,  result,
                          Toast.LENGTH_LONG).show();
              }
          } catch (Throwable t) {
              Toast.makeText(this, "Request failed: " + t.toString(),
                      Toast.LENGTH_LONG).show();
          }
      }
    
      public void clickbuttonRecieve(View v) {
          try {
              // http://androidarabia.net/quran4android/phpserver/connecttoserver.php
    
              // Log.i(getClass().getSimpleName(), "send  task - start");
              HttpParams httpParams = new BasicHttpParams();
              HttpConnectionParams.setConnectionTimeout(httpParams,
                      TIMEOUT_MILLISEC);
              HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
              //
              HttpParams p = new BasicHttpParams();
              // p.setParameter("name", pvo.getName());
    
              // Instantiate an HttpClient
              HttpClient httpclient = new DefaultHttpClient(p);
              String url = "http://192.168.0.103/webservice1.php?user=1&format=json";
              HttpPost httppost = new HttpPost(url);
    
              // Instantiate a GET HTTP method
              try {
                  Log.i(getClass().getSimpleName(), "send  task - start");
                  
                  //List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                  //nameValuePairs.add(new BasicNameValuePair("user", "1"));
                  //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                  
                  ResponseHandler<String> responseHandler = new BasicResponseHandler();
                  String responseBody = httpclient.execute(httppost,
                          responseHandler);
                  // Parse
                  JSONObject json = new JSONObject(responseBody);
                  JSONArray jArray = json.getJSONArray("posts");
                  ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    
                  for (int i = 0; i < jArray.length(); i++) {
                      HashMap<String, String> map = new HashMap<String, String>();
                      JSONObject e = jArray.getJSONObject(i);
                      String s = e.getString("post");
                      JSONObject jObject = new JSONObject(s);
    
                      map.put("idusers", jObject.getString("idusers"));
                      map.put("username", jObject.getString("username"));
                      map.put("fullname", jObject.getString("fullname"));
    
                      mylist.add(map);
                  }
                  Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
    
              } catch (ClientProtocolException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
              // Log.i(getClass().getSimpleName(), "send  task - end");
    
          } catch (Throwable t) {
              Toast.makeText(this, "Request failed: " + t.toString(),
                      Toast.LENGTH_LONG).show();
          }
    
      }
    
      public class Data {
          // private List<User> users;
          public List<User> users;
    
          // +getters/setters
      }
    
      static class User {
          String idusers;
          String username;
          String fullname;
          
          public String getIdusers() {
              return idusers;
          }
          public void setIdusers(String idusers) {
              this.idusers = idusers;
          }
          public String getUsername() {
              return username;
          }
          public void setUsername(String username) {
              this.username = username;
          }
          public String getFullname() {
              return fullname;
          }
          public void setFullname(String fullname) {
              this.fullname = fullname;
          }
    
      }
    }
    

    IP didalam file sesuaikan sama ip server anda, dan juga nama file php yang dibuat tadi

    6 Buat java class baru “StreamConverter.java” mengubah data ke Stream agar dapat di tangkap di php.

    (StreamConverter.java) download
    package com.ivans.php;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.util.Log;
    
    public class StreamConverter {
      public static String convertStreamToString(InputStream is) {
          /*
          * To convert the InputStream to String we use the
          * BufferedReader.readLine() method. We iterate until the BufferedReader
          * return null which means there's no more data to read. Each line will
          * appended to a StringBuilder and returned as String.
          */
          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
          StringBuilder sb = new StringBuilder();
    
          String line = null;
          try {
              while ((line = reader.readLine()) != null) {
                  sb.append(line + "\n");
              }
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              try {
                  is.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
          return sb.toString();
      }
    
      /*
      * This is a test function which will connects to a given rest service and
      * prints it's response to Android Log with labels "Praeda".
      */
      public static void connect(String url) {
    
          HttpClient httpclient = new DefaultHttpClient();
    
          // Prepare a request object
          HttpGet httpget = new HttpGet(url);
    
          // Execute the request
          HttpResponse response;
          try {
              response = httpclient.execute(httpget);
              // Examine the response status
              Log.i("Praeda", response.getStatusLine().toString());
    
              // Get hold of the response entity
              HttpEntity entity = response.getEntity();
              // If the response does not enclose an entity, there is no need
              // to worry about connection release
    
              if (entity != null) {
    
                  // A Simple JSON Response Read
                  InputStream instream = entity.getContent();
                  String result = convertStreamToString(instream);
                  Log.i("Praeda", result);
    
                  // A Simple JSONObject Creation
                  JSONObject json = new JSONObject(result);
                  Log.i("Praeda", "<jsonobject>\n" + json.toString()
                          + "\n</jsonobject>");
    
                  // A Simple JSONObject Parsing
                  JSONArray nameArray = json.names();
                  JSONArray valArray = json.toJSONArray(nameArray);
                  for (int i = 0; i < valArray.length(); i++) {
                      Log.i("Praeda",
                              "<jsonname" + i + ">\n" + nameArray.getString(i)
                                      + "\n</jsonname" + i + ">\n" + "<jsonvalue"
                                      + i + ">\n" + valArray.getString(i)
                                      + "\n</jsonvalue" + i + ">");
                  }
    
                  // A Simple JSONObject Value Pushing
                  json.put("sample key", "sample value");
                  Log.i("Praeda", "<jsonobject>\n" + json.toString()
                          + "\n</jsonobject>");
    
                  // Closing the input stream will trigger connection release
                  instream.close();
              }
    
          } catch (ClientProtocolException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      }
    }
    

    7 activity_main.xml

    (activity_main.xml) download
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <Button
            android:id="@+id/Button01"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:onClick="clickbuttonRecieve"
            android:text="@string/Button01" >
        </Button>
    
        <Button
            android:id="@+id/Button02"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:onClick="clickbuttonSent"
            android:text="@string/Button02" >
        </Button>
    
    </LinearLayout>
    

    Comments