Partage
  • Partager sur Facebook
  • Partager sur Twitter

Error parsing data

username not found

14 mars 2012 à 0:11:08

Bonsoir à tous,

Comme je débute sur android, je viens poser ma question sur le forum du siteduzero puisque je suis un zéro ^^ . En effet, j'ai créé une activité de login (qui marche bien)et je souhaiterai afficher suite à cette page les informations relatives à l'utilisateur connecté en les récupérant de la base de données mysql. Le problème c'est que (suite à l'identification), l'émulateur m'affiche dans la deuxième vue l'url correspondante à mon fichier php, et le LogCat retourne l'erreur suivante: Error parsing data org.json.JSONException: JSONObject["username"] not found.
Ci-dessous mon code:

Première activité:
[CODE]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());
}

}
});
}

}

[/CODE]

Deuxième activité (qui pose le problème)
[CODE]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;

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"));
// 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;
}
}
[/CODE]

script php:

[CODE]<?php
mysql_connect("localhost","root","");
mysql_select_db("mabase");
$sql=mysql_query("SELECT Nom FROM candidat WHERE username like '".$_REQUEST['username']."%' AND password like '".$_REQUEST['password']."%' ");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
[/CODE]

Merci de m'aider

Cordialement
  • Partager sur Facebook
  • Partager sur Twitter
14 mars 2012 à 9:22:26

Bonjour,

Il y a des règles à respecter sur le forum. En particulier, il faut que tu mettes une balise à ton titre et que tu utilises les balises de code. Comme ça fait beaucoup d'un coup, je ferme le sujet, mais n'hésite pas à en poster un nouveau en respectant ces points. ;)
  • Partager sur Facebook
  • Partager sur Twitter