Sarmad Sarmad - 1 month ago 6
JSON Question

Returning multiple JSON from php to android using volley

I have two tables

UserName Name
user01 name01
user02 name02


my second table

Name Subject
name01 math
name01 english


My php:

if($_SERVER['REQUEST_METHOD']=='GET'){

$id = $_GET['UserName'];
require_once('connect.php');

$sql = "SELECT * FROM mytable WHERE UserName='".$id."'";
$r = mysqli_query($con,$sql);


$result = array();
while($row = mysqli_fetch_array($r)){
array_push($result,array(
'UserName'=>$row[0],
'name'=>$row[1],

)
);
$sqll= "SELECT * FROM subjecttable WHERE UserName='".$id."'";
$r = mysqli_query($con,$sql);

}

echo json_encode(array("result"=>$result));

mysqli_close($con);

}

echo json_encode(array("result" => $result));


now I have to receive the json inside while loop as well as the json outside the loop… right now I can receive the json outside while loop

my android code for retrieving the json outside the while loop

try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
for (int x = 0; x < result.length(); x++) {
JSONObject collegeData = result.getJSONObject(x);
username = collegeData.getString(config.KEY_UserName);
name = collegeData.getString(config.KEY_NAME);
}
} catch (JSONException e) {
e.printStackTrace();
}


Inside that while loop it will return the subjects in my second table and I should retrieve all of them…

Answer

Well...I did receive the multiple jsons but combining them both

    {
"result":[
{"date":"01-01-2016",
"day_name":"Friday"},{"date":"02-01-2016",
"day_name":"Saturday"},{"date":"03-01-2016",
"day_name":"Sunday"},{"date":"04-01-2016",
"day_name":"Monday"},{"date":"05-01-2016",
"day_name":"Tuesday"},{"date":"06-01-2016",
"day_name":"Wednesday"},{"date":"07-01-2016",
"day_name":"Thursday"},
{MY OTHER JSON EXAMPLE--->"monday":"9",
"tuesday":"9" }]}

Then i used two for loops inside onresponse

First for loop was 0 to result.length-1...That wont include the last array Then the second for was from result.length-1 to result.length. With this implementation i was able to take different jsons when a single onResponse

NOTE The second json should not be a repeating set.

 private void showJSON(String response){
    try {
        JSONObject jsonObject =new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
        for(int x=0;x<result.length()-1;x++) {

            JSONObject collegeData = result.getJSONObject(x);
            //collecting present object in json
            ClassList.add(new totalClassObject(collegeData.getString("date"),collegeData.getString("day_name")));
            RefreshListVIew();

        }
        for(int x=result.length()-1;x<result.length();x++) {

            JSONObject collegeDays = result.getJSONObject(x);
            //For Fetching Second type json
        }


    } catch (JSONException e) {

        e.printStackTrace();
    }

}
Comments