Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray() 

Source Link

Document

Construct an empty JSONArray.

Usage

From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private WebViewClient createWebViewClientThatHandlesFileLinksForCharts() {
    WebViewClient webViewClient = new WebViewClient() {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Uri uri = Uri.parse(url);//from  ww  w.  java2  s  .c  o  m
            if (uri.getScheme().startsWith("http")) {
                return true; // throw away http requests - we don't want 3rd party javascript sending url requests due to security issues.
            }

            String inputIdStr = uri.getQueryParameter("inputId");
            if (inputIdStr == null) {
                return true;
            }
            long inputId = Long.parseLong(inputIdStr);
            JSONArray results = new JSONArray();
            for (Event event : experiment.getEvents()) {
                JSONArray eventJson = new JSONArray();
                DateTime responseTime = event.getResponseTime();
                if (responseTime == null) {
                    continue; // missed signal;
                }
                eventJson.put(responseTime.getMillis());

                // in this case we are looking for one input from the responses that we are charting.
                for (Output response : event.getResponses()) {
                    if (response.getInputServerId() == inputId) {
                        Input inputById = experiment.getInputById(inputId);
                        if (!inputById.isInvisible() && inputById.isNumeric()) {
                            eventJson.put(response.getDisplayOfAnswer(inputById));
                            results.put(eventJson);
                            continue;
                        }
                    }
                }

            }
            env.put("data", results.toString());
            env.put("inputId", inputIdStr);

            view.loadUrl(stripQuery(url));
            return true;
        }
    };
    return webViewClient;
}

From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private static String convertEventsToJsonString(final Experiment experiment, List<Event> events) {
    // TODO use jackson instead. But preserve these synthesized values for backward compatibility.
    final JSONArray experimentData = new JSONArray();
    for (Event event : events) {
        try {/*from  w  w w .  j  av  a 2  s . c  o m*/
            JSONObject eventObject = new JSONObject();
            boolean missed = event.getResponseTime() == null;
            eventObject.put("isMissedSignal", missed);
            if (!missed) {
                eventObject.put("responseTime", event.getResponseTime().getMillis());
            }

            boolean selfReport = event.getScheduledTime() == null;
            eventObject.put("isSelfReport", selfReport);
            if (!selfReport) {
                eventObject.put("scheduleTime", event.getScheduledTime().getMillis());
            }

            JSONArray responses = new JSONArray();
            for (Output response : event.getResponses()) {
                JSONObject responseJson = new JSONObject();
                Input input = experiment.getInputById(response.getInputServerId());
                if (input == null) {
                    continue;
                }
                responseJson.put("inputId", input.getServerId());
                // deprecate inputName in favor of name
                responseJson.put("inputName", input.getName());
                responseJson.put("name", input.getName());
                responseJson.put("responseType", input.getResponseType());
                responseJson.put("isMultiselect", input.isMultiselect());
                responseJson.put("prompt", getTextOfInputForOutput(experiment, response));
                responseJson.put("answer", response.getDisplayOfAnswer(input));
                // deprecated for answerRaw
                responseJson.put("answerOrder", response.getAnswer());
                responseJson.put("answerRaw", response.getAnswer());
                responses.put(responseJson);
            }

            eventObject.put("responses", responses);
            if (responses.length() > 0) {
                experimentData.put(eventObject);
            }
        } catch (JSONException jse) {
            // skip this event and do the next event.
        }
    }
    String experimentDataAsJson = experimentData.toString();
    return experimentDataAsJson;
}

From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java

/**
 * Gets the job data.//from w w  w .j  a  v  a  2  s  .c  om
 * 
 * @param thermostatId
 *            the thermostat id
 * @return the job data
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#getJobData(java.lang.Integer)
 */
@Override
public JSONArray getJobData(Integer thermostatId) {

    if (jobData == null) {
        log("Get json Array for Thermostat Id : " + thermostatId, true);
        Thermostat thermostat = findBythermostatId(thermostatId);
        jobDataList = mockJobDataBuilder.build(testName, thermostat.getTimezone());
        jobData = new JSONArray();
        int i = 0;
        for (MockJobData mockJobData : jobDataList) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("start", DateUtil.format(mockJobData.getStart(), "HH:mm:ss"));
                jsonObject.put("end", DateUtil.format(mockJobData.getEnd(), "HH:mm:ss"));
                jsonObject.put("moBlackOut", mockJobData.getBlackout());
                Calendar cuttOffTime = (Calendar) Calendar
                        .getInstance(TimeZone.getTimeZone(thermostat.getTimezone())).clone();
                cuttOffTime.set(Calendar.HOUR_OF_DAY, 0);
                cuttOffTime.set(Calendar.MINUTE, 0);
                cuttOffTime.set(Calendar.SECOND, 0);
                if (mockJobData.getCutoff() == null) {
                    jsonObject.put("moCutoff", DateUtil.format(cuttOffTime, "HH:mm:ss"));
                } else {
                    jsonObject.put("moCutoff", mockJobData.getCutoff());
                }

                jsonObject.put("moRecovery", mockJobData.getRecovery());
                jsonObject.put("deltaEE", mockJobData.getDelta());
                jobData.put(i, jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            i++;
        }
        log("Json Array : " + jobData, true);
        DataUtil.printMockSPOJobDataJson(jobData);
    }

    return jobData;
}

From source file:net.olejon.mdapp.InteractionsCardsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();/*ww w .  j  av  a  2 s. c o m*/

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

    // Layout
    setContentView(R.layout.activity_interactions_cards);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.interactions_cards_toolbar);
    mToolbar.setTitle(getString(R.string.interactions_cards_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.interactions_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.interactions_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.interactions_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new InteractionsCardsAdapter(mContext, mProgressBar, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No interactions
    mNoInteractionsLayout = (LinearLayout) findViewById(R.id.interactions_cards_no_interactions);

    Button noInteractionsButton = (Button) findViewById(R.id.interactions_cards_no_interactions_button);

    noInteractionsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.interactions_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "http://interaksjoner.no/analyser.asp?PreparatNavn="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&submit1=Sjekk");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("InteractionsCards", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(InteractionsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

                                                SQLiteDatabase sqLiteDatabase = new InteractionsSQLiteHelper(
                                                        mContext).getWritableDatabase();

                                                sqLiteDatabase.delete(InteractionsSQLiteHelper.TABLE,
                                                        InteractionsSQLiteHelper.COLUMN_STRING + " = "
                                                                + mTools.sqe(searchString) + " COLLATE NOCASE",
                                                        null);
                                                sqLiteDatabase.insert(InteractionsSQLiteHelper.TABLE, null,
                                                        contentValues);

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(getString(R.string.interactions_cards_search)
                                                        + ": \"" + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoInteractionsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("InteractionsCards", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("InteractionsCards", error.toString());
                    }
                });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("InteractionsCards", Log.getStackTraceString(e));
    }
}

From source file:org.chromium.ChromeBluetooth.java

private void getDevices(CallbackContext callbackContext) throws JSONException {
    JSONArray results = new JSONArray();

    for (BluetoothDevice device : knownBluetoothDevices.values()) {
        results.put(getBasicDeviceInfo(device));
    }/*from ww  w.j  a  va2s.co m*/

    for (ScanResult result : knownLeScanResults.values()) {
        results.put(getLeDeviceInfo(result));
    }

    callbackContext.success(results);
}

From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java

public void pubEvent(Channel ch, JSONObject e, FullHttpResponse resp) {
    // Prepare the HTTP request.
    JSONArray es = new JSONArray();
    es.put(e);/*from  w  ww.  j av  a2  s.c o m*/

    StringWriter estr = new StringWriter();
    es.write(estr);
    String contentStr = estr.toString();
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/events",
            ch.alloc().buffer().writeBytes(contentStr.getBytes()));

    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");

    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder.encode(sessCookies));

    l.info("PUB Event request {}", request);

    // Send the HTTP request.
    ch.writeAndFlush(request);
}

From source file:com.insthub.ecmobile.model.MockServer.java

public static <K> void ajax(AjaxCallback<K> callback) {
    try {//from   w  w w  . j a  v  a2 s .com

        JSONObject responseJsonObject = new JSONObject();
        if (callback.getUrl() == ProtocolConst.HOMEDATA) {

            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONObject dataJsonObject = new JSONObject();
            JSONArray itemJsonArray = new JSONArray();
            for (int i = 0; i < 3; i++) {
                PLAYER player = new PLAYER();
                player.description = "";
                player.url = "www.baidu.com";
                player.photo = new PHOTO();

                player.photo.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                itemJsonArray.put(player.toJson());
            }

            dataJsonObject.put("player", itemJsonArray);

            JSONArray item2JsonArray = new JSONArray();
            for (int i = 0; i < 3; i++) {
                SIMPLEGOODS good = new SIMPLEGOODS();
                good.img = new PHOTO();
                good.img.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                item2JsonArray.put(good.toJson());
            }

            dataJsonObject.put("promote_goods", item2JsonArray);
            responseJsonObject.put("data", dataJsonObject);

        } else if (callback.getUrl() == ProtocolConst.CATEGORYGOODS) {
            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONArray dataJsonObject = new JSONArray();
            for (int i = 0; i < 3; i++) {
                CATEGORYGOODS good = new CATEGORYGOODS();

                for (int j = 0; j < 3; j++) {
                    SIMPLEGOODS simplegood = new SIMPLEGOODS();
                    simplegood.img = new PHOTO();

                    simplegood.img.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                    good.goods.add(simplegood);
                }
                good.name = "";
                dataJsonObject.put(good.toJson());
            }

            responseJsonObject.put("data", dataJsonObject);

        } else if (callback.getUrl() == ProtocolConst.SEARCH) {
            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONArray dataJsonObject = new JSONArray();

            for (int j = 0; j < 3; j++) {
                SIMPLEGOODS simplegood = new SIMPLEGOODS();
                simplegood.img = new PHOTO();

                simplegood.img.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                dataJsonObject.put(simplegood.toJson());
            }

            responseJsonObject.put("data", dataJsonObject);
        } else if (callback.getUrl() == ProtocolConst.SHOPHELP) {
            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONArray dataJsonObject = new JSONArray();

            for (int i = 0; i < 3; i++) {
                SHOPHELP shophelp = new SHOPHELP();
                shophelp.name = "??";
                for (int j = 0; j < 3; j++) {
                    ARTICLE article = new ARTICLE();
                    article.short_title = "";
                    article.id = j + "";
                    article.title = "";
                    shophelp.article.add(article);
                }
                dataJsonObject.put(shophelp.toJson());
            }

            responseJsonObject.put("data", dataJsonObject);
        } else if (callback.getUrl() == ProtocolConst.GOODSDETAIL) {
            STATUS status = new STATUS();
            status.succeed = 1;
            status.error_code = 0;
            status.error_desc = "";
            responseJsonObject.put("status", status.toJson());

            JSONObject dataJsonObject = new JSONObject();
            GOODS goods = new GOODS();

            for (int i = 0; i < 5; i++) {
                PHOTO photo = new PHOTO();
                photo.url = "http://cache.miyoo.cn/attach/13/42157/1/6054/193729.jpg";
                goods.pictures.add(photo);
            }
            responseJsonObject.put("data", goods.toJson());

        }

        ((BeeCallback) callback).callback(callback.getUrl(), responseJsonObject, callback.getStatus());

    } catch (JSONException e) {
        // TODO: handle exception
    }
}

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

public void onPostSignIn(TwitterUser user, String oAuthToken, String oAuthSecret,
        SocialNetConstant.Type oSocialNetType) {

    if (user != null) {

        try {// w  w  w .  j  av a  2  s .co  m

            final Editor edit = mPreferences.edit();
            String userIdAsString = Long.toString(user.getId());

            AccountDescriptor account = new AccountDescriptor(this, user, oAuthToken, oAuthSecret,
                    oSocialNetType);
            edit.putString(getAccountDescriptorKey(user.getId()), account.toString());

            String accountIndices = mPreferences.getString(SHARED_PREFERENCES_KEY_ACCOUNT_INDICES, null);
            JSONArray jsonArray;

            if (accountIndices == null) {
                jsonArray = new JSONArray();
                jsonArray.put(0, user.getId());
                mAccounts.add(account);
            } else {
                jsonArray = new JSONArray(accountIndices);
                boolean exists = false;
                for (int i = 0; i < jsonArray.length(); i++) {
                    String c = jsonArray.getString(i);
                    if (c.compareTo(userIdAsString) == 0) {
                        exists = true;
                        mAccounts.set(i, account);
                        break;
                    }
                }

                if (exists == false) {
                    jsonArray.put(userIdAsString);
                    mAccounts.add(account);
                }
            }

            accountIndices = jsonArray.toString();
            edit.putString(SHARED_PREFERENCES_KEY_ACCOUNT_INDICES, accountIndices);

            edit.commit();

            setCurrentAccount(user.getId());

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

        updateTwitterAccountCount();
        if (TwitterManager.get().getSocialNetType() == oSocialNetType) {
            TwitterManager.get().setOAuthTokenWithSecret(oAuthToken, oAuthSecret, true);
        } else {
            TwitterManager.initModule(oSocialNetType,
                    oSocialNetType == SocialNetConstant.Type.Twitter ? ConsumerKeyConstants.TWITTER_CONSUMER_KEY
                            : ConsumerKeyConstants.APPDOTNET_CONSUMER_KEY,
                    oSocialNetType == SocialNetConstant.Type.Twitter
                            ? ConsumerKeyConstants.TWITTER_CONSUMER_SECRET
                            : ConsumerKeyConstants.APPDOTNET_CONSUMER_SECRET,
                    oAuthToken, oAuthSecret, getCurrentAccountKey(), mConnectionStatusCallbacks);
        }
    }
}

From source file:de.dakror.virtualhub.data.Catalog.java

public JSONObject getJSONObject() {
    try {//from   w w w  .  j a v  a 2 s . co m
        JSONObject o = new JSONObject();
        o.put("name", name);
        JSONArray sources = new JSONArray();
        for (File f : this.sources)
            sources.put(f.getPath().replace("\\", "/"));
        o.put("sources", sources);

        o.put("tags", tags.toArray(new String[] {}));

        return o;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:com.endofhope.neurasthenia.bayeux.BayeuxMessage.java

@Override
public String toString() {
    JSONObject jsonObject = null;//from ww  w  . j a v a2 s  . c  om
    try {
        if (type == BayeuxMessage.HANDSHAKE_REQ) {
            jsonObject = convertHandshakeReq();
        } else if (type == BayeuxMessage.HANDSHAKE_RESP) {
            jsonObject = convertHandshakeResp();
        } else if (type == BayeuxMessage.CONNECT_REQ) {
            jsonObject = convertConnectReq();
        } else if (type == BayeuxMessage.CONNECT_RESP) {
            jsonObject = convertConnectResp();
        } else if (type == BayeuxMessage.DISCONNECT_REQ) {
            jsonObject = convertDisconnectReq();
        } else if (type == BayeuxMessage.DISCONNECT_RESP) {
            jsonObject = convertDisconnectResp();
        } else if (type == BayeuxMessage.SUBSCRIBE_REQ) {
            jsonObject = convertSubscribeReq();
        } else if (type == BayeuxMessage.SUBSCRIBE_RESP) {
            jsonObject = convertSubscribeResp();
        } else if (type == BayeuxMessage.UNSUBSCRIBE_REQ) {
            jsonObject = convertUnsubscribeReq();
        } else if (type == BayeuxMessage.UNSUBSCRIBE_RESP) {
            jsonObject = convertUnsubscribeResp();
        } else if (type == BayeuxMessage.PUBLISH_REQ) {
            jsonObject = convertPublishReq();
        } else if (type == BayeuxMessage.PUBLISH_RESP) {
            jsonObject = convertPublishResp();
        } else if (type == BayeuxMessage.DELIVER_EVENT) {
            jsonObject = convertDeliverEvent();
        } else {
            throw new JSONException("Invalid BayeuxMessageType " + type);
        }
    } catch (JSONException e) {
        logger.log(Level.WARNING, "Invalid json", e);
    }
    JSONArray jsonArray = new JSONArray();
    jsonArray.put(jsonObject);
    String result = null;
    try {
        result = jsonArray.toString(4);
    } catch (JSONException e) {
        logger.log(Level.WARNING, "Invalid json array", e);
    }
    return result;
}