Android:从JSON获取数据

Android:从JSON获取数据

问题描述:

I am trying to get data from a MySQL Database to my Android-App. I am able to get a String but that is not really comfortable if I want more then just one data...

I read about something like JSON and were trying some example codes but I always get error messages like

"08-26 17:44:30.914: E/log_tag(9780): Error parsing data org.json.JSONException: No value for table1"

or

"08-26 17:45:52.403: E/log_tag(11220): Error parsing data org.json.JSONException: Value {"Role":"adminstrator","1":"0","age":"0","0":"adminstrator"} of type org.json.JSONObject cannot be converted to JSONArray"

So what do i make wrong?

PHP Script:

<?php
$con=mysqli_connect(****);
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT Role, age FROM table1 where 
Username='$username' and Password='$password'");
$row = mysqli_fetch_array($result);
print json_encode($row);
mysqli_close($con);
?>

Android codesnippet

        String result = sb.toString();

      //parse json data
        try{
            //JSONObject object = new JSONObject(result);
            //JSONArray jArray = object.getJSONArray("table1");
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","age: "+json_data.getInt("age")+
                                ", role: "+json_data.getString("Role")
                        );
                }
        }
        catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }

Content of result: {"0":"adminstrator","Role":"adminstrator","1":"0","age":"0"}

Thank you for your help!

You have a JSONOBject not an array

try{
    JSONObject json_data = new JSONObject(result);
    Log.i("log_tag","age: " + json_data.getString("age") +
                  ", role: "+json_data.getString("Role"));
}
catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
}

Don't use getInt since all the values have quotes, use getString instead.


For all users:

PHP

$result = mysqli_query($con,"SELECT Role, age FROM table1 ");
$json = array();
while($row = mysqli_fetch_array($result)){
    $json[] = $row;
}
mysqli_close($con);
print json_encode($json);

JAVA

try{
    JSONArray jArray = new JSONArray(result);
    for(int i=0;i<jArray.length();i++){
       JSONObject json_data = jArray.getJSONObject(i);
       Log.i("log_tag","age: " + json_data.getString("age") +
                      ", role: "+json_data.getString("Role"));
    }
}
catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
}