0

How to fetch this Two Json Response and save the json response in SQLite. Hope you will guide me how to fetch this Json object inside a Json Array inside an Object

My problem is a cannot fetch the 2nd json response. I noticed that only the 1st response was returned

Login response in Logcat

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}

only the 1st response was returned in this Logcat

D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute: false
D/TEST: org.json.JSONException: No value for sl_summ

This is the 1st Json response. Was parse and stored in SQLite

{  
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}

This is the 2nd Json response. Json object inside a JSON Array. Was not parse and inserted in SQLite

{
  "error": false,
  "sl_summ": 
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

Whole JSON response

{  
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ": 
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

This is my Login.java

try {
    JSONObject jObj = new JSONObject(response.toString());
    boolean error = jObj.getBoolean("error");
    Log.d(TAG, "Checking JSON Object" +jObj);

    Log.d("TEST", "-error attribute             : " + jObj.get("error").toString());
    // Check for error node in json
    if (!error) {
        // user successfully logged in
        // Create login session
        session.setLogin(true);

        // Now store the user in SQLite
        //String uid = jObj.getString("uid");

        JSONObject user = jObj.getJSONObject("user");
            Log.d("USER", "-user object     : " + jObj.getJSONObject("user").toString());
        String br_code = user.getString("br_code");
            Log.d("USER", "-br_code         : " + br_code);
        String mem_id = user.getString("mem_id");
            Log.d("USER", "-mem_id          : " + mem_id);
        String username = user.getString("username");
            Log.d("USER", "-username        : " + username);
        String email = user.getString("email");
            Log.d("USER", "-email           : " + email);
        String created_at = user.getString("created_at");
            Log.d("USER", "-created at      : " + created_at);

        // Inserting row in users table
        db.addUser(br_code, mem_id, username, email, created_at);

        //SL Details
        try {
            // read the json string into a json object
            JSONObject jsonObject = new JSONObject(response.toString());
            Log.d("sl_summ", "JSON String                  : " + jsonObject.toString());
            // access individual json object thru jsonObject.get("FIELD_NAME")
            Log.d("sl_summ", "-error attribute             : " + jsonObject.get("error").toString());
            // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
            Log.d("sl_summ", "-sl_summ array               : " + jsonObject.getJSONArray("sl_summ").toString());
            JSONArray array = ((JSONArray)jsonObject.getJSONArray("sl_summ"));
            for (int index=0; index<array.length(); index++) {
                JSONObject object = (JSONObject)array.get(index);
                Log.d("SL_SUUM", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                Log.d("SL_SUUM", "-tr_date attribute           : " + object.get("tr_date").toString());
                Log.d("SL_SUUM", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                Log.d("SL_SUUM", "-available_balance attribute : " + object.get("available_balance").toString());
                Log.d("SL_SUUM", "---------------------------------");
            }
        } catch (Exception exception) {
            Log.d("TEST", exception.toString());
        }

        // Launch main activity
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    } else {
        // Error in login. Get the error message
        String errorMsg = jObj.getString("error_msg");
        Toast.makeText(getApplicationContext(),
                errorMsg, Toast.LENGTH_LONG).show();
    }
} catch (JSONException e) {
    // JSON error
    e.printStackTrace();
    Log.d("TEST", e.toString());
    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}

SQlitehandler.java

public void addUserSLDTL(String sl_desc, String tr_date, String  actual_balance, String avail_balance){
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(SL_DESC, sl_desc); // sl desc
    values.put(TR_DATE, tr_date); // trans date
    values.put(ACTUAL_BALANCE, actual_balance); // actual balance
    values.put(AVAILABLE_BALANCE, avail_balance); // availabe balance

    // Inserting Row
    long id = db.insertOrThrow(TABLE_MEMBERS_SLDTL, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "Members's SL Details was inserted into sldtl table: " + id);
    Log.d(TAG, "SL Desc: " + sl_desc);
    Log.d(TAG, "Transaction Date: " + tr_date);
    Log.d(TAG, "Actual Balance: " + actual_balance);
    Log.d(TAG, "Available Balance: " + avail_balance);
}

public HashMap<String, String> getUserSLDTL() {
    HashMap<String, String> sl_summ = new HashMap<String, String>();
    String selectQuery = "SELECT * FROM " + TABLE_MEMBERS_SLDTL;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        sl_summ.put("sl_desc", cursor.getString(0));
        sl_summ.put("tr_date", cursor.getString(1));
        sl_summ.put("actual_balance", cursor.getString(2));
        sl_summ.put("avail_balance", cursor.getString(3));

        Log.d(TAG, "member's SLDTL data: " + sl_summ.toString());
    }
    else{
        Log.d(TAG, "member's SLDTL data is empty");
    }
    cursor.close();
    db.close();

    // return user
    Log.d(TAG, "Fetching member's SL details from Sqlite sldtl table: " + sl_summ.toString());

    return sl_summ;
}

Logcat message

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
D/InputTransport: Input channel destroyed: fd=76
D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/TEST: -error attribute             : false
D/SessionManager: User login session modified!
D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
D/USER: -br_code         : 12
D/USER: -mem_id          : 13
D/USER: -username        : novalyn
D/USER: -email           : gsac_tabaco@yahoo.com
D/USER: -created at      : 2016-07-22 09:05:21
D/SQLiteHandler: New member was inserted into table members: 13
D/SQLiteHandler: BR CODE: 12
D/SQLiteHandler: Member ID: 13
D/SQLiteHandler: Username: novalyn
D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
D/SQLiteHandler: Created at: 2016-07-22 09:05:21
D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ

Login.php

<?php
session_start();
require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);
$br_response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();

$arclass = "13";
$loanclass = "12";
$accintreceivable = "21";

if (isset($_POST['username']) && isset($_POST['password'])) {

    // receiving the post params
    $username= $_POST['username'];
    $password = $_POST['password'];

    // get the user by username and password
    $user = $db->getUserByUsernameAndPassword($username, $password);

    if ($user != null) {
        // user is found
        $response["error"] = FALSE;
        $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
        $response["user"]["mem_id"] = $user["MEMBER_ID"];
        $response["user"]["username"] = $user["USERNAME"];
        $response["user"]["email"] = $user["EMAIL"];
        $response["user"]["created_at"] = $user["REG_DATE"];
        json_encode($response, true);
        //Displaying json value
        echo json_encode($response, true);

        //$_SESSION= json_encode($response, true);
        // $_SESSION['br_code']= $user["MEMBER_ID_BRCODE"];
        // $_SESSION['username']= $user["USERNAME"];
        // $_SESSION['mem_id']= $user["MEMBER_ID"];

        $br_code= $user["MEMBER_ID_BRCODE"];
        $clientid= $user["MEMBER_ID"];
        //Check if the branch of the user exist in the BRANCH table
        $user = $db->getBrnchInfo($br_code);
        //var_dump($user);
        if ($user != null) {
            $br_response["error"] = FALSE;
            $br_response["user_br"]["ar_class"] = $arclass;
            $br_response["user_br"]["loan_class"] = $loanclass;
            $br_response["user_br"]["accnt_receivable"] = $accintreceivable;
            $br_response["user_br"]["br_code"] = $user["br_id"];
            $br_response["user_br"]["br_desc"] = $user["br_desc"];
            $br_response["user_br"]["br_address"] = $user["br_add"];
            $br_response["user_br"]["br_manager"] = $user["br_manager"];
            $br_response["user_br"]["br_accronym"] = $user["br_accronym"];
            $br_response["user_br"]["br_trans_date"] = $user["br_trans_date"];
            //json_encode($br_response, true);
            //echo json_encode($br_response, true);

            $trans_date = strtotime($user["br_trans_date"]);
            $date  = date('d',$trans_date);
            $year  = date('Y',$trans_date);
            $month = date('m',$trans_date);

            $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

            If($user_sldtl != null) {
                 for($i = 0; $i < count($user_sldtl); $i++){
                    $item = array();
                        $item["sl_desc"] = $user_sldtl[$i][7];
                        $item["tr_date"] = $user_sldtl[$i][10];
                        $item["actual_balance"] = $user_sldtl[$i][14];
                        $item["available_balance"] = $user_sldtl[$i][14];

                        $response = array("error" => FALSE);
                        $sl_response["sl_summ"][] = $item;
                    }
                    json_encode($sl_response);
                    echo json_encode($sl_response, true);
             }
             else {
                 $sl_response["error"] = TRUE;
                 $sl_response["error_msg"] = "NO SL Details found!";
                 echo json_encode($sl_response);
             }
        }
        else {
            $response["error"] = TRUE;
            $response["error_msg"] = "No branch code found.!";
            json_encode($response);
           // echo json_encode($response);
        }

        //header('Location: accountsummary.php');
    } else {
        // user is not found with the credentials
        $response["error"] = TRUE;
        $response["error_msg"] = "Login credentials are wrong. Please try again!";
        json_encode($response);
        echo json_encode($response);
        // echo "<br />" .$username. "<br />";
        // echo $password;
    }
} else {
    // required post params is missing
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters username or password is missing!";
    json_encode($response);
    echo json_encode($response);
}
?>
Novice
  • 77
  • 2
  • 11

3 Answers3

0
// your JSON format is wrong . you should arrange proper json data format 
//Like this:-  
{
  "obj1": {
    "error": false,
    "user": {
      "br_code": 12,
      "mem_id": 13,
      "username": "novalyn",
      "email": "gsac_tabaco@yahoo.com",
      "created_at": "2016-07-22 09:05:21"
    }
  },
  "obj2": {
    "error": false,
    "sl_summ": [
      {
        "sl_desc": "PA : Savings Account",
        "tr_date": "2015-08-17",
        "actual_balance": "483.67",
        "available_balance": "483.67"
      },
      {
        "sl_desc": "PA : Savings - Cash Bond",
        "tr_date": "2015-08-28",
        "actual_balance": "10129.43",
        "available_balance": "10129.43"
      }
    ]
  }
}
  • how can I do that sir? can you give me a sample code in php to correct my json response sir? – Novice Jul 06 '17 at 03:11
0

This is the correct format of your Json Response :

{
    "object1":{
        "error":false,
            "user":{
        "br_code":12,
                "mem_id":13,
                "username":"novalyn",
                "email":"gsac_tabaco@yahoo.com",
                "created_at":"2016-07-22 09:05:21"
    }
    }
    "object2":{
        "error":false,
            "sl_summ":
        [
        {
            "sl_desc":"PA : Savings Account",
                "tr_date":"2015-08-17",
                "actual_balance":"483.67",
                "available_balance":"483.67"
        },
        {
            "sl_desc":"PA : Savings - Cash Bond",
                "tr_date":"2015-08-28",
                "actual_balance":"10129.43",
                "available_balance":"10129.43"
        }
        ]
    }
}

Now parse your response using below method.

private void parseJsonResponse(String jsonString)
{
    try
    {
        JSONObject rootJsonObject = new JSONObject(jsonString);
        JSONObject object1 = rootJsonObject.has("object1") ? rootJsonObject.getJSONObject("object1") : new JSONObject();
        JSONObject object2 = rootJsonObject.has("object2") ? rootJsonObject.getJSONObject("object2") : new JSONObject();

       // Now get remaining values from object1 and object2

    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
Vishal Chhodwani
  • 2,567
  • 5
  • 27
  • 40
0

NOTE: as mentioned in previous question, the given JSON string needs to be in correct format i.e. either have a key for each object (login, accounts) or have them in a single array (input). I am giving solution for both the options.

Novice, I am providing you 2 separate methods so that you can handle incoming JSON string depending on how you construct it either 2 objects in single JSON String or 2 objects in an JSON array.

You can pick your solution :)

Try the code, let me know if you need more help and accept the answer.

OPTION1 : 2 Objects in single JSON string

{
   "login":{
      "error":false,
      "user":{
         "br_code":12,
         "mem_id":13,
         "username":"novalyn",
         "email":"gsac_tabaco@yahoo.com",
         "created_at":"2016-07-22 09:05:21"
      }
   },
   "accounts":{
      "error":false,
      "sl_summ":[
         {
            "sl_desc":"PA : Savings Account",
            "tr_date":"2015-08-17",
            "actual_balance":"483.67",
            "available_balance":"483.67"
         },
         {
            "sl_desc":"PA : Savings - Cash Bond",
            "tr_date":"2015-08-28",
            "actual_balance":"10129.43",
            "available_balance":"10129.43"
         }
      ]
   }
}

OPTION2 : 2 Objects in single JSON array string

{
   "input":[
      {
         "error":false,
         "user":{
            "br_code":12,
            "mem_id":13,
            "username":"novalyn",
            "email":"gsac_tabaco@yahoo.com",
            "created_at":"2016-07-22 09:05:21"
         }
      },
      {
         "error":false,
         "sl_summ":[
            {
               "sl_desc":"PA : Savings Account",
               "tr_date":"2015-08-17",
               "actual_balance":"483.67",
               "available_balance":"483.67"
            },
            {
               "sl_desc":"PA : Savings - Cash Bond",
               "tr_date":"2015-08-28",
               "actual_balance":"10129.43",
               "available_balance":"10129.43"
            }
         ]
      }
   ]
}

Code to handle both the scenarios (OPTION1 & OPTION2) of JSON String

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public static void jsonExample() {
    // OPTION 1
    String twoObjectString = "{ \"login\":{ \"error\":false, \"user\":{ \"br_code\":12, \"mem_id\":13, \"username\":\"novalyn\", \"email\":\"gsac_tabaco@yahoo.com\", \"created_at\":\"2016-07-22 09:05:21\" } }, \"accounts\":{ \"error\":false, \"sl_summ\":[ { \"sl_desc\":\"PA : Savings Account\", \"tr_date\":\"2015-08-17\", \"actual_balance\":\"483.67\", \"available_balance\":\"483.67\" }, { \"sl_desc\":\"PA : Savings - Cash Bond\", \"tr_date\":\"2015-08-28\", \"actual_balance\":\"10129.43\", \"available_balance\":\"10129.43\" } ] } }\n";
    // OPTION 2
    String arrayString = "{ \"input\": [ { \"error\":false, \"user\":{ \"br_code\":12, \"mem_id\":13, \"username\":\"novalyn\", \"email\":\"gsac_tabaco@yahoo.com\", \"created_at\":\"2016-07-22 09:05:21\" } }, { \"error\":false, \"sl_summ\":[ { \"sl_desc\":\"PA : Savings Account\", \"tr_date\":\"2015-08-17\", \"actual_balance\":\"483.67\", \"available_balance\":\"483.67\" }, { \"sl_desc\":\"PA : Savings - Cash Bond\", \"tr_date\":\"2015-08-28\", \"actual_balance\":\"10129.43\", \"available_balance\":\"10129.43\" } ] } ] }\n";
    try {
        Log.d("TEST", "COMBINED 2 OBJECTS             ");
        Log.d("TEST", "INPUT String                 : " + twoObjectString);
        JSONObject twoJSONObjects = new JSONObject(twoObjectString);
        handleTwoObjects(twoJSONObjects);

        Log.d("TEST", "2 OBJECTS IN ARRAY             ");
        Log.d("TEST", "INPUT String                   " + arrayString);
        JSONObject arrayJSONObject = new JSONObject(arrayString);
        handleArrayOfObjects(arrayJSONObject);
    } catch (Exception exception) {
        Log.d("TEST", exception.toString());
    }
}

// OPTION 1
public static void handleTwoObjects(JSONObject jsonObject)  throws Exception {
    // read the json string into a json object
    Log.d("TEST", "JSON String                  : " + jsonObject.toString());

    if (!jsonObject.isNull("login")) {
        JSONObject loginObject = (JSONObject) jsonObject.get("login");

        // access individual json object thru jsonObject.get("FIELD_NAME")
        Log.d("TEST", "-error attribute             : " + loginObject.get("error").toString());

        // Check if its login data i.e. user present
        if (!loginObject.isNull("user")) {
            // handle user login data
            JSONObject userJSONObject = (JSONObject) loginObject.get("user");
            Log.d("TEST", "User                         : " + userJSONObject.toString());
            Log.d("TEST", "-br_code attribute           : " + userJSONObject.get("br_code").toString());
            Log.d("TEST", "-mem_id attribute            : " + userJSONObject.get("mem_id").toString());
            Log.d("TEST", "-username attribute          : " + userJSONObject.get("username").toString());
            Log.d("TEST", "-email attribute             : " + userJSONObject.get("email").toString());
            Log.d("TEST", "-created_at attribute        : " + userJSONObject.get("created_at").toString());
            // Check if its account data i.e. sl_summ is present
        } else {
            // a new JSON string that doesn't have user in login Object
            Log.d("TEST", "Unknown JSON String          : " + loginObject.toString());
        }
    }

    if (!jsonObject.isNull("accounts")) {
        JSONObject accountsObject = (JSONObject) jsonObject.get("accounts");

        // access individual json object thru jsonObject.get("FIELD_NAME")
        Log.d("TEST", "-error attribute             : " + accountsObject.get("error").toString());

        JSONArray slArray = accountsObject.optJSONArray("sl_summ");

        // Check if its login data i.e. user present
        if (slArray != null) {
            // handle account data
            JSONArray array = ((JSONArray)accountsObject.getJSONArray("sl_summ"));
            // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
            Log.d("TEST", "-sl_summ array               : " + accountsObject.getJSONArray("sl_summ").toString());
            for (int index=0; index<array.length(); index++) {
                JSONObject object = (JSONObject)array.get(index);
                Log.d("TEST", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                Log.d("TEST", "-tr_date attribute           : " + object.get("tr_date").toString());
                Log.d("TEST", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                Log.d("TEST", "-available_balance attribute : " + object.get("available_balance").toString());
                Log.d("TEST", "---------------------------------");
            }
        } else {
            // a new JSON string that doesn't have sl_summ as member variable so display it and write new handler code
            Log.d("TEST", "Unknown JSON String          : " + jsonObject.toString());
        }
    }
}

// OPTION 2
public static void handleArrayOfObjects(JSONObject jsonObject)  throws Exception {
    // read the json string into a json object
    Log.d("TEST", "JSON String                  : " + jsonObject.toString());

    JSONArray inputArray = jsonObject.optJSONArray("input");

    if (inputArray != null && inputArray.length() > 0) {
        for (int oindex = 0; oindex < inputArray.length(); oindex++) {

            JSONObject currentObject = (JSONObject) inputArray.get(oindex);

            JSONArray slArray = currentObject.optJSONArray("sl_summ");

            // access individual json object thru jsonObject.get("FIELD_NAME")
            Log.d("TEST", "-error attribute             : " + currentObject.get("error").toString());

            // Check if its login data i.e. user present
            if (!currentObject.isNull("user") && slArray == null) {
                // handle user login data
                JSONObject userJSONObject = (JSONObject) currentObject.get("user");
                Log.d("TEST", "User                         : " + userJSONObject.toString());
                Log.d("TEST", "-br_code attribute           : " + userJSONObject.get("br_code").toString());
                Log.d("TEST", "-mem_id attribute            : " + userJSONObject.get("mem_id").toString());
                Log.d("TEST", "-username attribute          : " + userJSONObject.get("username").toString());
                Log.d("TEST", "-email attribute             : " + userJSONObject.get("email").toString());
                Log.d("TEST", "-created_at attribute        : " + userJSONObject.get("created_at").toString());
                // Check if its account data i.e. sl_summ is present
            } else if (slArray != null && currentObject.isNull("user")) {
                // handle account data
                JSONArray array = ((JSONArray)currentObject.getJSONArray("sl_summ"));
                // access individual json array thru jsonObject.getJSONArray("FIELD_NAME")
                Log.d("TEST", "-sl_summ array               : " + currentObject.getJSONArray("sl_summ").toString());
                for (int index=0; index<array.length(); index++) {
                    JSONObject object = (JSONObject)array.get(index);
                    Log.d("TEST", "-sl_desc attribute           : " + object.get("sl_desc").toString());
                    Log.d("TEST", "-tr_date attribute           : " + object.get("tr_date").toString());
                    Log.d("TEST", "-actual_balance attribute    : " + object.get("actual_balance").toString());
                    Log.d("TEST", "-available_balance attribute : " + object.get("available_balance").toString());
                    Log.d("TEST", "---------------------------------");
                }
            } else {
                // a new JSON string that doesn't have user or sl_summ as member variable so display it and write new handler code
                Log.d("TEST", "Unknown JSON String          : " + jsonObject.toString());
            }
        }
    }
}

Sample Logs for OPTION1 & OPTION2

07-05 20:21:58.001 8178-8178/? D/TEST: COMBINED 2 OBJECTS             
07-05 20:21:58.001 8178-8178/? D/TEST: INPUT String                 : { "login":{ "error":false, "user":{ "br_code":12, "mem_id":13, "username":"novalyn", "email":"gsac_tabaco@yahoo.com", "created_at":"2016-07-22 09:05:21" } }, "accounts":{ "error":false, "sl_summ":[ { "sl_desc":"PA : Savings Account", "tr_date":"2015-08-17", "actual_balance":"483.67", "available_balance":"483.67" }, { "sl_desc":"PA : Savings - Cash Bond", "tr_date":"2015-08-28", "actual_balance":"10129.43", "available_balance":"10129.43" } ] } }
07-05 20:21:58.001 8178-8178/? D/TEST: JSON String                  : {"login":{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}},"accounts":{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}}
07-05 20:21:58.001 8178-8178/? D/TEST: -error attribute             : false
07-05 20:21:58.001 8178-8178/? D/TEST: User                         : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
07-05 20:21:58.001 8178-8178/? D/TEST: -br_code attribute           : 12
07-05 20:21:58.001 8178-8178/? D/TEST: -mem_id attribute            : 13
07-05 20:21:58.001 8178-8178/? D/TEST: -username attribute          : novalyn
07-05 20:21:58.001 8178-8178/? D/TEST: -email attribute             : gsac_tabaco@yahoo.com
07-05 20:21:58.001 8178-8178/? D/TEST: -created_at attribute        : 2016-07-22 09:05:21
07-05 20:21:58.001 8178-8178/? D/TEST: -error attribute             : false
07-05 20:21:58.001 8178-8178/? D/TEST: -sl_summ array               : [{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_desc attribute           : PA : Savings Account
07-05 20:21:58.002 8178-8178/? D/TEST: -tr_date attribute           : 2015-08-17
07-05 20:21:58.002 8178-8178/? D/TEST: -actual_balance attribute    : 483.67
07-05 20:21:58.002 8178-8178/? D/TEST: -available_balance attribute : 483.67
07-05 20:21:58.002 8178-8178/? D/TEST: ---------------------------------
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_desc attribute           : PA : Savings - Cash Bond
07-05 20:21:58.002 8178-8178/? D/TEST: -tr_date attribute           : 2015-08-28
07-05 20:21:58.002 8178-8178/? D/TEST: -actual_balance attribute    : 10129.43
07-05 20:21:58.002 8178-8178/? D/TEST: -available_balance attribute : 10129.43
07-05 20:21:58.002 8178-8178/? D/TEST: ---------------------------------


07-05 20:21:58.002 8178-8178/? D/TEST: 2 OBJECTS IN ARRAY             
07-05 20:21:58.002 8178-8178/? D/TEST: INPUT String                   { "input": [ { "error":false, "user":{ "br_code":12, "mem_id":13, "username":"novalyn", "email":"gsac_tabaco@yahoo.com", "created_at":"2016-07-22 09:05:21" } }, { "error":false, "sl_summ":[ { "sl_desc":"PA : Savings Account", "tr_date":"2015-08-17", "actual_balance":"483.67", "available_balance":"483.67" }, { "sl_desc":"PA : Savings - Cash Bond", "tr_date":"2015-08-28", "actual_balance":"10129.43", "available_balance":"10129.43" } ] } ] }
07-05 20:21:58.002 8178-8178/? D/TEST: JSON String                  : {"input":[{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}},{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}]}
07-05 20:21:58.002 8178-8178/? D/TEST: -error attribute             : false
07-05 20:21:58.002 8178-8178/? D/TEST: User                         : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
07-05 20:21:58.002 8178-8178/? D/TEST: -br_code attribute           : 12
07-05 20:21:58.002 8178-8178/? D/TEST: -mem_id attribute            : 13
07-05 20:21:58.002 8178-8178/? D/TEST: -username attribute          : novalyn
07-05 20:21:58.002 8178-8178/? D/TEST: -email attribute             : gsac_tabaco@yahoo.com
07-05 20:21:58.002 8178-8178/? D/TEST: -created_at attribute        : 2016-07-22 09:05:21
07-05 20:21:58.002 8178-8178/? D/TEST: -error attribute             : false
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_summ array               : [{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_desc attribute           : PA : Savings Account
07-05 20:21:58.002 8178-8178/? D/TEST: -tr_date attribute           : 2015-08-17
07-05 20:21:58.002 8178-8178/? D/TEST: -actual_balance attribute    : 483.67
07-05 20:21:58.002 8178-8178/? D/TEST: -available_balance attribute : 483.67
07-05 20:21:58.002 8178-8178/? D/TEST: ---------------------------------
07-05 20:21:58.002 8178-8178/? D/TEST: -sl_desc attribute           : PA : Savings - Cash Bond
07-05 20:21:58.002 8178-8178/? D/TEST: -tr_date attribute           : 2015-08-28
07-05 20:21:58.002 8178-8178/? D/TEST: -actual_balance attribute    : 10129.43
07-05 20:21:58.002 8178-8178/? D/TEST: -available_balance attribute : 10129.43
07-05 20:21:58.002 8178-8178/? D/TEST: ---------------------------------

I do not have access to all the internal PHP files which i can use to run your PHP Code, so I replaced most of all the function calls with hard coded values as shared in sample response payload. Here is the code to generate JSON Objects in OPTION1 format.

In short, you have to add ["login"] and ["accounts"] ahead of all the sub attributes in $response so that they will be grouped in correct JSON Object and you will have two JSON objects that can be parsed with above android shared code.

<?php
// json response array
$br_response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();

$arclass = "13";
$loanclass = "12";
$accintreceivable = "21";

        // user is found
        $response["login"]["error"] = FALSE;
        $response["login"]["user"]["br_code"] = 12;
        $response["login"]["user"]["mem_id"] = 13;
        $response["login"]["user"]["username"] = "novalyn";
        $response["login"]["user"]["email"] = "gsac_tabaco@yahoo.com";
        $response["login"]["user"]["created_at"] = "2016-07-22 09:05:21";
                 for($i = 0; $i < 2; $i++){
                        $item = array();
                        $item["sl_desc"] = "PA : Savings Account";
                        $item["tr_date"] = "2015-08-17";
                        $item["actual_balance"] = "483.67";
                        $item["available_balance"] = "483.67";
                        $sl_response["sl_summ"][] = $item;
                    }
                    $response["accounts"] = $sl_response;
                    json_encode($response);
                    echo json_encode($response, true);

PHP Sample Run generated JSON response (OPTION1)

{
   "login":{
      "error":false,
      "user":{
         "br_code":12,
         "mem_id":13,
         "username":"novalyn",
         "email":"gsac_tabaco@yahoo.com",
         "created_at":"2016-07-22 09:05:21"
      }
   },
   "accounts":{
      "error":false,
      "sl_summ":[
         {
            "sl_desc":"PA : Savings Account",
            "tr_date":"2015-08-17",
            "actual_balance":"483.67",
            "available_balance":"483.67"
         },
         {
            "sl_desc":"PA : Savings Account",
            "tr_date":"2015-08-17",
            "actual_balance":"483.67",
            "available_balance":"483.67"
         }
      ]
   }
}

Code will be available for few days at https://codepad.remoteinterview.io/YJJKVUEAAH

JRG
  • 4,037
  • 3
  • 23
  • 34
  • thank you sir. so I need to change my JSON response format so that it can be parse and stored in database – Novice Jul 06 '17 at 03:48
  • Yes and then depending on how you construct (option 1 or 2), you can use above methods for parsing. – JRG Jul 06 '17 at 03:54
  • I have added sample PHP code that shows how to generate JSON String in OPTION1 format so that you can use the shared android code to parse it. – JRG Jul 06 '17 at 07:10
  • Hello sir Jigar. Can you help me how to have a dynamic TextView base in a table rows? https://stackoverflow.com/questions/45073047/how-to-add-textview-automatically-base-on-table-rows – Novice Jul 13 '17 at 06:44