Reputation: 3011
I am reading a php response in an android method.
PHP
if(mysqli_num_rows($result)>0) {
$status = "Success!";
echo "Success!";
} else {
echo "Login failed";
}
Android
@Override
protected void onPostExecute(String result) {
if(result.equals("Success!")) {
Toast.makeText(context, "Login Successful!", Toast.LENGTH_LONG).show();
Intent goToWelcomePage = new Intent(context, welcome.class);
context.startActivity(goToWelcomePage);
} else if (result.equals("User Created")){
Toast.makeText(context, "User Created. Login Now.", Toast.LENGTH_LONG).show();
Intent goToLoginPage = new Intent(context, MainActivity.class);
context.startActivity(goToLoginPage);
} else {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
The above script is working without any trouble.
However, I want to read an array of results.I tried this in PHP.
$status = array();
if(mysqli_num_rows($result)>0) {
$status = "Success!";
echo json_encode(array("result"=>$status,"name"=>$username));
} else {
$status = "Login failed";
echo json_encode(array("result"=>$status));
}
Not sure how to read this in Android. Besides, I am not sure if the above php is the right way to return results to android.
Upvotes: 2
Views: 38
Reputation: 396
No problem in the PHP code, at least it can return a correct json as you expected if what you want is:
{"result":"Success!","name":"YOUR_LOGIN_NAME"}
or
{"result":"Login failed"}
In Android, you should use a json parser library to parser the "result" such as Gson(https://github.com/google/gson).
you can create a response class like:
class MyResponse {
String result;
String name;
}
then you can simply call in your code:
@Override
protected void onPostExecute(String result) {
Gson gson = new Gson();
MyResponse response = gson.fromJson(result, MyResponse.class);
switch (response.result) {
case "Success!":
// do something when login success
// can call response.name here to read the login name
break;
case "Login failed":
// do something when login failed
break;
// and more...
}
And if you are interested in a modern HTTP client, you can have a look:
okhttp (https://github.com/square/okhttp)
retrofit (https://github.com/square/retrofit)
Upvotes: 1