Example usage for org.json JSONArray getLong

List of usage examples for org.json JSONArray getLong

Introduction

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

Prototype

public long getLong(int index) throws JSONException 

Source Link

Document

Get the long value associated with an index.

Usage

From source file:com.tweetlanes.android.core.App.java

void updateTwitterAccountCount() {

    mAccounts.clear();//from   w  w  w.jav  a2 s  .  c  o  m

    long currentAccountId = mPreferences.getLong(SharedPreferencesConstants.CURRENT_ACCOUNT_ID, -1);
    String accountIndices = mPreferences.getString(SharedPreferencesConstants.ACCOUNT_INDICES, null);
    if (accountIndices != null) {
        try {
            JSONArray jsonArray = new JSONArray(accountIndices);
            for (int i = 0; i < jsonArray.length(); i++) {
                Long id = jsonArray.getLong(i);

                String key = getAccountDescriptorKey(id);
                String jsonAsString = mPreferences.getString(key, null);
                if (jsonAsString != null) {
                    AccountDescriptor account = new AccountDescriptor(this, jsonAsString);
                    if (Constant.ENABLE_APP_DOT_NET == false
                            && account.getSocialNetType() == SocialNetConstant.Type.Appdotnet) {
                        continue;
                    }
                    mAccounts.add(account);

                    if (currentAccountId != -1 && account.getId() == currentAccountId) {
                        mCurrentAccountIndex = i;
                    }
                }
            }

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

    if (mCurrentAccountIndex == null && mAccounts.size() > 0) {
        mCurrentAccountIndex = 0;
    }
}

From source file:oculus.aperture.common.JSONProperties.java

@Override
public Iterable<Long> getLongs(String key) {
    try {/*from   w ww. ja va 2  s .c om*/
        final JSONArray array = obj.getJSONArray(key);

        return new Iterable<Long>() {
            @Override
            public Iterator<Long> iterator() {
                return new Iterator<Long>() {
                    private final int n = array.length();
                    private int i = 0;

                    @Override
                    public boolean hasNext() {
                        return n > i;
                    }

                    @Override
                    public Long next() {
                        try {
                            return (n > i) ? array.getLong(i++) : null;
                        } catch (JSONException e) {
                            return null;
                        }
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };

    } catch (JSONException e) {
        return EmptyIterable.instance();
    }
}

From source file:com.mm.yamingapp.core.MethodDescriptor.java

/**
 * Converts a parameter from JSON into a Java Object.
 * /*from  w  w  w  .  j av  a2 s .  com*/
 * @return TODO
 */
// TODO(damonkohler): This signature is a bit weird (auto-refactored). The obvious alternative
// would be to work on one supplied parameter and return the converted parameter. However, that's
// problematic because you lose the ability to call the getXXX methods on the JSON array.
@VisibleForTesting
static Object convertParameter(final JSONArray parameters, int index, Type type)
        throws JSONException, RpcError {
    try {
        // We must handle null and numbers explicitly because we cannot magically cast them. We
        // also need to convert implicitly from numbers to bools.
        if (parameters.isNull(index)) {
            return null;
        } else if (type == Boolean.class) {
            try {
                return parameters.getBoolean(index);
            } catch (JSONException e) {
                return new Boolean(parameters.getInt(index) != 0);
            }
        } else if (type == Long.class) {
            return parameters.getLong(index);
        } else if (type == Double.class) {
            return parameters.getDouble(index);
        } else if (type == Integer.class) {
            return parameters.getInt(index);
        } else {
            // Magically cast the parameter to the right Java type.
            return ((Class<?>) type).cast(parameters.get(index));
        }
    } catch (ClassCastException e) {
        throw new RpcError(
                "Argument " + (index + 1) + " should be of type " + ((Class<?>) type).getSimpleName() + ".");
    }
}

From source file:net.geco.model.iojson.PersistentStore.java

public void importControls(JSONStore store, Registry registry) throws JSONException {
    if (store.has(K.CONTROLS)) { // MIRG 2.x -> 2.2
        JSONArray controls = store.getJSONArray(K.CONTROLS);
        for (int i = 0; i < controls.length(); i++) {
            JSONArray codeData = controls.getJSONArray(i);
            registry.setControlPenalty(codeData.getInt(0), new Date(codeData.getLong(1)));
        }//  w w w .jav a 2 s .  c  o  m
    }
}

From source file:net.geco.model.iojson.PersistentStore.java

public void importRunnersData(JSONStore store, Registry registry, Factory factory) throws JSONException {
    final int I_RUNNER = 0;
    final int I_ECARD = 1;
    final int I_RESULT = 2;
    JSONArray runnersData = store.getJSONArray(K.RUNNERS_DATA);
    for (int i = 0; i < runnersData.length(); i++) {
        JSONArray runnerTuple = runnersData.getJSONArray(i);

        JSONObject c = runnerTuple.getJSONObject(I_RUNNER);
        Runner runner = factory.createRunner();
        runner.setStartId(c.getInt(K.START_ID));
        runner.setFirstname(c.getString(K.FIRST));
        runner.setLastname(c.getString(K.LAST));
        runner.setEcard(c.getString(K.ECARD));
        runner.setClub(store.retrieve(c.getInt(K.CLUB), Club.class));
        runner.setCategory(store.retrieve(c.getInt(K.CAT), Category.class));
        runner.setCourse(store.retrieve(c.getInt(K.COURSE), Course.class));
        runner.setRegisteredStarttime(new Date(c.getLong(K.START)));
        runner.setArchiveId((Integer) c.opt(K.ARK));
        runner.setRentedEcard(c.optBoolean(K.RENT));
        runner.setNC(c.optBoolean(K.NC));
        registry.addRunner(runner);/*from   ww  w  .j av  a  2s .c  om*/

        JSONObject d = runnerTuple.getJSONObject(I_ECARD);
        RunnerRaceData raceData = factory.createRunnerRaceData();
        raceData.setStarttime(new Date(d.getLong(K.START)));
        raceData.setFinishtime(new Date(d.getLong(K.FINISH)));
        raceData.setControltime(new Date(d.getLong(K.CHECK)));
        raceData.setReadtime(new Date(d.getLong(K.READ)));
        JSONArray p = d.getJSONArray(K.PUNCHES);
        Punch[] punches = new Punch[p.length() / 2];
        for (int j = 0; j < punches.length; j++) {
            punches[j] = factory.createPunch();
            punches[j].setCode(p.getInt(2 * j));
            punches[j].setTime(new Date(p.getLong(2 * j + 1)));
        }
        raceData.setPunches(punches);
        raceData.setRunner(runner);
        registry.addRunnerData(raceData);

        JSONObject r = runnerTuple.getJSONObject(I_RESULT);
        TraceData traceData = factory.createTraceData();
        traceData.setNbMPs(r.getInt(K.MPS));
        traceData.setNbExtraneous(r.optInt(K.EXTRA)); // MIGR v2.x -> v2.3
        JSONArray t = r.getJSONArray(K.TRACE);
        Trace[] trace = new Trace[t.length() / 2];
        for (int j = 0; j < trace.length; j++) {
            trace[j] = factory.createTrace(t.getString(2 * j), new Date(t.getLong(2 * j + 1)));
        }
        if (r.has(K.SECTION_DATA)) {
            SectionTraceData sectionData = (SectionTraceData) traceData;
            JSONArray sections = r.getJSONArray(K.SECTION_DATA);
            for (int j = 0; j < sections.length(); j++) {
                JSONArray section = sections.getJSONArray(j);
                sectionData.putSectionAt(store.retrieve(section.getInt(0), Section.class), section.getInt(1));
            }
        }
        JSONArray neut = r.getJSONArray(K.NEUTRALIZED);
        for (int j = 0; j < neut.length(); j++) {
            trace[neut.getInt(j)].setNeutralized(true);
        }
        traceData.setTrace(trace);
        raceData.setTraceData(traceData);

        RunnerResult result = factory.createRunnerResult();
        result.setRaceTime(r.optLong(K.RACE_TIME, TimeManager.NO_TIME_l)); // MIGR v2.x -> v2.2
        result.setResultTime(r.getLong(K.TIME));
        result.setStatus(Status.valueOf(r.getString(K.STATUS)));
        result.setTimePenalty(r.getLong(K.PENALTY));
        result.setManualTimePenalty(r.optLong(K.MANUAL_PENALTY, 0)); // MIGR v2.x -> v2.3
        raceData.setResult(result);
    }
}

From source file:com.nextgis.firereporter.ScanexSubscriptionItem.java

protected void FillData(int nType, String sData) {
    String sCleanData = GetFiresService.removeJsonT(sData);
    try {// w w w  .  j  a  va 2 s. com
        JSONObject object = new JSONObject(sCleanData);
        String sStatus = object.getString("Status");
        if (sStatus.equals("OK")) {
            JSONArray jsonArray = object.getJSONArray("Result");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONArray jsonSubArray = jsonArray.getJSONArray(i);
                long nID = jsonSubArray.getLong(0);
                String sPtCoord = jsonSubArray.getString(1);
                int nConfidence = jsonSubArray.getInt(2);
                int nPower = jsonSubArray.getInt(3);
                String sURL1 = jsonSubArray.getString(4);
                String sURL2 = jsonSubArray.getString(5);
                String sType = jsonSubArray.getString(6);
                String sPlace = jsonSubArray.getString(7);
                String sDate = jsonSubArray.getString(8);
                String sMap = jsonSubArray.getString(9);

                if (!mmoItems.containsKey(nID)) {
                    ScanexNotificationItem Item = new ScanexNotificationItem(c, nID, sPtCoord, nConfidence,
                            nPower, sURL1, sURL2, sType, sPlace, sDate, sMap, R.drawable.ic_scan);
                    mmoItems.put(Item.GetId(), Item);
                    //notify changes
                    c.onNewNotifictation(GetId(), Item);
                    setHasNews(true);
                }
            }
        } else {
            SendError(object.getString("ErrorInfo"));
        }
    } catch (JSONException e) {
        SendError(e.getLocalizedMessage());
    }

    /*44({
       "Status": "OK",
       "ErrorInfo": "",
       "Result": [[1306601,
       "61.917, 63.090",
       68,
       27.4,
       "\u003ca href=\u0027http://maps.kosmosnimki.ru/TileService.ashx/apikeyV6IAK16QRG/mapT42E9?SERVICE=WMS&request=GetMap&version=1.3&layers=C7B2E6510209444E80673F3C37519F7E,FFE60CFA7DAF498381F811C08A5E8CF5,T42E9.A78AC25E0D924258B5AF40048C21F7E7_dt04102013&styles=&crs=EPSG:3395&transparent=FALSE&format=image/jpeg&width=460&height=460&bbox=6987987,8766592,7058307,8836912\u0027\u003e \u003cimg src=\u0027http://maps.kosmosnimki.ru/TileService.ashx/apikeyV6IAK16QRG/mapT42E9?SERVICE=WMS&request=GetMap&version=1.3&layers=C7B2E6510209444E80673F3C37519F7E,FFE60CFA7DAF498381F811C08A5E8CF5,T42E9.A78AC25E0D924258B5AF40048C21F7E7_dt04102013&styles=&crs=EPSG:3395&transparent=FALSE&format=image/jpeg&width=100&height=100&bbox=6987987,8766592,7058307,8836912\u0027 width=\u0027{4}\u0027 height=\u0027{5}\u0027 /\u003e\u003c/a\u003e",
       "\u003ca href=\u0027http://fires.kosmosnimki.ru/?x=63.09&y=61.917&z=11&dt=04.10.2013\u0027 target=\"_blank\"\u003eView on the map\u003c/a\u003e",
       "Fire",
       "",
       "\/Date(1380859500000)\/",
       "http://maps.kosmosnimki.ru/TileService.ashx/apikeyV6IAK16QRG/mapT42E9?SERVICE=WMS&request=GetMap&version=1.3&layers=C7B2E6510209444E80673F3C37519F7E,FFE60CFA7DAF498381F811C08A5E8CF5,T42E9.A78AC25E0D924258B5AF40048C21F7E7_dt04102013&styles=&crs=EPSG:3395&transparent=FALSE&format=image/jpeg&width=460&height=460&bbox=6987987,8766592,7058307,8836912",
       null]]
    })*/
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

private void remove(JSONObject graves) {
    // pretend to be the server so we don't set usn = -1
    boolean wasServer = mCol.getServer();
    mCol.setServer(true);//w w  w.j av a 2s.  c  om
    try {
        // notes first, so we don't end up with duplicate graves
        mCol._remNotes(Utils.jsonArrayToLongArray(graves.getJSONArray("notes")));
        // then cards
        mCol.remCards(Utils.jsonArrayToLongArray(graves.getJSONArray("cards")), false);
        // and decks
        JSONArray decks = graves.getJSONArray("decks");
        for (int i = 0; i < decks.length(); i++) {
            mCol.getDecks().rem(decks.getLong(i), false, false);
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    mCol.setServer(wasServer);
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

private ArrayList<Object[]> newerRows(JSONArray data, String table, int modIdx) {
    long[] ids = new long[data.length()];
    try {//from   www.j a  va 2 s  . co  m
        for (int i = 0; i < data.length(); i++) {
            ids[i] = data.getJSONArray(i).getLong(0);
        }
        HashMap<Long, Long> lmods = new HashMap<Long, Long>();
        Cursor cur = null;
        try {
            cur = mCol.getDb().getDatabase().rawQuery(
                    "SELECT id, mod FROM " + table + " WHERE id IN " + Utils.ids2str(ids) + " AND " + usnLim(),
                    null);
            while (cur.moveToNext()) {
                lmods.put(cur.getLong(0), cur.getLong(1));
            }
        } finally {
            if (cur != null && !cur.isClosed()) {
                cur.close();
            }
        }
        ArrayList<Object[]> update = new ArrayList<Object[]>();
        for (int i = 0; i < data.length(); i++) {
            JSONArray r = data.getJSONArray(i);
            if (!lmods.containsKey(r.getLong(0)) || lmods.get(r.getLong(0)) < r.getLong(modIdx)) {
                update.add(ConvUtils.jsonArray2Objects(r));
            }
        }
        return update;
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mirasense.scanditsdk.plugin.PickerControllerBase.java

@Override
public void finishDidScanCallback(JSONArray data) {
    mNextState = 0;// w ww . j a v  a 2  s.co  m
    if (data != null && data.length() > 0) {
        try {
            mNextState = data.getInt(0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ArrayList<Long> rejectedCodeIds = new ArrayList<Long>();
        try {
            JSONArray jsonData = data.getJSONArray(1);
            for (int i = 0; i < jsonData.length(); ++i) {
                rejectedCodeIds.add(jsonData.getLong(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        setRejectedCodeIds(rejectedCodeIds);
    }
    synchronized (mSync) {
        mInFlightDidScanCallbackId.set(0); // zero means no in-flight didScan callback
        mSync.notifyAll();
    }
}

From source file:uk.ac.imperial.presage2.web.export.DataExportServlet.java

/**
 * Processes the JSON query and returns a table in the form of a double
 * {@link Iterable}.//from   www . j a v a2 s  .c  om
 * 
 * @param query
 *            JSON table specification.
 * @return An {@link Iterable} which iterates over each row in the result
 *         set, which is also given as an {@link Iterable}.
 * @throws JSONException
 *             If there is an error in the specification.
 */
Iterable<Iterable<String>> processRequest(JSONObject query) throws JSONException {

    // build source set
    Set<PersistentSimulation> sourceSims = new HashSet<PersistentSimulation>();

    Set<Long> sources = new HashSet<Long>();
    JSONArray sourcesJSON = query.getJSONArray("sources");
    for (int i = 0; i < sourcesJSON.length(); i++) {
        long simId = sourcesJSON.getLong(i);
        PersistentSimulation sim = sto.getSimulationById(simId);
        if (sim != null) {
            // add simulation and all of it's decendents.
            getDecendents(simId, sources);
        }
    }
    // build sourceSims set from simIds we have collected.
    for (Long sim : sources) {
        sourceSims.add(sto.getSimulationById(sim));
    }

    // check type
    JSONArray parametersJSON = query.getJSONArray("parameters");
    boolean timeSeries = false;
    List<IndependentVariable> vars = new ArrayList<IndependentVariable>(parametersJSON.length());
    for (int i = 0; i < parametersJSON.length(); i++) {
        if (parametersJSON.getString(i).equalsIgnoreCase("time"))
            timeSeries = true;
        else
            vars.add(new ParameterColumn(sourceSims, parametersJSON.getString(i)));
    }

    JSONArray columns = query.getJSONArray("columns");
    ColumnDefinition[] columnDefs = new ColumnDefinition[columns.length()];
    for (int i = 0; i < columns.length(); i++) {
        columnDefs[i] = ColumnDefinition.createColumn(columns.getJSONObject(i), timeSeries);
        columnDefs[i].setSources(sourceSims);
    }

    TimeColumn time = timeSeries ? new TimeColumn(sourceSims) : null;
    return new IterableTable(vars.toArray(new IndependentVariable[] {}), time, sourceSims, columnDefs);

}