gosulove gosulove - 3 months ago 11
JSON Question

Android Json data(output from mysqli) is not working in TextView

I am doing some basic test for displaying json data that's output from PHP mysqli into TextView.

TextView mTxtDisplay;

String url = "http://192.168.1.102/web_service/test.php/";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTxtDisplay = (TextView) findViewById(R.id.tv);

JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
mTxtDisplay.setText(response.toString());
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub

}
});

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsObjRequest);
}}


192.168.1.102/web_service/test.php

$sql="SELECT * FROM item where uid='1'";
$result = mysqli_query($conn, $sql);
$myArray = array();
if (mysqli_num_rows($result) > 0) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}


output

[{"iid":"482","uid":"1","item_id":"1","item_name":"Chicken Rice","item_price":"1","item_quantity":"1","status":"0"},
{"iid":"483","uid":"1","item_id":"1","item_name":"French Fries","item_price":"1","item_quantity":"1","status":"0"},
{"iid":"484","uid":"1","item_id":"1","item_name":"apple","item_price":"1","item_quantity":"1","status":"0"},
{"iid":"492","uid":"1","item_id":"1","item_name":"western+italian","item_price":"1","item_quantity":"1","status":"0"},
{"iid":"493","uid":"1","item_id":"1","item_name":"no_cat","item_price":"1","item_quantity":"1","status":"0"}]


I think my json is correct? But it simply doesn't display in Textview, it's EMPTY! without any errors .

After that, I realized data in the below format is working well(normal hard code Array).

{
"1":{"name":"Superman","date":"20160909","location":"Mars"},
"2":{"name":"Xman","date":"20160909","location":"Galaxy"},
"3":{"name":"Batman","date":"20160909","location":"Earth"}
}


So that means the second json data without "[]" works fine but the first json data with "[]" is not working. But this shouldn't be the way right?

What's wrong with the coding?

Answer

It is because data within [] is JSONArray not JSONObject. Instead of JSONObjectRequest try StringRequest and then print your response into EditText/TextView. You can access elements of your array to by converting them into JSONArray.

JSONArray arr=new JSONArray(response);