答:
You can accomplish this using ng-model along with $formatters and $parsers.

See more explanation here:

ngModel Formatters and Parsers

This is a TypeScript adaptation from some code I use to force currency formats.

```<code>app.directive('myModelFormat', ['$filter', function myModelFormatDirective($filter:ng.IFilterService):ng.IDirective {

    return {
        require: '?ngModel',
        link: myModelFormatLink
    };

    function myModelFormatLink(scope:ng.IScope, elem:ng.IAugmentedJQuery, attrs:ng.IAttributes, ctrl:ng.INgModelController) {

        if (!ctrl) {
            return;
        }

        const decimalWithOneDigit:RegExp = new RegExp('\\' + STRINGS.decimalSym + '\\d$');

        ctrl.$formatters.unshift(function myModelFormatFormatter(ignore:any):string {
            return $filter(attrs['myModelFormat'])(ctrl.$modelValue)
        });

        ctrl.$parsers.unshift(function myModelFormatParser(viewValue:string):any {
            const plainNumber:number = parseFloat(viewValue);
            let formatted:string = $filter(attrs['myModelFormat'])(plainNumber);

            // special case where they typed the decimal symbol but not a decimal value,
            // make sure we don't remove the symbol which prevents them from typing a decimal
            if (_s.endsWith(viewValue, STRINGS.decimalSym)) {
                formatted += STRINGS.decimalSym;
            }

            // alternate special case, they typed one decimal number, don't force it to zero, at least not yet..
            if (decimalWithOneDigit.test(viewValue)) {
                formatted = formatted.substr(0, formatted.length - 1);
            }

            elem.val(formatted);
            return plainNumber;
        });
    }
}]);
</code>```

Title: How do I limit decimal places to only two numbers when paste number into input box using angularjs?

Body:
I have input box accepting decimal numbers with having decimal points limit upto 2 places. Also I am not allowing input to enter more than two decimal places.

eg. 9999.99

But now the problem is when I am copy some number i.e. 999999.9999 and paste it into input box I want result i.e. 999999.99

Meaning I want to truncate rest of the decimal places and don't want rounding as well.

How can I achieve this using angularjs?

Body:
You can accomplish this using ng-model along with $formatters and $parsers.

See more explanation here:

ngModel Formatters and Parsers

This is a TypeScript adaptation from some code I use to force currency formats.

app.directive('myModelFormat', ['$filter', function myModelFormatDirective($filter:ng.IFilterService):ng.IDirective {

    return {
        require: '?ngModel',
        link: myModelFormatLink
    };

    function myModelFormatLink(scope:ng.IScope, elem:ng.IAugmentedJQuery, attrs:ng.IAttributes, ctrl:ng.INgModelController) {

        if (!ctrl) {
            return;
        }

        const decimalWithOneDigit:RegExp = new RegExp('\\' + STRINGS.decimalSym + '\\d$');

        ctrl.$formatters.unshift(function myModelFormatFormatter(ignore:any):string {
            return $filter(attrs['myModelFormat'])(ctrl.$modelValue)
        });

        ctrl.$parsers.unshift(function myModelFormatParser(viewValue:string):any {
            const plainNumber:number = parseFloat(viewValue);
            let formatted:string = $filter(attrs['myModelFormat'])(plainNumber);

            // special case where they typed the decimal symbol but not a decimal value,
            // make sure we don't remove the symbol which prevents them from typing a decimal
            if (_s.endsWith(viewValue, STRINGS.decimalSym)) {
                formatted += STRINGS.decimalSym;
            }

            // alternate special case, they typed one decimal number, don't force it to zero, at least not yet..
            if (decimalWithOneDigit.test(viewValue)) {
                formatted = formatted.substr(0, formatted.length - 1);
            }

            elem.val(formatted);
            return plainNumber;
        });
    }
}]);


来源: stackexchange

问:
How to fetch two Json response Json Object and Array
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

```<code>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"}]}
</code>```

only the 1st response was returned in this Logcat

```<code>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
</code>```

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

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

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

```<code>{
  "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>```

Whole JSON response

```<code>{
  "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>```

This is my Login.java

```<code>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();
}
</code>```

SQlitehandler.java

```<code>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;
}
</code>```

Logcat message

```<code>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
</code>```

Login.php

```<code><?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);
}
?>
</code>```

答:
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

```<code>{
   "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"
         }
      ]
   }
}
</code>```

OPTION2 : 2 Objects in single JSON array string

```<code>{
   "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>```

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

```<code>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());
            }
        }
    }
}
</code>```

Sample Logs for OPTION1 & OPTION2

```<code>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: ---------------------------------
</code>```

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.

```<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);
</code>```

PHP Sample Run generated JSON response (OPTION1)

```<code>{
   "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>```

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

ContentLicense: CC BY-SA 3.0

Body:
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 "
" .$username. "
";
        // 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);
}
?>

Body:
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


问:
JavaFX Button with multiple text lines
I need to create a toolbar in my screen that will have multiple buttons, and each button must have multiple lines of Text. For example:

I looked over the internet and StackOverflow but I couldn't find anything showing how to do this in JavaFX. I'm using JavaFX 8.

Someone could help me, please?

Tks

答:
In the button text property select "switch to multi-line mode

"

Title: JavaFX Button with multiple text lines


问:
Need to Seriazlize List<object>, but FXCop complains "Do not expose generic lists"
I have an object that I need to serialize. The object contains several properties, including a List. FXCop is complaining that I should not expose generic lists, and I get that, however, due to the fact that I can't specify an interface based property on an object that I want serialized I'm not sure where to turn next.

Any thoughts?

BTW, I'm using XMLSerialization, but that's not a requirement.

答:
I took FxCop's suggestion and wrapped my list in a Collection. This blew some of my code out of the water, but a after a few adjustments I was up and running again.

Here's some code showing before and after:

Before:

```<code>   public class PersistentDataView
    {
        public string Title { get; set; }
        private List<object> Inputs { get; set;}
    }
</code>```

After:

```<code>    public class PersistentDataView
    {
        private List<object> _inputs;

        public string Title { get; set; }
        public Collection<object> Inputs
        {
            get
            {
                if (_inputs == null)
                    _inputs = new List<object>();

                //Wrap the private field into a collection.
                return new Collection<object>(_inputs);
            }
        }
  }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I took FxCop's suggestion and wrapped my list in a Collection. This blew some of my code out of the water, but a after a few adjustments I was up and running again.

Here's some code showing before and after:

Before:

   public class PersistentDataView
    {
        public string Title { get; set; }
        private List<object> Inputs { get; set;}
    }

After:

    public class PersistentDataView
    {
        private List<object> _inputs;

        public string Title { get; set; }
        public Collection<object> Inputs
        {
            get
            {
                if (_inputs == null)
                    _inputs = new List<object>();

                //Wrap the private field into a collection.
                return new Collection<object>(_inputs);
            }
        }
  }


问:
Phonegap - clicking on icon restarts app instead of switching to already running app
I have a very simple Phonegap application that loads an external website:

```<code><script type="text/javascript" src="cordova.js"></script>
<script>
    function onDeviceReady() {
        if (navigator.connection.type == Connection.NONE) {
            navigator.notification.alert('An internet connection is required to continue');
        } else {
            window.location = "http://example.com";
        }
    }
    document.addEventListener("deviceready", onDeviceReady, false);
</script>
</code>```

When I run it it all works properly and loads the external site.  If I switch to a different app and then click the icon to run it (in Android) it switches back to the already running application with no issues.

The problem started occurring <s>when I switched from my testing environment to my production one and switched it to go to an https version</s>.  Now, when I click on the icon it restarts the application instead of simply switching back to the application already running.

Is there any way to control whether clicking on the icon reloads the application or simply switches back to the already running application?

EDIT:

Okay, I thought the only difference was changing the "http" to "https", but apparently I also did an upgrade of "phonegap".  I tried switching it back to "http" and it's still doing the same wrong thing.  Is there any way to control this?  I'm currently running 6.5.2 and I think the proper functionality was with 6.5.0 .

EDIT 2:

Alright... It seems that it's somewhat random.  I have it running the latest and using "https" and it sometimes reloads and sometimes doesn't.

答:
Mobile operating system OS's each have different ways of managing memory in apps. The general consensus is that the app should always "save early/often" in case it's killed by the OS to free up memory, etc.

In this case, there may be a way though. Try out the Android Launch Mode preference:

```<code><preference name="AndroidLaunchMode" value="singleInstance" />
</code>```

I've never used this, so perhaps try out each mode too.

Body:
I have a very simple Phonegap application that loads an external website:

When I run it it all works properly and loads the external site.  If I switch to a different app and then click the icon to run it (in Android) it switches back to the already running application with no issues.

The problem started occurring <s>when I switched from my testing environment to my production one and switched it to go to an https version</s>.  Now, when I click on the icon it restarts the application instead of simply switching back to the application already running.

Is there any way to control whether clicking on the icon reloads the application or simply switches back to the already running application?

EDIT:

Okay, I thought the only difference was changing the "http" to "https", but apparently I also did an upgrade of "phonegap".  I tried switching it back to "http" and it's still doing the same wrong thing.  Is there any way to control this?  I'm currently running 6.5.2 and I think the proper functionality was with 6.5.0 .

EDIT 2:

Alright... It seems that it's somewhat random.  I have it running the latest and using "https" and it sometimes reloads and sometimes doesn't.

Body:
Mobile operating system OS's each have different ways of managing memory in apps. The general consensus is that the app should always "save early/often" in case it's killed by the OS to free up memory, etc.

In this case, there may be a way though. Try out the Android Launch Mode preference:

<preference name="AndroidLaunchMode" value="singleInstance" />

I've never used this, so perhaps try out each mode too.


问:
How do I implement getsymbols function using for statement?
```<code>library(quantmod)
kospi = c('000020','000030','000040')
koslist = as.character(kospi)
koslist
startDate <<- as.Date("2017-01-01")
endDate <<- as.Date("2017-01-05")

for(i in koslist){
  assign('m','i',envir = .GlobalEnv) # set m Global global variable #Problem1
  tt = getSymbols(m, src = "google", from = startDate, to = endDate,env=NULL)
ff = data.frame(tt)
 kk = ff$I.Close #Problem2
 print(kk)
 }
</code>```

I wanted to make for statement code to use getSymbols function(function to get stock information). But I encountered two problem.

I couldn't set the Global variable in for statement. If I do not set the Global variable, function got me a wrong data. But I still got a wrong data nevertheless I set the Global variable. I don't know Problem.

Even if I solve the problem1, I have a column name problem. Yahoo got me a data like this. Every column name have 'X'(+Global variables(stockcode)). I don't know for statement'Global variable to column name.

```<code>           X005930.Open X005930.High X005930.Low X005930.Close
2017-01-02      1799000      1812000     1794000       1805000
2017-01-03      1814000      1831000     1801000       1824000
2017-01-04      1825000      1826000     1805000       1808000
2017-01-05      1803000      1803000     1777000       1778000
</code>```

I am not sure approach like that. I want repeat the getsymbols function. I struggle with this a couple of weeks. Please let me know solution.

答:
There are multiple issues with your script.  In your statement:

```<code>assign('m','i',envir = .GlobalEnv)
</code>```

You are assigning the literal string 'i' to the variable m, not a stock symbol.  Secondly, the first argument in getSymbols is a stock symbol.   000020, 000030 or 000040 are not valid stock symbols.

Try this:

```<code>library(quantmod)
symbol_list = c('AAPL','GOOGL','MSFT')
startDate <<- as.Date("2017-01-01")
endDate <<- as.Date("2017-01-05")

for(i in symbol_list){
    tt = getSymbols(i, src = "google", from = startDate, to = endDate,env=NULL)
    print(tt)
}
</code>```

Body:
library(quantmod)
kospi = c('000020','000030','000040')
koslist = as.character(kospi)
koslist
startDate <<- as.Date("2017-01-01")
endDate <<- as.Date("2017-01-05")

for(i in koslist){
  assign('m','i',envir = .GlobalEnv) # set m Global global variable #Problem1
  tt = getSymbols(m, src = "google", from = startDate, to = endDate,env=NULL)
ff = data.frame(tt)
 kk = ff$I.Close #Problem2
 print(kk)
 }

I wanted to make for statement code to use getSymbols function(function to get stock information). But I encountered two problem.

I couldn't set the Global variable in for statement. If I do not set the Global variable, function got me a wrong data. But I still got a wrong data nevertheless I set the Global variable. I don't know Problem.

Even if I solve the problem1, I have a column name problem. Yahoo got me a data like this. Every column name have 'X'(+Global variables(stockcode)). I don't know for statement'Global variable to column name.

           X005930.Open X005930.High X005930.Low X005930.Close
2017-01-02      1799000      1812000     1794000       1805000
2017-01-03      1814000      1831000     1801000       1824000
2017-01-04      1825000      1826000     1805000       1808000
2017-01-05      1803000      1803000     1777000       1778000

I am not sure approach like that. I want repeat the getsymbols function. I struggle with this a couple of weeks. Please let me know solution.

Body:
There are multiple issues with your script.  In your statement:

assign('m','i',envir = .GlobalEnv)

You are assigning the literal string 'i' to the variable m, not a stock symbol.  Secondly, the first argument in getSymbols is a stock symbol.   000020, 000030 or 000040 are not valid stock symbols.

Try this:

library(quantmod)
symbol_list = c('AAPL','GOOGL','MSFT')
startDate <<- as.Date("2017-01-01")
endDate <<- as.Date("2017-01-05")

for(i in symbol_list){
    tt = getSymbols(i, src = "google", from = startDate, to = endDate,env=NULL)
    print(tt)
}


问:
table view is not loading data
I am running the following code, and have a UITableView nested within a UIViewController.  The code should be using a nib to populate the rows, but for some reason nothing shows up when the UITableView loads.  Below is the following class associated with the UIViewController that has an embedded tableview.  Does anyone know why this may not be loading?

Code I have tried:

```<code>import UIKit
import Firebase

class Today: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    var anArray: [String] = ["a", "b", "c"]

    @IBOutlet weak var myTableView: UITableView!
    override func viewDidLoad() {

        let nib = UINib.init(nibName: "ScheduleCellTableViewCell", bundle: nil)

        self.myTableView.registerNib(nib, forCellReuseIdentifier: "cell")

        self.myTableView.reloadData() //<<<<<<<<<<<<< RELOADS TABLEVIEW

    }//viewDidLoad() ends here

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return the count of the number of groups
        return anArray.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ScheduleCellTableViewCell

        let val = indexPath.row

        cell.testLabel.text = anArray[val]

        return cell
    }

    public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 160.0
    }
}
</code>```

答:
You don't need to reloadData() for UITableView on viewDidLoad().

connect UITableView dataSource and delegate in UIViewController of the referencingOutlets. Like as below,

Title: table view is not loading data

Body:
I am running the following code, and have a UITableView nested within a UIViewController.  The code should be using a nib to populate the rows, but for some reason nothing shows up when the UITableView loads.  Below is the following class associated with the UIViewController that has an embedded tableview.  Does anyone know why this may not be loading?

Code I have tried:

import UIKit
import Firebase

class Today: UIViewController, UITableViewDelegate, UITableViewDataSource  {

    var anArray: [String] = ["a", "b", "c"]

    @IBOutlet weak var myTableView: UITableView!
    override func viewDidLoad() {

        let nib = UINib.init(nibName: "ScheduleCellTableViewCell", bundle: nil)

        self.myTableView.registerNib(nib, forCellReuseIdentifier: "cell")

        self.myTableView.reloadData() //<<<<<<<<<<<<< RELOADS TABLEVIEW

    }//viewDidLoad() ends here

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return the count of the number of groups
        return anArray.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ScheduleCellTableViewCell

        let val = indexPath.row

        cell.testLabel.text = anArray[val]

        return cell
    }

    public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 160.0
    }
}


问:
Getting the active process in Compact Framework C#
What I am trying to do is get the name of the executable that owns the window that currently has focus from another process. The purpose of the program is to track how much time you spend in each program.
I tried to do this with GetWindowThreadProcessId(GetForegroundWindow()) (both in "coredll.dll") then use Process.GetProcessById() on that, but the process object I get always has "" for Process.StartInfo.FileName. It doesn't seem to work properly in Windows Mobile. Does anyone know how this could be done? Thanks</p>

答: If GetwindowThreadProcessId fails you, perhaps getting all processes and calling EnumWindows for each process will return a window with the same handle as the foreground window.</p>


问:
How to use ReactXP storage api?
I am new in ReactXP and I am trying to create a small app using Microsoft ReactXP framework. I want to save key value pair in my local storage. Microsoft provided an api called Storage
https://microsoft.github.io/reactxp/docs/apis/storage.html
https://github.com/Microsoft/reactxp/blob/master/src/web/Storage.ts

And I am trying to use it as

```<code>onLoginPressed(){
        const user = new User(this.state.userEmail, this.state.password);
        RestClient.login(user).then(success => {
            alert(success.message);
            Storage.setItem('userEmail', success.userInfo.userEmail);
        }).catch(error => {
            alert('Error in login');
        });
    }
</code>```

but it showing an error

```<code>ERROR in [at-loader] ./src/Login.tsx:102:21
    TS2339: Property 'setItem' does not exist on type '{ new (): Storage; prototype: Storage; }'.
</code>```

because of poor documentation I am not able to use it. Can anybody help me?

答:
I found the solution as follows

```<code>onLoginPressed(){
        const user = new User(this.state.userEmail, this.state.password);
        RestClient.login(user).then(success => {
            alert(success.message);
            RX.Storage.setItem('userEmail', success.userInfo.userEmail);
        }).catch(error => {
            alert('Error in login');
        });
    }
</code>```

and you can get it as follows :

```<code>RX.Storage.getItem('userEmail').then(success => {
     this.setState({
          userEmail: success
     });
});
</code>```

Title: How to use ReactXP storage api?

Body:
I am new in ReactXP and I am trying to create a small app using Microsoft ReactXP framework. I want to save key value pair in my local storage. Microsoft provided an api called Storage
https://microsoft.github.io/reactxp/docs/apis/storage.html
https://github.com/Microsoft/reactxp/blob/master/src/web/Storage.ts

And I am trying to use it as

onLoginPressed(){
        const user = new User(this.state.userEmail, this.state.password);
        RestClient.login(user).then(success => {
            alert(success.message);
            Storage.setItem('userEmail', success.userInfo.userEmail);
        }).catch(error => {
            alert('Error in login');
        });
    }

but it showing an error

ERROR in [at-loader] ./src/Login.tsx:102:21
    TS2339: Property 'setItem' does not exist on type '{ new (): Storage; prototype: Storage; }'.

because of poor documentation I am not able to use it. Can anybody help me?

Body:
I found the solution as follows

onLoginPressed(){
        const user = new User(this.state.userEmail, this.state.password);
        RestClient.login(user).then(success => {
            alert(success.message);
            RX.Storage.setItem('userEmail', success.userInfo.userEmail);
        }).catch(error => {
            alert('Error in login');
        });
    }

and you can get it as follows :

RX.Storage.getItem('userEmail').then(success => {
     this.setState({
          userEmail: success
     });
});


问:
Why created dynamically drop down box not looks good?
I use jQuery mobile 1.4.5 and jQuery 1.8.3 and jQuery-ui- 1.9.2

I create dropbox dynamically here the JavaScript code:

```<code>function setLayerPropertyControls() {

    var content = '<fieldset style="border: solid 1px #6b6b6b;">';

    content += '<label for="select-native-1">Basic:</label>' +
              '<select name="select-native-1" id="select-native-1">' +
                   '<option value="1">The 1st Option</option>' +
                   '<option value="2">The 2nd Option</option>' +
                   '<option value="3">The 3rd Option</option>' +
                   '<option value="4">The 4th Option</option>' +
               '</select>';

    content += '</fieldset>';
    layerProp.append(content);
}
</code>```

Here is html markup:

```<code><div data-role="page" id="layerProperty">
    <div data-role="header" data-position="fixed" data-theme="b">
        <h1 id="layers property"></h1>
        <a href="#mapPage" data-mini="true" data-icon="arrow-l">חזור</a>
    </div>

    <div data-role="content">
        <div id="vectorLayerProperties">
        </div>
        <div id="vectorLayerslist"></div>
    </div>
</div>
</code>```

Here the result in the view:

While if I take this code:

```<code> <div class="ui-field-contain">
        <label for="select-native-1">Basic:</label>
        <select name="select-native-1" id="select-native-1">
            <option value="1">The 1st Option</option>
            <option value="2">The 2nd Option</option>
            <option value="3">The 3rd Option</option>
            <option value="4">The 4th Option</option>
        </select>
    </div>
</code>```

And paste it in HTML:

```<code><div data-role="page" id="layerProperty">
    <div data-role="header" data-position="fixed" data-theme="b">
        <h1 id="layers property"></h1>
        <a href="#mapPage" data-mini="true" data-icon="arrow-l">חזור</a>
    </div>

    <div data-role="content">
        <div id="vectorLayerProperties">

            <div class="ui-field-contain">
                <label for="select-native-1">Basic:</label>
                <select name="select-native-1" id="select-native-1">
                    <option value="1">The 1st Option</option>
                    <option value="2">The 2nd Option</option>
                    <option value="3">The 3rd Option</option>
                    <option value="4">The 4th Option</option>
                </select>
            </div>

        </div>
        <div id="vectorLayerslist"></div>
    </div>

</div>
</code>```

It looks looks like that:

Any idea why do I get poor style of the drop down-box when I try to create it dynamically in the code?

答:
your dynamically code has this

<fieldset style="border: solid 1px #6b6b6b;"> </fieldset>;

but pure html not have.

so i think maybe is css layer problom?

Body:
I use jQuery mobile 1.4.5 and jQuery 1.8.3 and jQuery-ui- 1.9.2

I create dropbox dynamically here the JavaScript code:

function setLayerPropertyControls() {

    var content = '<fieldset style="border: solid 1px #6b6b6b;">';

    content += 'Basic:' +
              '<select name="select-native-1" id="select-native-1">' +
                   '<option value="1">The 1st Option</option>' +
                   '<option value="2">The 2nd Option</option>' +
                   '<option value="3">The 3rd Option</option>' +
                   '<option value="4">The 4th Option</option>' +
               '</select>';

    content += '</fieldset>';
    layerProp.append(content);
}

Here is html markup:

        חזור

Here the result in the view:

While if I take this code:

        Basic:
        <select name="select-native-1" id="select-native-1">
            <option value="1">The 1st Option</option>
            <option value="2">The 2nd Option</option>
            <option value="3">The 3rd Option</option>
            <option value="4">The 4th Option</option>
        </select>

And paste it in HTML:

        חזור

                Basic:
                <select name="select-native-1" id="select-native-1">
                    <option value="1">The 1st Option</option>
                    <option value="2">The 2nd Option</option>
                    <option value="3">The 3rd Option</option>
                    <option value="4">The 4th Option</option>
                </select>

It looks looks like that:

Any idea why do I get poor style of the drop down-box when I try to create it dynamically in the code?


问:
I need to set next button as disabled till any radio button got selected
In my use case i need to set Next button from a popup is disabled in default till any one of the radio button got selected.

Need to achieve this in Ember.Js

My hbs code (for that popup):

```<code>{{! To list all accounts in popup }}
<div id="listAllAccounts" class="modal animated fadeInUp modal-pop downloadAsPopup">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true" {{action 'clearModal'}}>×</button>
        <h4 class="modal-title">List of accounts</h4>
      </div>
      <div class="modal-body">
        <div class="textGroup">
          <h2 class="primaryTitle">Select an account.</h2>
        </div>
        <div class="modalTableHolder">
          <table class="primaryListTable" id="AccountsInfo">
            <thead>
              <td class="tablestyle5">Account ID</td>
              <td class="tablestyle5">Account Name</td>
            </thead>
            <tbody>
              {{#each model.integration as |list index|}}
                <tr>
                  <td class="tablestyle5"><input type="radio" name="accounts" class="messageCheckbox mt6 mR5" data-acc-name={{list.ACCOUNT_NAME}} value={{list.ACCOUNT_ID}}>{{list.ACCOUNT_ID}}</td>
                  <td class="tablestyle5">{{list.ACCOUNT_NAME}}</td>
                </tr>
              {{/each}}
            </tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer">
        <div class="text-right">
          <button type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" {{action 'clearModal'}}>Cancel</button>
          <button type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" {{action 'showContainerPopup' 'clearModal'}}>Next</button>
        </div>
      </div>
    </div>
  </div>
</div>
{{! To list all accounts in popup Ends }}
</code>```

JS code:

```<code>Ember.run.scheduleOnce('afterRender', this, function() {
          new URI(Abc, this.get('currentOrg.ABC_ID'), Project, this.get('defaultProject.PROJECT_ID'), Integration)
          .addQueryParam('email', this.get(email))
          .GETS()
          .then(function(res) {
            if(res.length !== 0){
              var sett = projectObj.get("INTEGRATION");
              self.set("model.integration", res);    //this is where i set data to that popup
              common.hideModal("loadingPopup");
              common.showModal("listAllAccounts");
            } else {
              common.hideModal("loadingPopup");
              options.content = i18n("enable.integration.noaccount.error");
              options.type = 'warning';
              dialog.showCard(options);
            }
          });
</code>```

This is the popup. I need to disable the next button until anyone selects any one radio button. If radio button is checked i need to enable next option.

答:
You can use .change() or .one("change") to check whether they select yet.

```<code> $(".text-right button:last").prop("disabled", true); // disable the button
 $('input[type="radio"]').one("change", function () {
         $(".text-right button:last").prop("disabled", false); // enable it;
 });
</code>```

Body:
In my use case i need to set Next button from a popup is disabled in default till any one of the radio button got selected.

Need to achieve this in Ember.Js

My hbs code (for that popup):

{{! To list all accounts in popup }}

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true" {{action 'clearModal'}}>×</button>

List of accounts

Select an account.

              Account ID
              Account Name

              {{#each model.integration as |list index|}}

                  <input type="radio" name="accounts" class="messageCheckbox mt6 mR5" data-acc-name={{list.ACCOUNT_NAME}} value={{list.ACCOUNT_ID}}>{{list.ACCOUNT_ID}}
                  {{list.ACCOUNT_NAME}}

              {{/each}}

          <button type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" {{action 'clearModal'}}>Cancel</button>
          <button type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" {{action 'showContainerPopup' 'clearModal'}}>Next</button>

{{! To list all accounts in popup Ends }}

JS code:

Ember.run.scheduleOnce('afterRender', this, function() {
          new URI(Abc, this.get('currentOrg.ABC_ID'), Project, this.get('defaultProject.PROJECT_ID'), Integration)
          .addQueryParam('email', this.get(email))
          .GETS()
          .then(function(res) {
            if(res.length !== 0){
              var sett = projectObj.get("INTEGRATION");
              self.set("model.integration", res);    //this is where i set data to that popup
              common.hideModal("loadingPopup");
              common.showModal("listAllAccounts");
            } else {
              common.hideModal("loadingPopup");
              options.content = i18n("enable.integration.noaccount.error");
              options.type = 'warning';
              dialog.showCard(options);
            }
          });

This is the popup. I need to disable the next button until anyone selects any one radio button. If radio button is checked i need to enable next option.

Body:
You can use .change() or .one("change") to check whether they select yet.

 $(".text-right button:last").prop("disabled", true); // disable the button
 $('input[type="radio"]').one("change", function () {
         $(".text-right button:last").prop("disabled", false); // enable it;
 });


问:
Implement ECDiffieHellmanCng in Xamarin
I am trying to use the Elliptic Curve Diffie-Hellman algorithm for key exchange in a xamarin application. However, I am getting a reference/compilation errors for the class. My assumption is that the class is not part of Mono. Do you know of a workaround for using that algorithm in Xamarin Apps? Please share your thoughts.

Thank you!

ECDiffieHellmanCng

```<code>var sessionClient = new ECDiffieHellmanCng {
                KeySize = 521,
                KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash,
                HashAlgorithm = CngAlgorithm.Sha256
            };
</code>```

答:
Sounds like you can use third party solutions like,

https://www.nuget.org/packages/Curve25519/

This blog post contains tons of samples for different platforms,

http://blog.srinivasan.biz/software/elliptic-curve-cryptography-computing-shared-key

Title: Implement ECDiffieHellmanCng in Xamarin

Body:
I am trying to use the Elliptic Curve Diffie-Hellman algorithm for key exchange in a xamarin application. However, I am getting a reference/compilation errors for the class. My assumption is that the class is not part of Mono. Do you know of a workaround for using that algorithm in Xamarin Apps? Please share your thoughts.

Thank you!

ECDiffieHellmanCng

var sessionClient = new ECDiffieHellmanCng {
                KeySize = 521,
                KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash,
                HashAlgorithm = CngAlgorithm.Sha256
            };