Eclipse Client-Server Application (ECSA)


ECSA:   SOLD       




In this section, you will learn about:

  1. Login using php
  2. Login using mySQL server 
  3. Android and mySQL server (NOT YET AVAILABLE) 
  4. JSOIN WebService (coming soon) 
  5. Facebook-Twitter API (coming soon)

1. Login using php

In this section, you will create a simple project in the form of a login page that authenticates via PHP on the server. The scenario is as in Figure 16.1.


Figure 16.1. Client server scenario

In this case, Android acts as a client. The input text in the form of username and password on the login page is packaged in such a way and then sent to the server.

On the server side, the data sent by Android is captured by the PHP file and then processed whether the data matches or not. Next, PHP issues an answer that will then be captured by Android.

| Langkah | Client                                                          | Server                                             |
|---------|-----------------------------------------------------------------|----------------------------------------------------|
| 1       | Mengambil teks username dan password                            | -                                                  |
| 2       | Megirim data username dan password ke server                    | Data ditangkap oleh PHP                            |
| 3       | -                                                               | PHP mengeluarkan jawaban berhasil login atau tidak |
| 4       | Jawaban dari server ditangkap oleh android kemudian ditampilkan |                                                    |

This project was completed in 3 stages, 

  1. XAMPP installation to activate local server (localhost)
  2. Creating a PHP file 
  3. Creating a project on Android

Well, it's time for us to get started.

2. XAMPP Installation

1. Download xampp on the official website

2. Find the XAMPP-Control file, start APACHE and MYSQL (Figure 16.2)


Figure 16.2 When xampp control is active

3. Go to the c:/xampp/htdocs directory, create a new folder called android.

3. Create a PHP file

1. Type the following login.php file (you can use notepad)

1: <?php
2: $user=$_POST['auser'];
3: $pass=$_POST['apass'];
4:
5: if($user=='omayib'&&$pass='1234'){
6: $ket='Login sukses';
7: }else{
8: $ket='gagal login';
9: }
10: echo $ket;
11: ?>

2. Save in the directory C:/xampp/htdocs/android

4. Create a Project on Android

1. Prepare a new project with the following conditions

| Project name    | PHPLogin            |
|-----------------|---------------------|
| Build Target    | Android 2.2         |
| Aplication name | Login melalui PHP   |
| Package name    | omayib.com.phplogin |
| Create Activity | Phplogin            |
| Min SDK version | 8                   |

2. Type strings.xml as follows

1: <?xml version="1.0" encoding="utf-8"?>
2: <resources>
3: <string name="hello">Hello World, Phplogin!</string>
4: <string name="app_name">Login melalui PHP</string>
5: <string name="txtPesan">Silakan Login dulu</string>
6: <string name="txtUser">Username</string>
7: <string name="txtPass">Password</string>
8: <string name="btnLogin">Login</string>
9: <string name="btnSignUp">Sign Up</string>
10: </resources>

3. Type main.xml as follows

1: <?xml version="1.0" encoding="utf-8"?>
2: <LinearLayout
3: xmlns:android="http://schemas.android.com/apk/res/android"
4: android:orientation="vertical"
5: android:layout_width="fill_parent"
6: android:layout_height="fill_parent">
7: <TextView
8: android:layout_width="fill_parent"
9: android:layout_height="wrap_content"
10: android:text="@string/hello" />
11: <TextView
12: android:layout_width="wrap_content"
13: android:layout_height="wrap_content"
14: android:id="@+id/textView2"
15: android:text="@string/txtUser"></TextView>
16: <EditText
17: android:layout_width="match_parent"
18: android:layout_height="wrap_content"
19: android:id="@+id/userInput"></EditText>
20: <TextView
21: android:layout_width="wrap_content"
22: android:layout_height="wrap_content"
23: android:id="@+id/textView1"
24: android:text="@string/txtPass"></TextView>
25: <EditText
26: android:layout_width="match_parent"
27: android:layout_height="wrap_content"
28: android:id="@+id/passInput"></EditText>
29: <Button android:id="@+id/button1"
30: android:layout_width="match_parent"
31: android:layout_height="wrap_content"
32: android:text="@string/btnLogin"></Button>
33: <EditText
34: android:layout_width="match_parent"
35: android:layout_height="wrap_content"
36: android:id="@+id/status"
37: android:text="@string/txtPesan"></EditText>
38: </LinearLayout>

4. Create a ClientToserver.java class which will later act as a bridge between php deserver and the phplogin activity.

1: package omayib.com.phplogin;
2:
3: import java.io.BufferedReader;
4: import java.io.InputStreamReader;
5: import java.net.URI;
6: import java.util.ArrayList;
7:
8: import org.apache.http.HttpResponse;
9: import org.apache.http.NameValuePair;
10: import org.apache.http.client.HttpClient;
11: import
org.apache.http.client.entity.UrlEncodedFormEntity;
12: import org.apache.http.client.methods.HttpGet;
13: import org.apache.http.client.methods.HttpPost;
14: import org.apache.http.conn.params.ConnManagerParams;
15: import org.apache.http.impl.client.DefaultHttpClient;
16: import org.apache.http.params.HttpConnectionParams;
17: import org.apache.http.params.HttpParams;
18:
19: public class ClientToServer {
20: public static final int HTTP_TIMEOUT = 30 * 1000;
21: private static HttpClient client;
22: private static HttpClient getHttpClient() {
23: if (client == null) {
24: client = new DefaultHttpClient();
25: final HttpParams parameterHttp = client.getParams();
26: HttpConnectionParams.setConnectionTimeout(parameterHttp,
27: HTTP_TIMEOUT);
28: ConnManagerParams.setTimeout(parameterHttp,
HTTP_TIMEOUT);
29: }
30: return client;
31: }
32:
33: public static String eksekusiHttpPost(String url,
34: ArrayList<NameValuePair> postParameter) throws Exception
{
35: BufferedReader in = null;
36: try {
37: HttpClient klien = getHttpClient();
38: HttpPost req = new HttpPost(url);
39: UrlEncodedFormEntity formEntity = new
UrlEncodedFormEntity(
40: postParameter);
41: req.setEntity(formEntity);
42: HttpResponse jawaban = klien.execute(req);
43: in = new BufferedReader(new
InputStreamReader(jawaban.getEntity().getContent()));
44: StringBuffer sb = new StringBuffer("");
45: String line = "";
46: String NL = System.getProperty("line.separator");
47: while ((line = in.readLine()) != null) {
48: sb.append(line + NL);
49: }
50: in.close();
51: String hasil = sb.toString();
52: return hasil;
53: } finally {
54: if (in != null) {
55: in.close();
56: }
57: }
58:
59: }
60:
61: public static String eksekusiHttpGet(String url) throws
Exception {
62: BufferedReader in = null;
63: try {
64: HttpClient hc = getHttpClient();
65: HttpGet req = new HttpGet();
66: req.setURI(new URI(url));
67: HttpResponse resp = hc.execute(req);
68: in = new BufferedReader(new
InputStreamReader(resp.getEntity().getContent()));
69: StringBuffer sb = new StringBuffer("");
70: String line = "";
71: String NL = System.getProperty("line.separator");
72: while ((line = in.readLine()) != null) {
73: sb.append(line + NL);
74: }
75: in.close();
76: String hasil = sb.toString();
77: return hasil;
78: } finally {
79: if (in != null) {
80: in.close();
81: }
82: }
83: }
84: }

5. In phplogin.java change the code as below

1: package omayib.com.phplogin;
2:
3: import java.util.ArrayList;
4:
5: import org.apache.http.NameValuePair;
6: import org.apache.http.message.BasicNameValuePair;
7:
8: import android.app.Activity;
9: import android.os.Bundle;
10: import android.view.View;
11: import android.view.View.OnClickListener;
12: import android.widget.Button;
13: import android.widget.EditText;
14: import android.widget.Toast;
15:
16: public class Phplogin extends Activity implements
OnClickListener {
17: Button loginBtn;
18: EditText user, pass;
19: EditText status;
20: private String url = "http://10.0.2.2/android/login.php";
21:
22: /** Called when the activity is first created. */
23: @Override
24: public void onCreate(Bundle savedInstanceState) {
25: super.onCreate(savedInstanceState);
26: setContentView(R.layout.main);
27:
28: user = (EditText) findViewById(R.id.userInput);
29: pass = (EditText) findViewById(R.id.passInput);
30: status = (EditText) findViewById(R.id.status);
31: loginBtn = (Button) findViewById(R.id.button1);
32: loginBtn.setOnClickListener(this);
33: }
34:
35: @Override
36: public void onClick(View v) {
37: // TODO Auto-generated method stub
38: kirimData();
39: }
40:
41: private void kirimData() {
42: // TODO Auto-generated method stub
43: ArrayList<NameValuePair> kirimkephp = new
44: ArrayList<NameValuePair>();
45: kirimkephp.add(new
46: BasicNameValuePair("auser",user.getText().toString()));
47: kirimkephp.add(new
48: BasicNameValuePair("apass",pass.getText().toString()));
49: String respon=null;
50: try {
51: respon=ClientToServer.eksekusiHttpPost(url,
52: kirimkephp);
53: String res=respon.toString();
54: res=res.trim();
55: Toast.makeText(this, res.toString(),
56: Toast.LENGTH_SHORT).show();
57: status.setText(res.toString());
58: } catch (Exception e) {
59: // TODO Auto-generated catch block
60: e.printStackTrace();
61: }
62: }
63: }

6. In the AndroidManifest.xml section, add permission.internet

1: <?xml version="1.0" encoding="utf-8"?>
2: <manifest xmlns:android="http://schemas.android.com/apk/res/android"
3: package="com.login.php"
4: android:versionCode="1"
5: android:versionName="1.0">
6: <uses-sdk android:minSdkVersion="8" />
7:
8: <uses-permission android:name="android.permission.INTERNET">
10: </uses-permission>
11:
12: <application android:icon="@drawable/icon"
13: android:label="@string/app_name">
14: <activity android:name=".LoginPHP"
15: android:label="@string/app_name">
16: <intent-filter>
17: <action android:name="android.intent.action.MAIN"/>
19: <category
20: android:name="android.intent.category.LAUNCHER" />
21: </intent-filter>
22: </activity>
23: </application>
24: </manifest>

7. Run it, if successful the result will be as shown in figure 16.3.


Figure 16.3 Final result of the phplogin project

5. Login Using Database

Now let's change the scenario a little. The PHP file is tasked with matching data from Android with data in the database. In other words, in this section the PHP file functions as a bridge between the Android client and the database on the server.


Figure 16.4. Login scenario using database

In general, the steps that must be taken are as follows:

  1. Create a database on localhost server
  2. Create php 
  3. Creating a project on Android

6. Create a database on the localhost server

  1. Run xampp
  2. Run the browser, type "localhost/phpmyadmin" 
  3. To create a database, in the SQL section type the following:
Create database logindb;

4. Click the logindb database, then we will create a user table. In the SQL section, type the following

CREATE TABLE IF NOT EXISTS `user` (
  `_id` int(4) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `email` varchar(32) NOT NULL,
  `akun twitter` varchar(32) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

To be more clear, this step 4 looks like figure 6.15.


Figure 16.5 SQL to create a user table

5. Enter data into the database

INSERT INTO `logindb`.`user` (`_id` ,`username` ,`pass
word` , `email` ,`akun twitter`)
VALUES (
'1', 'omayib', '1234r', '[email protected]', '@omayib'
);

If it is correct, the final result will be like figure 16.6.


Figure 16.6 User table in the database and its data

7. Create php

The next step is to create a logindb.php file that will be tasked with matching data from the server and client. The following is logindb.php. Save the logindb.php file in the c:/xampp/htdocs/android/ directory.

1: <?php
2: $user=$_POST['user'];
3: $pass=$_POST['pass'];
4:
5: $konek=mysql_connect("localhost","root","");
6: mysql_select_db("latihanDB");
7:
8: $quer="SELECT * FROM user WHERE username='$user' AND password='$pass'";
9: $hasil=mysql_query($quer) or die("Kesalahan query:".mysql_error());
10:
11: if(mysql_num_rows($hasil)==1){
12: echo 1;
13: }else{
14: echo 0;
15: }
16: ?>

8. Create a project on Android

This section still uses the previous login project, the PHPLogin project. It's just that the url is changed like this Previously.

private String url = "http://10.0.2.2/android/login.php";

Then replaced

private String url = "http://10.0.2.2/android/loginDB.php";

Post a Comment

Previous Next

نموذج الاتصال