Example usage for org.json JSONArray getInt

List of usage examples for org.json JSONArray getInt

Introduction

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

Prototype

public int getInt(int index) throws JSONException 

Source Link

Document

Get the int value associated with an index.

Usage

From source file:com.yoncabt.ebr.util.ResultSetDeserializer.java

public List<Object[]> getData() {
    List<Object[]> ret = new ArrayList<>();
    JSONArray arr = jo.getJSONArray("values");
    for (int i = 0; i < arr.length(); i++) {
        List<Object> column = new ArrayList<>();
        JSONArray row = arr.getJSONArray(i);
        for (int j = 0; j < types.size(); j++) {
            if (row.isNull(j)) {
                column.add(null);//from   www  . j a  v a2s.com
            } else {
                switch (types.get(j)) {
                case DATE:
                    column.add(new Date(row.getLong(j)));
                    break;
                case STRING:
                    column.add(row.getString(j));
                    break;
                case INTEGER:
                    column.add(row.getInt(j));
                    break;
                case LONG:
                    column.add(row.getLong(j));
                    break;
                case DOUBLE:
                    column.add(row.getDouble(j));
                    break;
                default:
                    throw new AssertionError();
                }
            }
        }
        ret.add(column.toArray());
    }
    return ret;
}

From source file:com.dubsar_dictionary.Dubsar.model.Synset.java

@Override
public void parseData(Object jsonResponse) throws JSONException {
    JSONArray response = (JSONArray) jsonResponse;

    setPos(response.getString(1));/*from w  w w . java 2s .com*/
    setLexname(response.getString(2));
    mGloss = response.getString(3);

    JSONArray samples = response.getJSONArray(4);
    mSamples = new ArrayList<String>(samples.length());
    int j;
    for (j = 0; j < samples.length(); ++j) {
        mSamples.add(samples.getString(j));
    }

    JSONArray senses = response.getJSONArray(5);
    mSenses = new ArrayList<Sense>(senses.length());
    for (j = 0; j < senses.length(); ++j) {
        JSONArray _sense = senses.getJSONArray(j);

        int senseId = _sense.getInt(0);
        String senseName = _sense.getString(1);

        Sense sense = new Sense(senseId, senseName, this);
        sense.setLexname(getLexname());
        if (!_sense.isNull(2)) {
            sense.setMarker(_sense.getString(2));
        }
        sense.setFreqCnt(_sense.getInt(3));

        mSenses.add(sense);
    }

    mFreqCnt = response.getInt(6);

    parsePointers(response.getJSONArray(7));
}

From source file:plugin.geolocation.GeoBroker.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action       The action to execute.
 * @param args       JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return          True if the action was valid, or false if not.
 *//*w  ww.  j  a  v  a  2  s  . c o  m*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (locationManager == null) {
        locationManager = (LocationManager) this.cordova.getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
    }
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        if (networkListener == null) {
            networkListener = new NetworkListener(locationManager, this);
        }
        if (gpsListener == null) {
            gpsListener = new GPSListener(locationManager, this);
        }

        if (action.equals("getLocation")) {
            boolean enableHighAccuracy = args.getBoolean(0);
            int maximumAge = args.getInt(1);
            String provider = (enableHighAccuracy
                    && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                            ? LocationManager.GPS_PROVIDER
                            : LocationManager.NETWORK_PROVIDER;
            Location last = this.locationManager.getLastKnownLocation(provider);
            // Check if we can use lastKnownLocation to get a quick reading and use less battery
            if (last != null && (System.currentTimeMillis() - last.getTime()) <= maximumAge) {
                PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(last));
                callbackContext.sendPluginResult(result);
            } else {
                this.getCurrentLocation(callbackContext, enableHighAccuracy, args.optInt(2, 60000));
            }
        } else if (action.equals("addWatch")) {
            String id = args.getString(0);
            boolean enableHighAccuracy = args.getBoolean(1);
            this.addWatch(id, callbackContext, enableHighAccuracy);
        } else if (action.equals("clearWatch")) {
            String id = args.getString(0);
            this.clearWatch(id);
        } else {
            return false;
        }
    } else {
        PluginResult.Status status = PluginResult.Status.NO_RESULT;
        String message = "Location API is not available for this device.";
        PluginResult result = new PluginResult(status, message);
        callbackContext.sendPluginResult(result);
    }
    return true;
}

From source file:br.unicamp.cst.learning.glas.LearnerCodelet.java

@Override
public void proc() {

    if (enabled) {

        if ((first_run || (SOLUTION_TREE_MO.getEvaluation() < this.getGoal_fitness()))
                && !((String) EVENTS_SEQUENCE_MO.getI()).isEmpty()) {

            //         System.out.println("Init proc ... ");

            try {
                JSONArray sequence_json = new JSONArray(EVENTS_SEQUENCE_MO.getI());

                System.out.print(".");
                int sequence_lenght = sequence_json.length();
                //If (maxEventsSequenceLenght==Integer.MAX_VALUE), it tries to learn a new tree as soon as possible (if it has new events and previous learning is over)
                //TODO Increment this condition for it to start learning only if it makes a mistake?
                //If maxEventsSequenceLenght is a finite integer (set by the user) it waits until maxEventsSequenceLenght new events are presented to the current solution. Only then does it start learning a new sequence.
                if (maxEventsSequenceLenght == Integer.MAX_VALUE
                        || (sequence_lenght - last_number_of_events) >= maxEventsSequenceLenght) {

                    while (sequence_json.length() > maxEventsSequenceLenght) { // learns only with the last MAX_EVENTS_SEQUENCE_LENGHT events
                        sequence_json.remove(0);
                    }/*  w w  w . j  ava2s. c  o  m*/
                    if (this.printSequenceUsedForLearning) {
                        System.out.println("");
                    }
                    GlasSequence mySequence = new GlasSequence();
                    if (this.printSequenceUsedForLearning) {
                        System.out.println("Sequence used for learning: ");
                    }
                    for (int e = 0; e < sequence_json.length(); e++) {
                        //TODO Should be inside GlasSequence?            
                        JSONObject event_json = sequence_json.getJSONObject(e);
                        int stim = event_json.getInt(GlasSequenceElements.SENSED_STIMULUS.toString());
                        int act = event_json.getInt(GlasSequenceElements.EXPECTED_ACTION.toString());
                        double rew = event_json.getDouble(GlasSequenceElements.REWARD_RECEIVED.toString());

                        //                     Sequence used for learning: 
                        //                        0,2,0,-1.0 //TODO

                        if (this.printSequenceUsedForLearning) {
                            System.out.println(e + "," + stim + "," + act + "," + rew);
                        }

                        mySequence.addEvent(new GlasEvent(stim, act, rew));
                    }

                    //TODO Store WHO acted on this sequence, and its results

                    JSONArray solution_tree_phenotype_jsonarray = new JSONArray(SOLUTION_TREE_MO.getI());
                    int[] solution_tree_phenotype_int = new int[solution_tree_phenotype_jsonarray.length()];
                    for (int i = 0; i < solution_tree_phenotype_jsonarray.length(); i++) {
                        solution_tree_phenotype_int[i] = solution_tree_phenotype_jsonarray.getInt(i);
                    }

                    int[] genotype_int = this.getGenotypeFromPhenotype(solution_tree_phenotype_int);

                    int nNodesIndi = (solution_tree_phenotype_int.length / 3);
                    Individual indi = new Individual(nNodesIndi, nStimuli, nActions);
                    indi.setChromossome(genotype_int);

                    double max_fit = this.getMaxFitnessForSequence(mySequence);
                    double fit = indi.getFitness(mySequence);
                    indi.setNormalizedFitness(fit / max_fit);

                    indi_list.add(indi);
                    if (this.printLearnedSolutionTree) {
                        //                     System.out.println("");
                        System.out.print(fit + ",");
                        System.out.print(fit / max_fit + ",");
                        System.out.print(nNodesIndi + ",");
                        for (int i = 0; i < genotype_int.length; i++) {
                            System.out.print(genotype_int[i] + ",");
                        }
                        System.out.print(indi_list.size());
                        System.out.println("");
                    }

                    //LEARNING PHASE
                    System.out.println("I just started learning from a new sequence...");
                    int[] temp_best_found_int = { 1, 1, 1 };
                    double temp_best_found_fit = Double.NEGATIVE_INFINITY;
                    double normalized_fitness = Double.NEGATIVE_INFINITY;

                    GlasLearner myLearner = new GlasLearner(nNodes, nStimuli, nActions);
                    for (int local_nNodes = minNumberOfNodes; local_nNodes <= maxNumberOfNodes; local_nNodes++) {

                        myLearner = new GlasLearner(local_nNodes, nStimuli, nActions);
                        boolean show_gui = false;
                        myLearner.setShow_gui(show_gui);
                        myLearner.setnReRuns(nReRuns);
                        //      int max_number_reRuns=500;  //int max_number_reRuns=500;
                        //      int nParticles = 1000;            //int nParticles = 1000;
                        //      myLearner.setMax_number_reRuns(max_number_reRuns);
                        //      myLearner.setnParticles(nParticles);

                        //                     
                        myLearner.learnSequence(mySequence);
                        //                     
                        if (myLearner.getBest_found_fit() > temp_best_found_fit) {
                            temp_best_found_int = myLearner.getBest_found_solution();
                            temp_best_found_fit = myLearner.getBest_found_fit();
                        }

                        if (this.printLearnedSolutionTree) {
                            double temp_max_fit = this.getMaxFitnessForSequence(mySequence);
                            //                        System.out.println("");
                            System.out.print(temp_best_found_fit + ",");
                            normalized_fitness = temp_best_found_fit / temp_max_fit;
                            System.out.print(normalized_fitness + ",");
                            System.out.print(local_nNodes + ",");
                            for (int i = 0; i < temp_best_found_int.length - 1; i++) {
                                System.out.print(temp_best_found_int[i] + ",");
                            }
                            System.out.println(temp_best_found_int[temp_best_found_int.length - 1]);

                        }

                    }
                    System.out.println("...finished learning.");
                    int[] best_found_int = temp_best_found_int; //TODO Unnecessary?

                    int[] new_solution_tree_int = this.getPhenotypeFromGenotype(best_found_int);

                    double best_found_fit = temp_best_found_fit; //TODO Unnecessary?

                    best_solution_tree = new JSONArray();
                    for (int i = 0; i < new_solution_tree_int.length; i++) {
                        best_solution_tree.put(new_solution_tree_int[i]);
                    }

                    SOLUTION_TREE_MO.updateI(best_solution_tree.toString());
                    //                  SOLUTION_TREE_MO.setEvaluation(best_found_fit);
                    SOLUTION_TREE_MO.setEvaluation(normalized_fitness);
                    first_run = false;

                    //                  }
                    if (SOLUTION_TREE_MO.getEvaluation() >= this.getGoal_fitness()) {
                        System.out.println("Found goal fitness = " + SOLUTION_TREE_MO.getEvaluation());
                    }

                    if (plot_solution) {

                        double[] best_found_double = new double[best_found_int.length];

                        for (int i = 0; i < best_found_double.length; i++) {
                            best_found_double[i] = ((double) best_found_int[i]);
                        }

                        double[] sol = new double[nNodes * 3];
                        int count = 0;
                        for (int i = 0; i < sol.length; i++) {
                            if ((i % nNodes) == 0) {
                                sol[i] = 0;

                            } else {
                                sol[i] = best_found_double[count];
                                count++;
                            }

                        }

                        //                     ploter = new GlasPlot(sol);

                        //                     ploter.plot();

                    }

                    sequence_json = new JSONArray(EVENTS_SEQUENCE_MO.getI());
                    last_number_of_events = sequence_json.length();

                    //                  System.out.println("##########################################");

                } //if(sequence_json.length()>=MAX_EVENTS_SEQUENCE_LENGHT)

            } catch (JSONException e) {
                System.out.println("This should not happen! (at LearnerCodelet)");
                e.printStackTrace();
            }

        }

        if (indi_list.size() >= this.maxNumberOfSolutions) {
            System.out.println("Stopped learning.");
            this.setEnabled(false);
        }
    } else {//if enabled
            //         System.out.println("Learning is halted."); //Do nothing
    }

}

From source file:com.example.huma.al_malzma.helper.JsonHelper.java

/**
 * Creates an int array out of a json array.
 *
 * @param json The String containing the json array.
 * @return An array with the extracted integers or an
 * empty int array if an exception occurred.
 *//* www. j  a  va2 s .c o  m*/
public static int[] jsonArrayToIntArray(String json) {
    try {
        JSONArray jsonArray = new JSONArray(json);
        int[] intArray = new int[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            intArray[i] = jsonArray.getInt(i);
        }
        return intArray;
    } catch (JSONException e) {
        Log.e(TAG, "Error during Json processing: ", e);
    }
    return new int[0];
}

From source file:com.liferay.mobile.android.v62.shoppingcategory.ShoppingCategoryService.java

public Integer getCategoriesCount(long groupId, long parentCategoryId) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*  www.j a  va  2 s.  com*/
        JSONObject _params = new JSONObject();

        _params.put("groupId", groupId);
        _params.put("parentCategoryId", parentCategoryId);

        _command.put("/shoppingcategory/get-categories-count", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getInt(0);
}

From source file:com.baroq.pico.google.PlayServices.java

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) {

    try {/*from  w w w.  ja v a2  s.c o m*/
        if (!ACTION_SETUP.equals(action) && !ACTION_SIGNIN.equals(action)
                && (null == mHelper || !mHelper.isConnected())) {
            callbackContext.error("Please setup and signin to use PlayServices plugin");
            return false;
        }
        if (ACTION_SETUP.equals(action)) {
            int l = data.length();
            if (0 == l) {
                callbackContext.error("Expecting at least 1 parameter for action: " + action);
                return false;
            }
            clientTypes = data.getInt(0);
            String[] extraScopes = new String[l - 1];
            for (int i = 1; i < l; i++) {
                extraScopes[i - 1] = data.getString(i);
            }
            setup(clientTypes, extraScopes, callbackContext);
            PluginResult pluginResult = new PluginResult(PluginResult.Status.NO_RESULT);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_SIGNIN.equals(action)) {
            mHelper.beginUserInitiatedSignIn();
            callbackContext.success();
        } else if (ACTION_SIGNOUT.equals(action)) {
            signout();
            callbackContext.success();
        } else if (ACTION_AS_MAX_KEYS.equals(action)) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                    mHelper.getAppStateClient().getMaxNumKeys());
            pluginResult.setKeepCallback(false);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_AS_MAX_SIZE.equals(action)) {
            PluginResult pluginResult = new PluginResult(PluginResult.Status.OK,
                    mHelper.getAppStateClient().getMaxStateSize());
            pluginResult.setKeepCallback(false);
            callbackContext.sendPluginResult(pluginResult);
        } else if (ACTION_AS_DEL.equals(action)) {
            int key = data.getInt(0);
            mHelper.getAppStateClient().deleteState(this, key);
            callbackContext.success();
        } else if (ACTION_AS_LIST.equals(action)) {
            mHelper.getAppStateClient().listStates(this);
            callbackContext.success();
        } else if (ACTION_AS_LOAD.equals(action)) {
            int key = data.getInt(0);
            mHelper.getAppStateClient().loadState(this, key);
            callbackContext.success();
        } else if (ACTION_AS_RESOLVE.equals(action)) {
            int key = data.getInt(0);
            String resolvedVersion = data.getString(1);
            String value = data.getString(2);
            mHelper.getAppStateClient().resolveState(this, key, resolvedVersion, value.getBytes());
            callbackContext.success();
        } else if (ACTION_AS_UPDATE.equals(action)) {
            int key = data.getInt(0);
            String value = data.getString(1);
            mHelper.getAppStateClient().updateState(key, value.getBytes());
            callbackContext.success();
        } else if (ACTION_AS_UPDATE_NOW.equals(action)) {
            int key = data.getInt(0);
            String value = data.getString(1);
            mHelper.getAppStateClient().updateStateImmediate(this, key, value.getBytes());
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_ACHIEVEMENTS.equals(action)) {
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getAchievementsIntent(), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_LEADERBOARDS.equals(action)) {
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getAllLeaderboardsIntent(), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_SHOW_LEADERBOARD.equals(action)) {
            String id = data.getString(0);
            cordova.startActivityForResult((CordovaPlugin) this,
                    mHelper.getGamesClient().getLeaderboardIntent(id), RC_UNUSED);
            callbackContext.success();
        } else if (ACTION_GAME_INCR_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            int numSteps = data.getInt(1);
            mHelper.getGamesClient().incrementAchievement(id, numSteps);
            callbackContext.success();
        } else if (ACTION_GAME_INCR_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            int numSteps = data.getInt(1);
            mHelper.getGamesClient().incrementAchievementImmediate(this, id, numSteps);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_ACHIEVEMENTS.equals(action)) {
            boolean forceReload = data.getBoolean(0);
            mHelper.getGamesClient().loadAchievements(this, forceReload);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_GAME.equals(action)) {
            mHelper.getGamesClient().loadGame(this);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_LEADERBOARD_METADATA.equals(action)) {
            if (1 == data.length()) {
                mHelper.getGamesClient().loadLeaderboardMetadata(this, data.getBoolean(0));
            } else {
                mHelper.getGamesClient().loadLeaderboardMetadata(this, data.getString(0), data.getBoolean(1));
            }
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_MORE_SCORES.equals(action)) {
            if (null == scoreBuffer) {
                callbackContext.error("Get a leaderboard fist before calling: " + action);
                return false;
            }
            int maxResults = data.getInt(0);
            int pageDirection = data.getInt(0);
            mHelper.getGamesClient().loadMoreScores(this, scoreBuffer, maxResults, pageDirection);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_PLAYER.equals(action)) {
            String playerId = data.getString(0);
            mHelper.getGamesClient().loadPlayer(this, playerId);
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_PLAYER_CENTERED_SCORES.equals(action)) {
            String leaderboardId = data.getString(0);
            int span = data.getInt(1);
            int leaderboardCollection = data.getInt(2);
            int maxResults = data.getInt(3);
            if (data.isNull(4)) {
                mHelper.getGamesClient().loadPlayerCenteredScores(this, leaderboardId, span,
                        leaderboardCollection, maxResults);
            } else {
                boolean forceReload = data.getBoolean(4);
                mHelper.getGamesClient().loadPlayerCenteredScores(this, leaderboardId, span,
                        leaderboardCollection, maxResults, forceReload);
            }
            callbackContext.success();
        } else if (ACTION_GAME_LOAD_TOP_SCORES.equals(action)) {
            String leaderboardId = data.getString(0);
            int span = data.getInt(1);
            int leaderboardCollection = data.getInt(2);
            int maxResults = data.getInt(3);
            if (data.isNull(4)) {
                mHelper.getGamesClient().loadTopScores(this, leaderboardId, span, leaderboardCollection,
                        maxResults);
            } else {
                boolean forceReload = data.getBoolean(4);
                mHelper.getGamesClient().loadTopScores(this, leaderboardId, span, leaderboardCollection,
                        maxResults, forceReload);
            }
            callbackContext.success();
        } else if (ACTION_GAME_REVEAL_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().revealAchievement(id);
            callbackContext.success();
        } else if (ACTION_GAME_REVEAL_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().revealAchievementImmediate(this, id);
            callbackContext.success();
        } else if (ACTION_GAME_SUBMIT_SCORE.equals(action)) {
            String leaderboardId = data.getString(0);
            int score = data.getInt(1);
            mHelper.getGamesClient().submitScore(leaderboardId, score);
            callbackContext.success();
        } else if (ACTION_GAME_SUBMIT_SCORE_NOW.equals(action)) {
            String leaderboardId = data.getString(0);
            int score = data.getInt(1);
            mHelper.getGamesClient().submitScoreImmediate(this, leaderboardId, score);
            callbackContext.success();
        } else if (ACTION_GAME_UNLOCK_ACHIEVEMENT.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().unlockAchievement(id);
            callbackContext.success();
        } else if (ACTION_GAME_UNLOCK_ACHIEVEMENT_NOW.equals(action)) {
            String id = data.getString(0);
            mHelper.getGamesClient().unlockAchievementImmediate(this, id);
            callbackContext.success();
        } else {
            callbackContext.error("Unknown action: " + action);
            return false;
        }
    } catch (JSONException ex) {
        callbackContext.error(ex.getMessage());
        return false;
    }

    return true;
}

From source file:com.dubsar_dictionary.Dubsar.model.DailyWord.java

@Override
public void parseData(Object jsonResponse) throws JSONException {
    JSONArray response = (JSONArray) jsonResponse;

    int id = response.getInt(0);
    String name = response.getString(1);
    String pos = response.getString(2);
    int freqCnt = response.getInt(3);
    String inflections = response.getString(4);

    mWord = new Word(id, name, pos);

    mWord.setFreqCnt(freqCnt);//from   w w w .ja  va  2 s  .c  o  m
    mWord.setInflections(inflections);

    mExpirationMillis = response.getLong(5) * 1000;
}

From source file:io.rapidpro.androidchannel.json.JSON.java

public Integer[] getIntegerArray(String key) {
    try {//  w w  w. j a  va  2 s  . c o m
        JSONArray array = m_o.getJSONArray(key);
        Integer[] integerArray = new Integer[array.length()];
        for (int i = 0; i < integerArray.length; i++) {
            integerArray[i] = array.getInt(i);
        }
        return integerArray;
    } catch (Throwable t) {
        throw new JSONException(t);
    }
}

From source file:jGW2API.util.wvw.MatchDetails.java

public MatchDetails(JSONObject json) {
    this.maps = new ArrayList();
    this.matchID = json.getString("match_id");
    JSONArray tmp = json.getJSONArray("scores");
    this.redScore = new Integer(tmp.getInt(0));
    this.blueScore = new Integer(tmp.getInt(1));
    this.greenScore = new Integer(tmp.getInt(2));
    tmp = json.getJSONArray("maps");
    for (int i = 0; i < tmp.length(); i++) {
        this.maps.add(new WvWMap(tmp.getJSONObject(i)));
    }/*from  ww w.j  a  va  2 s .c o m*/
}