Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

In this page you can find the example usage for org.json JSONArray length.

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:org.chromium.ChromeAlarms.java

private void clear(final CordovaArgs args, final CallbackContext callbackContext) {
    try {/*w  w w .j  a v a 2  s. com*/
        JSONArray alarmNames = args.getJSONArray(0);
        for (int i = 0; i < alarmNames.length(); i++) {
            cancelAlarm(alarmNames.getString(i));
        }
        callbackContext.success();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Could not clear alarm", e);
        callbackContext.error("Could not create alarm");
    }
}

From source file:com.theaigames.game.warlight2.MapCreator.java

/**
 * @param mapString : string that represents the map to be created
 * @return : a Map object to use in the game
 *///from   w  w  w .  jav a2 s  .c om
public static Map createMap(String mapString) {
    Map map = new Map();

    //parse the map string
    try {
        JSONObject jsonMap = new JSONObject(mapString);

        // create SuperRegion objects
        JSONArray superRegions = jsonMap.getJSONArray("SuperRegions");
        for (int i = 0; i < superRegions.length(); i++) {
            JSONObject jsonSuperRegion = superRegions.getJSONObject(i);
            map.add(new SuperRegion(jsonSuperRegion.getInt("id"), jsonSuperRegion.getInt("bonus")));
        }

        // create Region object
        JSONArray regions = jsonMap.getJSONArray("Regions");
        for (int i = 0; i < regions.length(); i++) {
            JSONObject jsonRegion = regions.getJSONObject(i);
            SuperRegion superRegion = map.getSuperRegion(jsonRegion.getInt("superRegion"));
            map.add(new Region(jsonRegion.getInt("id"), superRegion));
        }

        // add the Regions' neighbors
        for (int i = 0; i < regions.length(); i++) {
            JSONObject jsonRegion = regions.getJSONObject(i);
            Region region = map.getRegion(jsonRegion.getInt("id"));
            JSONArray neighbors = jsonRegion.getJSONArray("neighbors");
            for (int j = 0; j < neighbors.length(); j++) {
                Region neighbor = map.getRegion(neighbors.getInt(j));
                region.addNeighbor(neighbor);
            }
        }
    } catch (JSONException e) {
        System.err.println("JSON: Can't parse map string: " + e);
    }

    map.sort();

    return map;
}

From source file:org.catnut.fragment.HomeTimelineFragment.java

@Override
protected void refresh() {
    // ???/*from w ww .j  a v a  2  s . co m*/
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // refresh!
    final int size = getFetchSize();
    (new Thread(new Runnable() {
        @Override
        public void run() {
            // ??????(?-)???Orz...
            String query = CatnutUtils.buildQuery(new String[] { BaseColumns._ID }, mSelection, Status.TABLE,
                    null, BaseColumns._ID + " desc", size + ", 1" // limit x, y
            );
            Cursor cursor = getActivity().getContentResolver().query(CatnutProvider.parse(Status.MULTIPLE),
                    null, query, null, null);
            // the cursor never null?
            final long since_id;
            if (cursor.moveToNext()) {
                since_id = cursor.getLong(0);
            } else {
                since_id = 0;
            }
            cursor.close();
            final CatnutAPI api = TweetAPI.homeTimeline(since_id, 0, size, 0, 0, 0, 0);
            // refresh...
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mRequestQueue.add(new CatnutRequest(getActivity(), api,
                            new StatusProcessor.TimelineProcessor(Status.HOME, true),
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Log.d(TAG, "refresh done...");
                                    mTotal = response.optInt(TOTAL_NUMBER);
                                    // ???
                                    JSONArray jsonArray = response.optJSONArray(Status.MULTIPLE);
                                    int newSize = jsonArray.length(); // ...
                                    Bundle args = new Bundle();
                                    args.putInt(TAG, newSize);
                                    getLoaderManager().restartLoader(0, args, HomeTimelineFragment.this);
                                }
                            }, errorListener)).setTag(TAG);
                }
            });
        }
    })).start();
}

From source file:com.google.samples.apps.friendlyping.gcm.MyGcmListenerService.java

private ArrayList<Pinger> getPingers(Bundle data) throws JSONException {
    final JSONArray clients = new JSONArray(data.getString("clients"));
    ArrayList<Pinger> pingers = new ArrayList<>(clients.length());
    for (int i = 0; i < clients.length(); i++) {
        JSONObject jsonPinger = clients.getJSONObject(i);
        pingers.add(Pinger.fromJson(jsonPinger));
    }/*ww w  .j  a  va 2s  .  c o m*/
    return pingers;
}

From source file:org.b3log.rhythm.repository.impl.UserRepositoryImpl.java

@Override
public JSONObject getByEmail(final String email) throws RepositoryException {
    final Query query = new Query().setPageCount(1);
    query.setFilter(new PropertyFilter(User.USER_EMAIL, FilterOperator.EQUAL, email.toLowerCase().trim()));

    try {//from   www  .  ja  v a2 s  .co  m
        final JSONObject result = get(query);
        final JSONArray array = result.getJSONArray(Keys.RESULTS);

        if (0 == array.length()) {
            return null;
        }

        return array.getJSONObject(0);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);

        throw new RepositoryException(e);
    }
}

From source file:com.example.pyrkesa.shwc.OngoingNotificationListenerService.java

@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    final String ACTION_DEMAND = "ACTION_DEMAND";
    String EXTRA_CMD = "EXTRA_CMD";

    dataEvents.close();/*w  ww .  ja  va2 s .  co m*/

    if (!mGoogleApiClient.isConnected()) {
        ConnectionResult connectionResult = mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS);
        if (!connectionResult.isSuccess()) {
            Log.e(TAG, "Service failed to connect to GoogleApiClient.");
            return;
        }
    }

    for (DataEvent event : events) {
        if (event.getType() == DataEvent.TYPE_CHANGED) {
            String path = event.getDataItem().getUri().getPath();
            if (PATH.equals(path)) {
                // Get the data out of the event
                DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
                //final String title = dataMapItem.getDataMap().getString(KEY_TITLE);
                final String room_devices = dataMapItem.getDataMap().getString(KEY_ROOM_DEVICES);
                final String room_name = dataMapItem.getDataMap().getString(KEY_ROOM_NAME);
                //  Asset asset = dataMapItem.getDataMap().getAsset(KEY_BACKGROUND);

                try {
                    JSONObject roomJSON = new JSONObject(room_devices);
                    JSONArray devicesArray = roomJSON.getJSONArray("devices");
                    String firstPageText = "quipements :";

                    ArrayList<Device> devicess = new ArrayList<Device>();

                    for (int i = 0; i < devicesArray.length(); i++) {
                        JSONObject d = devicesArray.getJSONObject(i);
                        Device device = new Device(d.getString("id"), d.getString("name"), d.getInt("type"),
                                d.getString("status"));

                        String Newline = System.getProperty("line.separator");

                        firstPageText += Newline;
                        firstPageText += device.name;

                        devicess.add(device);

                    }
                    if (firstPageText.equalsIgnoreCase("quipements :")) {
                        firstPageText = "Aucun quipement";
                    }

                    Bitmap background = BitmapFactory.decodeResource(this.getResources(),
                            R.drawable.bg_distance);
                    NotificationCompat.WearableExtender notifExtender = new NotificationCompat.WearableExtender();

                    for (Device d : devicess) {
                        try {
                            notifExtender.addAction(d.getAction(OngoingNotificationListenerService.this));
                        } catch (Exception e) {
                            Log.e("Erreur get Action :", e.getMessage());
                        }
                    }

                    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                            .setContentTitle("Pice : " + roomJSON.getString("name"))
                            .setContentText(firstPageText).setSmallIcon(R.drawable.mini_logo)
                            .extend(notifExtender.setBackground(background)).setOngoing(true);

                    // Build the notification and show it
                    NotificationManager notificationManager = (NotificationManager) getSystemService(
                            NOTIFICATION_SERVICE);
                    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
                } catch (Throwable t) {
                    Log.e("JSON_WEAR_SHWC", "Could not parse malformed JSON: " + room_devices + t.getMessage());
                }

            } else {
                Log.d(TAG, "Unrecognized path: " + path);
            }
        }
    }
}

From source file:com.example.wmgps.MainActivity.java

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    /*Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);*//*www .  j av a2 s.  com*/

    /*EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
            
    TextView output = (TextView) findViewById(R.id.welcome);
    output.setText(message);*/

    /*Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
    startActivity(browserIntent);
            
    */
    TextView hiddenText = (TextView) findViewById(R.id.Hidden11);
    if (Misc.isNullTrimmedString(hiddenText.getText().toString())) {
        TextView output = (TextView) findViewById(R.id.welcome1);
        boolean without_connection = true;
        Map<String, ArrayList<String>> typeAndValueOfTag = new LinkedHashMap<String, ArrayList<String>>(); // Insertion order must be followed

        String response = Misc.EMPTY_STRING;
        String welcome1String = "*******************Connected*************************";
        try {

            response = new RetrieveFeedTask().execute(new String[] {}).get();

        } catch (Exception e) {
            response = Misc.EMPTY_STRING;
            Log.e("Exception ", e.getMessage());

            Log.e("Exception ", e.getLocalizedMessage());

            Log.e("Exception ", e.getStackTrace().toString());

        }

        if (Misc.isNullTrimmedString(response)) {
            // welcome1String = "***Loading Static, couldn't connect***";

            response = "{\"window\":{\"elements\":[{\"type\":\"hidden\",\"name\":\"sourceAction\"},{\"type\":\"label\",\"value\":\"Warehouse Management\"},"
                    + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"--------- ----------\"},{\"type\":\"break\"}, {\"type\":\"label\",\"value\":\" User ID: \"},"
                    + "{\"type\":\"entry\",\"name\":\"j_username\",\"value\":\"\",\"maxLength\":15,\"dispLength\":10,"
                    + "\"setHidden\":[{\"hiddenName\":\"sourceAction\",\"hiddenValue\":\"username\"}],\"focus\":true},"
                    + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"Password: \"},"
                    + "{\"type\":\"entry\",\"name\":\"j_password\",\"value\":\"\",\"hideInput\":true,\"maxLength\":14,\"dispLength\":10,\"focus\":false},"
                    + "{\"type\":\"keybinding\",\"value\":\"CTRL-X\",\"URL\":\"\",\"keyDescription\":\"CTRL-X Exit\"},"
                    + "{\"type\":\"keybinding\",\"value\":\"CTRL-L\",\"URL\":\"/scopeRF/RFLogin/RFLegal.jsp\",\"keyDescription\":\"CTRL-L License Agreement\"}]"
                    + ",\"submit\":\"/scopeRF/RFLogin/ProcessLogin.jsp\"}}";
        }

        StringBuffer finalEncodedString = new StringBuffer(Misc.EMPTY_STRING);

        int currentOutputTag = R.id.Hidden1;
        int currentInputTag = R.id.edit_message;

        // Renderer::decodeConfig()
        if (!Misc.isNullTrimmedString(response)) {
            try {
                JSONObject jsonObj = new JSONObject(response);

                for (Iterator iterator = jsonObj.keys(); iterator.hasNext();) {
                    String name = (String) iterator.next();

                    JSONObject jsonObj1 = jsonObj.getJSONObject(name);

                    for (Iterator iterator1 = jsonObj1.keys(); iterator1.hasNext();) {
                        String name1 = (String) iterator1.next();

                        if ("elements".equals(name1)) {
                            JSONArray jsonArr = jsonObj1.getJSONArray(name1);
                            boolean userName = false;
                            boolean password = false;
                            for (int i = 0; i < jsonArr.length(); i++) {
                                JSONObject temp = jsonArr.getJSONObject(i);
                                String initialValue = null;
                                String initialName = null;
                                String initialLabel = null;

                                if (!temp.isNull("name") && temp.getString("name").equals("j_password")) {
                                    initialName = "j_password";
                                } else if (!temp.isNull("name")
                                        && temp.getString("name").equals("j_username")) {
                                    initialName = "j_username";
                                }

                                for (Iterator iterator2 = temp.keys(); iterator2.hasNext();) {
                                    String tempName = (String) iterator2.next();
                                    String tempValue = (String) temp.getString(tempName);

                                    if (tempName.equals("type")) {
                                        if (tempValue.equals("label") || tempValue.equals("entry")) {
                                            initialLabel = tempValue;
                                        }
                                    } else if (tempName.equals("value")) {
                                        initialValue = tempValue;
                                    }

                                    /* if(tempName.equals("label"))
                                     {
                                        if(Misc.isNullTrimmedString(initialValue))
                                     initialLabel = tempName;
                                        else
                                        {
                                     typeAndValueOfTag.put("output",initialValue);
                                     initialValue = Misc.EMPTY_STRING;
                                     continue;
                                        }
                                     }
                                     else if(tempName.equals("value"))
                                     {
                                        if(Misc.isNullTrimmedString(initialName) && Misc.isNullTrimmedString(initialLabel))
                                        {
                                     initialValue = tempValue;
                                        }
                                        else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("label"))
                                        {
                                     typeAndValueOfTag.put("output",tempValue);
                                     initialValue = Misc.EMPTY_STRING;
                                     continue;
                                        }
                                        else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("entry"))
                                        {
                                     if(!Misc.isNullTrimmedString(initialName) && initialName.equals("name"))
                                        typeAndValueOfTag.put("input",tempValue);
                                     else
                                        initialValue = tempValue;
                                        }
                                     }
                                     else if(tempName.equals("entry"))
                                     {
                                        if(Misc.isNullTrimmedString(initialValue) || Misc.isNullTrimmedString(initialLabel))
                                        {
                                     initialName = tempName;
                                        }
                                        else
                                     typeAndValueOfTag.put("input",initialValue);
                                                
                                        finalEncodedString.append("  " + tempName + "  " + tempValue + " ----- ");
                                     }*/
                                }

                                if (initialLabel != null) {
                                    if (initialLabel.equals("label")) {
                                        if (initialValue.equals(" User ID: ")) {
                                            TextView output1 = (TextView) findViewById(R.id.userNameText);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            userName = true;
                                            password = false;
                                        } else if (initialValue.equals("Password: ")) {
                                            TextView output1 = (TextView) findViewById(R.id.passwordText);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            password = true;
                                            userName = false;
                                        } else {
                                            TextView output1 = (TextView) findViewById(currentOutputTag++);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            userName = false;
                                            password = false;
                                        }
                                    } else if (initialLabel.equals("entry")) {
                                        if ("j_password".equals(initialName)) {
                                            EditText input = ((EditText) findViewById(R.id.passwordEdit));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter password");
                                            }
                                        } else if ("j_username".equals(initialName)) {
                                            EditText input = ((EditText) findViewById(R.id.userNameEdit));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter username");
                                            }
                                        } else {
                                            EditText input = ((EditText) findViewById(currentInputTag++));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter value");
                                            } else
                                                input.setText(initialValue);
                                        }
                                    }
                                }
                                /*if(initialLabel != null)
                                {
                                   List<String> listOfValues;
                                   if(typeAndValueOfTag.containsKey(initialLabel))
                                   {
                                  listOfValues = typeAndValueOfTag.get(initialLabel);
                                  listOfValues.add(initialValue);
                                   }
                                   typeAndValueOfTag.put(initialLabel,initialValue);
                                }*/
                            }
                        } else {
                            // Here, just the URL would get processed. So don't use.
                            // output.setText("  " + name + "  " + jsonObj1.getString(name1));
                        }
                    }
                }

                TextView welcome1 = (TextView) findViewById(R.id.welcome1);
                welcome1.setText(welcome1String);

                // processUIDisplay(typeAndValueOfTag);

                /*if(finalEncodedString.length() == 0)
                   finalEncodedString.append("Could not process");
                        
                output.setText(finalEncodedString.toString());
                        
                TextView output2 = (TextView) findViewById(R.id.Hidden1);
                output2.setText("Hidden one is enabled");
                output2.setVisibility(View.VISIBLE);*/

            } catch (JSONException e) {
                Log.e("Exception ", e.getMessage());

                Log.e("Exception ", e.getLocalizedMessage());

                Log.e("Exception ", e.getStackTrace().toString());
            }
        }

        hiddenText.setText("validated user");

        /* {"window":{"elements":[{"type":"hidden","name":"sourceAction"},{"type":"label","value":"Warehouse Management"},
                  {"type":"break"},{"type":"label","value":"--------- ----------"},{"type":"break"}, {"type":"label","value":" User ID: "},
                  {"type":"entry","name":"j_username","value":"","maxLength":15,"dispLength":10,
                  "setHidden":[{"hiddenName":"sourceAction","hiddenValue":"username"}],"focus":true},
                  {"type":"break"},{"type":"label","value":"Password: "},
                  {"type":"entry","name":"j_password","value":"","hideInput":true,"maxLength":14,"dispLength":10,"focus":false},
                  {"type":"keybinding","value":"CTRL-X","URL":"","keyDescription":"CTRL-X Exit"},
                  {"type":"keybinding","value":"CTRL-L","URL":"/scopeRF/RFLogin/RFLegal.jsp","keyDescription":"CTRL-L License Agreement"}]
           ,"submit":"/scopeRF/RFLogin/ProcessLogin.jsp"}}*/
    } else {
        List outputList = verifyUser();

        if (!Misc.isNullList(outputList)) {
            String sessionId = (String) outputList.get(0);
            String userType = (String) outputList.get(1);

            Intent intent = new Intent(this, MenuActivity.class);
            if (!Misc.isNullTrimmedString(sessionId) && !Misc.isNullTrimmedString(userType)
                    && Integer.parseInt(sessionId) > 0) {
                if (userType.equals(Constants.WORKER)) {
                    MenuActivity.sessionId = Misc.EMPTY_STRING;
                    TextView error = (TextView) findViewById(R.id.ErrorText);
                    error.setText(Misc.EMPTY_STRING);
                    error.setVisibility(View.GONE);
                    intent.putExtra(Constants.USER_TYPE, Constants.WORKER);
                    intent.putExtra(Constants.SESSION_ID, sessionId);
                } else {
                    TextView error = (TextView) findViewById(R.id.ErrorText);
                    error.setText(Misc.EMPTY_STRING);
                    error.setVisibility(View.GONE);
                    intent.putExtra(Constants.USER_TYPE, Constants.SUPERVISOR);
                    intent.putExtra(Constants.SESSION_ID, sessionId);
                }
            }
            // goto Maps screen
            // Get the message from the intent
            startActivity(intent);
        } else {

            TextView error = (TextView) findViewById(R.id.ErrorText);
            error.setText("Invalid Username/Password");
            error.setVisibility(View.VISIBLE);
        }
    }
    return;

}

From source file:org.uiautomation.ios.server.command.web.SetValueHandler.java

@Override
public Response handle() throws Exception {
    int id = Integer.parseInt(getRequest().getVariableValue(":reference"));
    RemoteWebElement element = new RemoteWebElement(new NodeId(id), getSession());

    JSONArray array = getRequest().getPayload().getJSONArray("value");
    String value = "";
    if (array.length() == 1) {
        Object o = array.get(0);//from  ww  w .j  av  a  2 s.  com
        if (o instanceof String) {
            value = (String) o;
        } else {
            throw new RuntimeException("NI");
        }
    } else {
        throw new RuntimeException("NI");
    }

    boolean useNativeEvents = getConfiguration("nativeEvents", nativeEvents);

    if (useNativeEvents) {
        element.setValueNative(value);
    } else {
        element.setValueAtoms(value);
    }

    Response res = new Response();
    res.setSessionId(getSession().getSessionId());
    res.setStatus(0);
    res.setValue(new JSONObject());
    return res;
}

From source file:com.sonoport.freesound.response.mapping.Mapper.java

/**
 * Transform a JSON Array into a {@link List}.
 *
 * @param jsonArray The {@link JSONArray} to convert
 * @return List of values/*from  w w  w  . j  av a2  s .  co m*/
 */
protected List<String> parseArray(final JSONArray jsonArray) {
    final List<String> arrayContents = new ArrayList<>();

    if (jsonArray != null) {
        for (int i = 0; i < jsonArray.length(); i++) {
            final String element = jsonArray.getString(i);
            if (element != null) {
                arrayContents.add(element);
            }
        }
    }

    return arrayContents;
}

From source file:com.sonoport.freesound.response.mapping.Mapper.java

/**
 * Transform an array of JSON Objects into a {@link List} of DTOs.
 *
 * @param <T> The object type contained with in the array
 *
 * @param jsonArray The {@link JSONArray} to convert
 * @param objectMapper The {@link Mapper} to use to process the JSON objects
 *
 * @return List of DTOs// w ww.ja v  a  2  s . com
 */
protected <T extends Object> List<T> parseArray(final JSONArray jsonArray,
        final Mapper<JSONObject, T> objectMapper) {
    final List<T> arrayContents = new ArrayList<>();

    if (jsonArray != null) {
        for (int i = 0; i < jsonArray.length(); i++) {
            final JSONObject element = jsonArray.getJSONObject(i);
            if (element != null) {
                arrayContents.add(objectMapper.map(element));
            }
        }
    }

    return arrayContents;
}