Attendre la fin d'une AsyncTask
Bonjour à tous.
Tout d'abord merci à ceux qui prendront le temps de me lire et de m'aider.
Voilà le topo :
- une application Android qui se connecte à un serveur PHP, via un log et un mdp. Le serveur envoie des données au format JSON comme réponses au client Android.
- j'arrive à me connecter, à récupérer une réponse du serveur (dès la connexion on reçoit "success" ou "no" en format JSON) et j'arrive à transformer l'objet JSON reçu en objet JAVA.
- J'ai deux classes :
---mon activité possède deux simples EditText (log et mdp) et un bouton de connexion.
---une classe qui hérite de AsyncTask. C'est dans le onPostExecute que je transforme la réponse reçue JSON en Java.
Jusque là, tout fonctionne, et tout est bon d'après ce qu'affiche le Logcat.
Mon PROBLEME :
--> Je n'arrive pas à récupérer cette variable (réponse JSON tranformée en Java dans le onpostexecute) dans mon activité...
Voilà le code de ma classe AsyncTask Héritée:
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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class HTTPRequest extends AsyncTask<String, Void, String> {
private String[][] params;
private String url;
static private String fullUrl;
static String reponse = "";
static String objetJson = "";
EditText displayRep;
public HTTPRequest(String url, String[][] params) {
this.url = url;
this.params = params;
createFullURL();
}
public void createFullURL(){
fullUrl = url;
for(int i=0; i <= params.length ; i++)
{
if(i!=0)
fullUrl = fullUrl + "&" + params[0][i] + "=" + params[1][i];
else
fullUrl = fullUrl + params[0][i] + "=" + params[1][i];
}
System.out.println(fullUrl);
}
public HTTPRequest() {
}
@Override
protected String doInBackground(String... urls) {
return GET();
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
JSONObject json;
try {
json = new JSONObject(reponse);
objetJson = json.getString("success");
} catch (JSONException e){
System.out.println(e);
}
displayRep.setText(result);
System.out.println("Objet JSON222 = " + objetJson);
}
public static String GET(){
InputStream inputStream = null;
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(fullUrl));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if (inputStream != null) {
reponse = convertInputStreamToString(inputStream);
System.out.println("result1 = "+reponse);
}
else {
reponse = "Did not work!";
System.out.println("Message reponse vaut NULL : "+reponse);
}
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return reponse;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null) {
result += line;
}
inputStream.close();
return result;
}
public void setDisplayRep(EditText test) {
this.displayRep = test;
}
public String getObjJSON() {
return objetJson;
}
} |
Et là le code de mon Activité :
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
|
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
public class MainActivity extends Activity {
String login = null;
String motDePasse = null;
Button connexion = null;
Button effacer = null;
EditText log = null;
EditText mdp = null;
EditText etResponse;
HTTPRequest req;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
connexion = (Button)findViewById(R.id.connec);
effacer = (Button)findViewById(R.id.eff);
log = (EditText)findViewById(R.id.log);
mdp = (EditText)findViewById(R.id.mdp);
etResponse = (EditText) findViewById(R.id.etResponse);
// on attribue un listener aux vues log, mdp, connexion et effacer
connexion.setOnClickListener(connexionListener);
effacer.setOnClickListener(effacerListener);
log.addTextChangedListener(textWatcher);
mdp.addTextChangedListener(textWatcher);
}
// TEXTWATCHER : quand les EditTextView Login et mdp changent
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
login = log.getText().toString();
motDePasse = mdp.getText().toString();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
};
// LISTENER : Pour le bouton de connexion
private OnClickListener connexionListener = new OnClickListener() {
@Override
public void onClick(View v) {
//String adr = "http://192.168.1.19/projetandroid/data.php?action=Connexion&";
String adr = "http://10.0.2.2/AndroidApp_Serveur/data.php?";
String[][] params = { {"action","login","mdp"},{"Connexion",login,motDePasse} };
req = new HTTPRequest(adr, params);
req.setDisplayRep(etResponse);
req.execute("GET");
String test = req.getObjJSON();
if(test.equals("success")) {
System.out.println("coucou = "+test);
}
else if(test.equals("no")) {
System.out.println("coucou = "+test);
}
}
};
// LISTENER : Pour le bouton Effacer
private OnClickListener effacerListener = new OnClickListener() {
@Override
public void onClick(View v) {
log.getText().clear();
mdp.getText().clear();
}
};
} |
En fait quand je lance l'appli, je rentre mes identifiants, je clique sur connexion et là j'ai bien l'affichage du "success" venant du
Code:
System.out.println("Objet JSON = " + objetJson);
(qui vient de la méthode onPostexecute)
Par contre cela ne rentre jamais dans le
Code:
if(test.equals("success")) {
de la méthode onClick de mon activité.
SANS QUITTER l'application, je change mes logs (pour mettre des faux) et je clique sur connexion. Cette fois j'ai bien le "NO" de l'affichage dans le onpostexecute. Par contre côté activité, cela rentre dans le if cette fois, mais avec la valeur "success" ..8O
Voilà le soucis ... J'ai l'impression que mon moyen pour récupérer la variable côté activité n'est pas le bon...
J'ai pensé que l'AsyncTask n'était pas finie quand je voulais récupérer la variable, mais comme je le vois dans le logcat, ca rentre bien dans le onPostExecute donc je ne comprend pas ...
Merci à ceux qui pourrait m'aider en tout cas, désolé du super long post surtout.
Bonne soirée