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:ch.icclab.cyclops.resource.impl.ExternalAppResource.java

/**
 * Receives the JSON array, transforms it and send it to the db resource to persist it into InfluxDB
 *
 * Pseudo Code/*from   w  w w  .j a v  a  2s  .  c  om*/
 * 1. Iterate through the JSONArray to get the JSON obj
 * 2. Iterate through the JSON Obj to get the usage details
 * 3. Build the TSDB POJO
 * 4. Pass this POJO obj to the TSDB resource for persisting it into the DB
 *
 * @param jsonArr An array containing the usage data as part of JSON Objects
 * @return String
 */
public boolean saveData(JSONArray jsonArr) {

    JSONObject jsonObj, metadata, usageData;
    String metername = null;
    String source;
    TSDBResource dbResource = new TSDBResource();
    JSONArray dataArr;
    ArrayList<Object> objArrNode;
    ArrayList<ArrayList<Object>> objArr = new ArrayList<ArrayList<Object>>();
    TSDBData dbData = new TSDBData();
    ArrayList<String> columnNameArr = new ArrayList<String>();
    columnNameArr.add("timestamp");
    columnNameArr.add("userid");
    columnNameArr.add("source");
    columnNameArr.add("usage");

    try {
        for (int i = 0; i < jsonArr.length(); i++) {
            jsonObj = (JSONObject) jsonArr.get(i);
            metadata = (JSONObject) jsonObj.get("metadata");
            source = (String) metadata.get("source");
            dataArr = (JSONArray) jsonObj.get("usage");

            for (int j = 0; j < dataArr.length(); j++) {
                objArrNode = new ArrayList<Object>();
                usageData = (JSONObject) dataArr.get(j);
                metername = (String) usageData.get("metername");
                objArrNode.add(usageData.get("timestamp"));
                objArrNode.add(usageData.get("userid"));
                objArrNode.add(source);
                objArrNode.add(usageData.get("usage"));
                objArr.add(objArrNode);
            }
            dbData.setName(metername);
            dbData.setColumns(columnNameArr);
            dbData.setPoints(objArr);

            dbResource.saveExtData(dbData);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.ct.speech.HintReceiver.java

/**
 * Fire an intent to start the speech recognition activity.
 * // w w  w. j  a v  a 2s  . c o  m
 * @param args
 *            Argument array with the following string args: [req
 *            code][number of matches][prompt string] Google speech
 *            recognizer
 */

private void startSpeechRecognitionActivity(JSONArray args) {
    // int reqCode = 42; // Hitchhiker? // global now
    int maxMatches = 2;
    String prompt = "";
    String language = "";
    try {
        if (args.length() > 0) {
            // Request code - passed back to the caller on a successful
            // operation
            String temp = args.getString(0);
            reqCode = Integer.parseInt(temp);
        }
        if (args.length() > 1) {
            // Maximum number of matches, 0 means the recognizer decides
            String temp = args.getString(1);
            maxMatches = Integer.parseInt(temp);
        }
        if (args.length() > 2) {
            // Optional text prompt
            prompt = args.getString(2);
        }
        if (args.length() > 3) {
            // Optional language specified
            language = args.getString(3);
        }
    } catch (Exception e) {
        Log.e(TAG, String.format("startSpeechRecognitionActivity exception: %s", e.toString()));
    }
    final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra("calling_package", "com.ct.BasicAppFrame");
    // If specific language
    if (!language.equals("")) {
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
    }
    if (maxMatches > 0)
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches);
    if (!(prompt.length() == 0))
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
    // ctx.startActivityForResult(this, intent, reqCode); //removed to try
    // using recognizer directly
    try {
        this.ctx.runOnUiThread(new Runnable() {
            public void run() {
                final SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer((Context) ctx);
                RecognitionListener listener = new RecognitionListener() {
                    @Override
                    public void onResults(Bundle results) {
                        //closeRecordedFile();
                        sendBackResults(results);
                        ArrayList<String> voiceResults = results
                                .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                        if (voiceResults == null) {
                            Log.e(TAG, "No voice results");
                        } else {
                            // Log.d(TAG, "Printing matches: ");
                            for (@SuppressWarnings("unused")
                            String match : voiceResults) {
                                // Log.d(TAG, match);
                            }
                        }
                        recognizer.destroy();
                    }

                    @Override
                    public void onReadyForSpeech(Bundle params) {
                        // Log.d(TAG, "Ready for speech");
                    }

                    @Override
                    public void onError(int error) {
                        Log.d(TAG, "Error listening for speech: " + error);
                        if (error == SpeechRecognizer.ERROR_NO_MATCH) {
                            sendBackResults(NO_MATCH);
                        } else if (error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT) {
                            sendBackResults(NO_INPUT);
                        } else {
                            speechFailure("unknown error");
                        }
                        recognizer.destroy();
                    }

                    @Override
                    public void onBeginningOfSpeech() {
                        // Log.d(TAG, "Speech starting");
                        setStartOfSpeech();
                    }

                    @Override
                    //doesn't fire in Android after Ice Cream Sandwich
                    public void onBufferReceived(byte[] buffer) {
                    }

                    @Override
                    public void onEndOfSpeech() {
                        setEndOfSpeech();
                    }

                    @Override
                    public void onEvent(int eventType, Bundle params) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onPartialResults(Bundle partialResults) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onRmsChanged(float rmsdB) {
                        // TODO Auto-generated method stub

                    }
                };
                recognizer.setRecognitionListener(listener);
                Log.d(TAG, "starting speech recognition activity");
                recognizer.startListening(intent);
            }
        });
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.openquartz.glassmemo.Utils.java

/**
 * Gets the arraylist from shared preferences 
 * @param context/*from   w  ww.  ja va2 s  . co  m*/
 * @param key
 * @return
 */
public static ArrayList<String> getStringArrayPref(final Context context, String key) {

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
    String json = sharedPref.getString(key, null);
    ArrayList<String> memoList = new ArrayList<String>();

    if (json != null) {
        try {
            JSONArray a = new JSONArray(json);

            for (int i = 0; i < a.length(); i++) {
                memoList.add(a.optString(i));
            }
        } catch (JSONException e) {
        }
    }

    return memoList;
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitCherryPickTest.java

@Test
public void testCherryPick() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

        // get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());

        String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION);
        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "first line\nsec. line\nthird line\n");

        addFile(testTxt);//  w  w w  . ja v  a2  s  .  c om

        commitFile(testTxt, "lines in test.txt", false);

        // create new file
        String fileName = "new.txt";
        request = getPostFilesRequest(folderLocation + "/", getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        // add all
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "added new.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsec. line\nthird line\nfourth line\n");

        // add
        addFile(testTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enlarged test.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsecond line\nthird line\nfourth line\n");

        // add
        addFile(testTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "fixed test.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // remember starting point and commit to cherry-pick
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(5, commitsArray.length());
        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String toCherryPick = commit.getString(ProtocolConstants.KEY_NAME);
        commit = commitsArray.getJSONObject(3);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String startingPoint = commit.getString(ProtocolConstants.KEY_NAME);

        // branch
        response = branch(branchesLocation, "side", startingPoint);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        response = checkoutBranch(cloneLocation, "side");
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsec. line\nthird line\nfeature++\n");

        // add
        addFile(testTxt);

        // commit
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "enhanced test.txt", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // CHERRY-PICK
        JSONObject cherryPick = cherryPick(gitHeadUri, toCherryPick);
        CherryPickStatus mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT));
        assertEquals(CherryPickStatus.OK, mergeResult);
        assertTrue(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED));

        // try again, should be OK, but nothing changed
        cherryPick = cherryPick(gitHeadUri, toCherryPick);
        mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT));
        assertEquals(CherryPickStatus.OK, mergeResult);
        assertFalse(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED));

        // 'new.txt' should be not there
        JSONObject newTxt = getChild(folder, "new.txt");
        assertNull(newTxt);

        // check cherry-pick result in the file
        request = getGetRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION));
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        assertEquals("first line\nsecond line\nthird line\nfeature++\n", response.getText());

        // check log
        commitsArray = log(gitHeadUri);
        assertEquals(4, commitsArray.length());
        commit = commitsArray.getJSONObject(0);
        assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(1);
        assertEquals("enhanced test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(2);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(3);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
    }
}

From source file:com.ecml.MidiOptions.java

/** Initialize the options from a json string
 * /* ww w.j  a  v a 2s .  c  o m*/
 * @param jsonString
 */
public static MidiOptions fromJson(String jsonString) {
    if (jsonString == null) {
        return null;
    }
    MidiOptions options = new MidiOptions();
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray jsonTracks = json.getJSONArray("tracks");
        options.tracks = new boolean[jsonTracks.length()];
        for (int i = 0; i < options.tracks.length; i++) {
            options.tracks[i] = jsonTracks.getBoolean(i);
        }

        JSONArray jsonMute = json.getJSONArray("mute");
        options.mute = new boolean[jsonMute.length()];
        for (int i = 0; i < options.mute.length; i++) {
            options.mute[i] = jsonMute.getBoolean(i);
        }

        JSONArray jsonInstruments = json.getJSONArray("instruments");
        options.instruments = new int[jsonInstruments.length()];
        for (int i = 0; i < options.instruments.length; i++) {
            options.instruments[i] = jsonInstruments.getInt(i);
        }

        if (json.has("time")) {
            JSONObject jsonTime = json.getJSONObject("time");
            int numer = jsonTime.getInt("numerator");
            int denom = jsonTime.getInt("denominator");
            int quarter = jsonTime.getInt("quarter");
            int tempo = jsonTime.getInt("tempo");
            options.time = new TimeSignature(numer, denom, quarter, tempo);
        }

        options.useDefaultInstruments = json.getBoolean("useDefaultInstruments");
        options.scrollVert = json.getBoolean("scrollVert");
        options.showPiano = json.getBoolean("showPiano");
        options.showNoteColors = json.getBoolean("showNoteColors");
        options.showLyrics = json.getBoolean("showLyrics");
        options.delay = json.getInt("delay");
        options.twoStaffs = json.getBoolean("twoStaffs");
        options.showNoteLetters = json.getInt("showNoteLetters");
        options.transpose = json.getInt("transpose");
        options.key = json.getInt("key");
        options.combineInterval = json.getInt("combineInterval");
        options.shade1Color = json.getInt("shade1Color");
        options.shade2Color = json.getInt("shade2Color");
        options.showMeasures = json.getBoolean("showMeasures");
        options.playMeasuresInLoop = json.getBoolean("playMeasuresInLoop");
        options.playMeasuresInLoopStart = json.getInt("playMeasuresInLoopStart");
        options.playMeasuresInLoopEnd = json.getInt("playMeasuresInLoopEnd");
    } catch (Exception e) {
        return null;
    }
    return options;
}

From source file:com.andybotting.tramhunter.objects.FavouriteList.java

/**
 * Get the favourite items//  w  ww . jav  a 2 s .  c  o  m
 * @return 
 */
public ArrayList<Favourite> getFavouriteItems() {

    ArrayList<Favourite> favourites = new ArrayList<Favourite>();
    JSONArray favouriteJSONArray = null;
    TramHunterDB db = new TramHunterDB();

    // Fetch JSON favourite stops string from preferences
    String favouriteString = mPreferenceHelper.getStarredStopsString();
    if (LOGV)
        Log.i(TAG, "Parsing favourite string: " + favouriteString);

    // Check to see if we even have any favourites
    if (favouriteString.length() > 1) {

        // Convert any old favourites - if not a JSON Array
        if (!favouriteString.contains("["))
            favouriteString = convertOldFavourites(favouriteString);

        try {
            favouriteJSONArray = new JSONArray(favouriteString);

            for (int i = 0; i < favouriteJSONArray.length(); i++) {

                JSONObject favouriteJSONObject = favouriteJSONArray.getJSONObject(i);

                int tramTrackerID = favouriteJSONObject.optInt("stop");
                int routeID = favouriteJSONObject.optInt("route", -1);
                String name = favouriteJSONObject.optString("name", null);

                Stop stop = db.getStop(tramTrackerID);
                Route route = null;

                if (routeID != -1)
                    route = db.getRoute(routeID);

                favourites.add(new Favourite(stop, route, name));
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    db.close();
    return favourites;
}

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

@Override
public List<I> map(final JSONObject source) {
    final List<I> items = new LinkedList<>();
    final JSONArray resultsArray = extractFieldValue(source, "results", JSONArray.class);

    if (resultsArray != null) {
        for (int i = 0; i < resultsArray.length(); i++) {
            if (!resultsArray.isNull(i)) {
                final JSONObject jsonObject = resultsArray.getJSONObject(i);
                if ((jsonObject != null)) {
                    final I item = itemMapper.map(jsonObject);
                    items.add(item);// ww  w  .ja  v  a 2s .c  o  m
                }
            }
        }
    }

    return items;
}

From source file:de.kp.ames.web.function.transform.cache.XslCacheManager.java

/**
 * This method retrieves the actually uploaded transformators 
 * that are currently not registered in the OASIS ebXML RegRep
 * /*from   www  .  jav a 2 s .  co m*/
 * @return
 * @throws Exception
 */
public JSONArray getJEntries() throws Exception {

    JSONArray jEntries = new JSONArray();

    List<CacheEntry> transformators = cache.getAll();
    for (int ix = 0; ix < transformators.size(); ix++) {

        XslTransformator transformator = (XslTransformator) transformators.get(ix);
        String key = transformator.getKey();

        JSONObject jTransformator = new JSONObject();

        jTransformator.put(JsonConstants.J_KEY, key);
        jTransformator.put(JsonConstants.J_NAME, transformator.getName());

        jTransformator.put(JsonConstants.J_DESC, "No description available.");
        jTransformator.put(JsonConstants.J_MIME, transformator.getMimetype());

        jEntries.put(jEntries.length(), jTransformator);

    }

    return jEntries;

}

From source file:com.keylesspalace.tusky.util.NotificationMaker.java

public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;//from   w  ww  .j av a  2  s  .com
    }

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }

    notificationPreferences.edit().putString("current", currentNotifications.toString()).commit();

    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body))
                .setContentText(truncateWithEllipses(bodyForType(body), 40));

        Target mTarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                builder.setLargeIcon(bitmap);

                setupPreferences(preferences, builder);

                ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE)))
                        .notify(notifyId, builder.build());
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        };

        Picasso.with(context).load(body.account.avatar).placeholder(R.drawable.avatar_default)
                .transform(new RoundedTransformation(7, 0)).into(mTarget);
    } else {
        setupPreferences(preferences, builder);
        try {
            builder.setContentTitle(String.format(context.getString(R.string.notification_title_summary),
                    currentNotifications.length()))
                    .setContentText(truncateWithEllipses(joinNames(context, currentNotifications), 40));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE))).notify(notifyId,
            builder.build());
}

From source file:com.keylesspalace.tusky.util.NotificationMaker.java

@Nullable
private static String joinNames(Context context, JSONArray array) throws JSONException {
    if (array.length() > 3) {
        return String.format(context.getString(R.string.notification_summary_large), array.get(0), array.get(1),
                array.get(2), array.length() - 3);
    } else if (array.length() == 3) {
        return String.format(context.getString(R.string.notification_summary_medium), array.get(0),
                array.get(1), array.get(2));
    } else if (array.length() == 2) {
        return String.format(context.getString(R.string.notification_summary_small), array.get(0),
                array.get(1));/*from  ww  w  .  j av a2 s.  c  om*/
    }

    return null;
}