1 pièce(s) jointe(s)
Passer d'une vue à une autre
Bonsoir,
J'ai établi la connexion entre mon application android et ma BDD mysql via un script php. Par la suite j'ai essayé de passer de cette première vue d'authentification à une deuxième vue qui va afficher les informations personnelles de l'utilisateur connecté en les récupérant de la BDD.
Toutefois, après avoir confirmé l'exactitude du login et du mot de passe saisis, l'émulateur m'affiche dans la deuxième vue l'url vers mon script php et non pas les informations demandées :(
Ci-dessous mon code:
Activity principale:
Code:
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
| package com.test.log2;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login2Activity extends Activity {
EditText un,pw;
TextView error;
Button ok;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
un=(EditText)findViewById(R.id.edittext_un);
pw=(EditText)findViewById(R.id.edittext_pw);
ok=(Button)findViewById(R.id.button_login);
error=(TextView)findViewById(R.id.textview_error);
ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
//String valid = "1";
String response = null;
try {
response = httpclient.executeHttpPost("http://10.0.2.2/mesRequetes/log.php", postParameters);
String res=response.toString();
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
{
error.setText("Correct Username and Password");
Intent intent = new Intent(Login2Activity.this, DonneesPersonnelles.class);
startActivity(intent);
}
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}
}
});
}
} |
hpptclient.java
Code:
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
| package com.test.log2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
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.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class httpclient {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} |
Deuxième vue:
Code:
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
| package com.test.log2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DonneesPersonnelles extends Activity {
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Définir le texte et appeler la fonction de connexion.
txt.setText("Connexion...");
// Appeler la méthode pour récupérer les données JSON
txt.setText(getServerData(strURL));
}
public static final String strURL = "http://10.0.2.2/mesRequetes/donnees.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username","password"));
// Envoie de la commande http
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convertion de la requête en string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
// Parse les données JSON
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
// Affichage ID_ville et Nom_ville dans le LogCat
Log.i("log_tag","username: "+json_data.getInt("username")+
", password: "+json_data.getString("password")
);
// Résultats de la requête
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
} |
Résultat:
Pièce jointe 91062
Veuillez m'aider à trouver d'où vient l'erreur
Merci d'avance
passer d'une view à une autre
Bonjour,
Merci pour votre réponse.
En fait, j'ai découvert qu'il y a des erreurs au niveau de mon code.
Voilà ma version actuelle:
Code:
1 2 3 4 5 6 7 8 9
| <?php
mysql_connect("localhost","root","");
mysql_select_db("ayda2");
$sql=mysql_query("SELECT * FROM candidat WHERE id_can like '".$_REQUEST['identifiant']."%'");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?> |
Code:
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
| package com.test.log2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DonneesPersonnelles extends Activity {
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Définir le texte et appeler la fonction de connexion.
txt.setText("Connexion...");
// Appeler la méthode pour récupérer les données JSON
txt.setText(getServerData(strURL));
}
public static final String strURL = "http://10.0.2.2/mesRequetes/donnees.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("identifiant", "9090909"));
// Envoie de la commande http
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convertion de la requête en string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
// Parse les données JSON
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id_can: "+json_data.getInt("id_can"));
// Résultats de la requête
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
} |
Maintenant, après mon identification, l'émulateur m'affiche dans la deuxième view les informations relatives à l'utilisateur dont l'identifiant est 9090909. J'ai testé avec les différents logins et mots de passe que 'ai dans la base, mais le résultat est toujours le même.
passer d'une view à une autre
En fait, j'ai modifié le code et voilà le nouveau:
première activity:
Code:
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
| package com.test.log2;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login2Activity extends Activity {
EditText un,pw;
TextView error;
Button ok;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
un=(EditText)findViewById(R.id.edittext_un);
pw=(EditText)findViewById(R.id.edittext_pw);
ok=(Button)findViewById(R.id.button_login);
error=(TextView)findViewById(R.id.textview_error);
ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
String response = null;
try {
response = httpclient.executeHttpPost("http://10.0.2.2/mesRequetes/log.php", postParameters);
String res=response.toString();
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
{
error.setText("Correct Username and Password");
//ton champ
EditText usern = (EditText) findViewById(R.id.edittext_un);
// ta valeur
String loginStr = usern.getText().toString();
// ton champ
EditText passw = (EditText) findViewById(R.id.edittext_pw);
//ta valeur
String passStr = passw.getText().toString();
Intent intent = new Intent(Login2Activity.this, DonneesPersonnelles.class);
//On rajoute les valeurs à l'Intent
intent.putExtra("username", loginStr);
intent.putExtra("password", passStr);
startActivity(intent);
}
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}
}
});
}
} |
Deuxième activity:
Code:
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
| package com.test.log2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.test.log2.Login2Activity;
public class DonneesPersonnelles extends Activity {
TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
txt.setText("Connexion...");
txt.setText(getServerData(strURL));
}
public static final String strURL = "http://10.0.2.2/mesRequetes/donnees.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
Intent intent = getIntent();
String usern = intent.getExtras().getString("username");
String passw = intent.getExtras().getString("password");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", usern));
nameValuePairs.add(new BasicNameValuePair("password", passw));
// Envoie de la commande http
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","username: "+json_data.getString("username")+
",password: "+json_data.getString("password"));
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
} |
Suite à mon identification, l'émulateur m'affiche le même résultat (URL du fichier php) et le LogCat m'affiche ceci:
Code:
1 2 3 4 5 6 7 8 9 10 11 12
| 03-10 20:49:15.487: W/KeyCharacterMap(200): No keyboard for id 0
03-10 20:49:15.557: W/KeyCharacterMap(200): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
03-10 20:49:23.007: D/dalvikvm(200): GC freed 3216 objects / 200360 bytes in 102ms
03-10 20:49:23.117: I/global(200): Default buffer size used in BufferedReader constructor. It would be better to be explicit if an 8k-char buffer is required.
03-10 20:49:23.587: E/log_tag(200): Error parsing data org.json.JSONException: A JSONArray text must start with '[' at character 1 of <br />
03-10 20:49:23.587: E/log_tag(200): <font size='1'><table class='xdebug-error' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
03-10 20:49:23.587: E/log_tag(200): <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: identifiant in C:\wamp\www\mesRequetes\donnees.php on line <i>4</i></th></tr>
03-10 20:49:23.587: E/log_tag(200): <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
03-10 20:49:23.587: E/log_tag(200): <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
03-10 20:49:23.587: E/log_tag(200): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0013</td><td bgcolor='#eeeeec' align='right'>366720</td><td bgcolor='#eeeeec'>{main}( )</td><td title='C:\wamp\www\mesRequetes\donnees.php' bgcolor='#eeeeec'>..\donnees.php<b>:</b>0</td></tr>
03-10 20:49:23.587: E/log_tag(200): </table></font>
03-10 20:49:23.587: E/log_tag(200): [{"id_can":"2020202","username":"alex","password":"1234567","Nom":"kef","Prenom":"Mirez","DNaiss":"1985-07-16","Diplome":"Genie civil"},{"id_can":"9090909","username":"lily","password":"azerty","Nom":"hani","Prenom":"lilia","DNaiss":"1987-11-09","Diplome":"informatique"},{"id_can":"998898989","username":"dadad","password":"010101","Nom":"hani","Prenom":"haifa","DNaiss":null,"Diplome":"Maintenance industrielle"}] |