Bonjour,
J'essaye de suivre ce tuto : http://dsilvera.developpez.com/tutor...es-script-php/ mais quand je lance l'appli sur mon téléphone je bloque sur la page qui me demande les informations de connexion ( Je vois "please wait" tous le temps).
Voici mes fichiers :
SCRIPT BASE DE DONNEE :SCRIPT PHP situé sur bouzoubad.free.fr/log.php :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 -- phpMyAdmin SQL Dump -- version 2.6.4-pl4 -- http://www.phpmyadmin.net -- -- Host: localhost -- -- -------------------------------------------------------- -- -- Création Table `auth_table` -- CREATE TABLE IF NOT EXISTS auth_table ( user_id int(10) UNSIGNED NOT NULL AUTO_INCREMENT, username varchar(20) NOT NULL DEFAULT '', password varchar(32) NOT NULL DEFAULT '', PRIMARY KEY (user_id), UNIQUE KEY username (username) ) ENGINE = InnoDB; -- -- Insertion Table `auth_table` -- INSERT INTO auth_table (username, password) VALUES ('test', MD5('pass'));MAIN.XML :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 <?php unset($_GET); if( isset($_POST['username']) && isset($_POST['password']) ) { echo '<?xml version="1.0"?>'."\n"; echo "<login>\n"; // host doit être remplacé par le serveur de la base de données. // user représente le nom d'utilisateur de la base de données. // pass est le mot de passe pour accéder à cette base de données avec cette // utilisateur. if (!@mysql_connect('bouzoubad.sql.free.fr', 'bouzoubad', 'azrael0')) { error(1); } // database représente le nom d ela base de données if (!mysql_select_db('Log')) { error(2); } if(get_magic_quotes_gpc()) { $login = stripslashes($_POST['username']); $pass = stripslashes($_POST['password']); } else { $login = $_POST['username']; $pass = $_POST['password']; } unset($_POST); $kid = login($login, $pass); if($kid == -1) { error(3); } else { printf(' <user id="%d"/>'."\n",$kid); } echo "</login>"; } function error($ec) { printf(' <error value="%d"/>'."\n".'</login>',$ec); die(); } function login($login, $pass) { $select = " SELECT user_id FROM auth_table WHERE username = '%s' AND password = '%s' "; $fixedlogin = mysql_real_escape_string($login); $fixedpass = mysql_real_escape_string($pass); $query = sprintf($select, $fixedlogin, $fixedpass); $result = mysql_query($query); if(mysql_num_rows($result) != 1) { return -1; } $row = mysql_fetch_row($result); return $row[0]; } ?>LOGIN.XML :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 <RelativeLayout 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" > <EditText android:id="@+id/username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_below="@+id/please" android:layout_marginTop="45dp" android:ems="10" android:hint="@string/hint_username" android:padding="20dp" android:singleLine="true" /> <EditText android:id="@+id/password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_below="@+id/username" android:ems="10" android:hint="@string/hint_password" android:inputType="textPassword" android:padding="20dp" > <requestFocus /> </EditText> <Button android:id="@+id/cancelbutton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_marginBottom="40dp" android:text="@string/Cancel" /> <TextView android:id="@+id/please" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="17dp" android:padding="10dp" android:text="@string/please" android:textAppearance="?android:attr/textAppearanceMedium" /> <Button android:id="@+id/okbutton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@+id/cancelbutton" android:layout_alignParentLeft="true" android:text="@string/Login" /> </RelativeLayout>MAIN.JAVA :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 <RelativeLayout 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" tools:context=".Login" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="170dp" android:text="@string/TextView" /> </RelativeLayout>LOGIN.JAVA :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 package com.example.gyropode; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import com.example.gyropode.Login; public class Main extends Activity { private TextView tv; public static final int RESULT_Main = 1; public void onCreate(Bundle icicle) { super.onCreate(icicle); //Appel de la page de Login startActivityForResult(new Intent(Main.this, Login.class), RESULT_Main); tv = new TextView(this); setContentView(tv); } private void startup(Intent i) { // Récupère l'identifiant int user = i.getIntExtra("userid",-1); //Affiche les identifiants de l'utilisateur tv.setText("UserID: "+String.valueOf(user)+" logged in"); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == RESULT_Main && resultCode == RESULT_CANCELED) finish(); else startup(data); } }STRINGS.XML :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342 package com.example.gyropode; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; 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.params.HttpConnectionParams; import org.apache.http.protocol.HTTP; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Looper; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.gyropode.R; public class Login extends Activity { // Lien vers votre page php sur votre serveur private static final String UPDATE_URL = "http://bouzoubad.free.fr/log.php"; public ProgressDialog progressDialog; private EditText UserEditText; private EditText PassEditText; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialisation d'une progress bar progressDialog = new ProgressDialog(this); progressDialog.setMessage("Please wait..."); progressDialog.setIndeterminate(true); progressDialog.setCancelable(false); // Récupération des éléments de la vue définis dans le xml UserEditText = (EditText) findViewById(R.id.username); PassEditText = (EditText) findViewById(R.id.password); Button button = (Button) findViewById(R.id.okbutton); // Définition du listener du bouton button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int usersize = UserEditText.getText().length(); int passsize = PassEditText.getText().length(); // si les deux champs sont remplis if (usersize > 0 && passsize > 0) { progressDialog.show(); String user = UserEditText.getText().toString(); String pass = PassEditText.getText().toString(); // On appelle la fonction doLogin qui va communiquer avec le PHP doLogin(user, pass); } else createDialog("Error", "Please enter Username and Password"); } }); button = (Button) findViewById(R.id.cancelbutton); // Création du listener du bouton cancel (on sort de l'appli) button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { quit(false, null); } }); } private void quit(boolean success, Intent i) { // On envoie un résultat qui va permettre de quitter l'appli setResult((success) ? Activity.RESULT_OK : Activity.RESULT_CANCELED, i); finish(); } private void createDialog(String title, String text) { // Création d'une popup affichant un message AlertDialog ad = new AlertDialog.Builder(this) .setPositiveButton("Ok", null).setTitle(title).setMessage(text) .create(); ad.show(); } private void doLogin(final String login, final String pass) { final String pw = md5(pass); // Création d'un thread Thread t = new Thread() { public void run() { Looper.prepare(); // On se connecte au serveur afin de communiquer avec le PHP DefaultHttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000); HttpResponse response; HttpEntity entity; try { // On établit un lien avec le script PHP HttpPost post = new HttpPost(UPDATE_URL); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", login)); nvps.add(new BasicNameValuePair("password", pw)); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); // On passe les paramètres login et password qui vont être récupérés // par le script PHP en post post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // On récupère le résultat du script response = client.execute(post); entity = response.getEntity(); InputStream is = entity.getContent(); // On appelle une fonction définie plus bas pour traduire la réponse read(is); is.close(); if (entity != null) entity.consumeContent(); } catch (Exception e) { progressDialog.dismiss(); createDialog("Error", "Couldn't establish a connection"); } Looper.loop(); } }; t.start(); } private void read(InputStream in) { // On traduit le résultat d'un flux SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp; try { sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); // Cette classe est définie plus bas LoginContentHandler uch = new LoginContentHandler(); xr.setContentHandler(uch); xr.parse(new InputSource(in)); } catch (ParserConfigurationException e) { } catch (SAXException e) { } catch (IOException e) { } } private String md5(String in) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(in.getBytes()); byte[] a = digest.digest(); int len = a.length; StringBuilder sb = new StringBuilder(len << 1); for (int i = 0; i < len; i++) { sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16)); sb.append(Character.forDigit(a[i] & 0x0f, 16)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } private class LoginContentHandler extends DefaultHandler { // Classe traitant le message de retour du script PHP private boolean in_loginTag = false; private int userID; private boolean error_occured = false; public void startElement(String n, String l, String q, Attributes a) throws SAXException { if (l == "login") in_loginTag = true; if (l == "error") { progressDialog.dismiss(); switch (Integer.parseInt(a.getValue("value"))) { case 1: createDialog("Error", "Couldn't connect to Database"); break; case 2: createDialog("Error", "Error in Database: Table missing"); break; case 3: createDialog("Error", "Invalid username and/or password"); break; } error_occured = true; } if (l == "user" && in_loginTag && a.getValue("id") != "") // Dans le cas où tout se passe bien on récupère l'ID de l'utilisateur userID = Integer.parseInt(a.getValue("id")); } public void endElement(String n, String l, String q) throws SAXException { // on renvoie l'id si tout est ok if (l == "login") { in_loginTag = false; if (!error_occured) { progressDialog.dismiss(); Intent i = new Intent(); i.putExtra("userid", userID); quit(true, i); } } } public void characters(char ch[], int start, int length) { } public void startDocument() throws SAXException { } public void endDocument() throws SAXException { } } }
Merci
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Gyropode</string> <string name="bienvenue">Bienvenue</string> <string name="menu_settings">Settings</string> <string name="Start">Start</string> <string name="title_activity_avertissements">Avertissements</string> <string name="avertissements">Avertissement</string> <string name="avertissements1"> - Le port du casque est obligatoire.</string> <string name="avertissements2"> - Toute modification du système engendre une perte de la garantie constructeur.</string> <string name="avertissements3"> - Ne pas utliser le gyropode sous la pluie ou sur sol humide.</string> <string name="avertissements4"> - Toute personne mesurant moins de 1m40, pesant moins de 40kg ou plus de 90kg, ne doit pas utliser le gyropode.</string> <string name="avertissements5"> - Interdit au moins de 16 ans.</string> <string name="avertissements6"> - Ne pas utiliser la tablette en présence de vapeurs.</string> <string name="avertissements7"> - Ne pas utliser la tablette en dehors des températures recommandées (entre 0°C et 40°C).</string> <string name="avertissements8"> - Ne pas placer de charges trop importantes sur le guidon.</string> <string name="OK">J\'accepte</string> <string name="Avertissement">Avertissement</string> <string name="bug">Test : Si vous ne voyez pas un cercle en rotation cela veut dire que l\'application ne fonctionne pas.</string> <string name="Username">Username</string> <string name="Password">Password</string> <string name="Login">Login</string> <string name="Cancel">Cancel</string> <string name="hint_password">password</string> <string name="hint_username">username</string> <string name="title_activity_main">main</string> <string name="title_activity_login">Login</string> <string name="please">Veuillez vous identifier avec votre username et le mot de passe fourni.</string> <string name="TextView">TEST</string> </resources>
Partager