Example usage for org.json JSONArray toString

List of usage examples for org.json JSONArray toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONArray.

Usage

From source file:de.joinout.criztovyl.tools.json.JSONFile.java

public JSONFile setData(JSONArray json) {
    data = json.toString();

    return this;
}

From source file:com.ss.android.apker.volley.toolbox.JsonArrayRequest.java

/**
 * Creates a new request./*from w  ww  .j av  a  2  s . c  om*/
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonArrayRequest(Context context, int method, String url, JSONArray jsonRequest,
        Listener<JSONArray> listener, ErrorListener errorListener) {
    super(context, method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}

From source file:org.jboss.aerogear.cordova.push.PushPlugin.java

@Override
public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) {
    Log.v(TAG, "execute: action=" + action);
    foreground = true;/*from   ww w  .j av  a 2s  .  co m*/

    if (REGISTER.equals(action)) {
        Log.v(TAG, "execute: data=" + data.toString());

        try {
            context = callbackContext;

            JSONObject pushConfig = parseConfig(data);
            saveConfig(pushConfig);
            cordova.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    register(callbackContext);
                }
            });
        } catch (JSONException e) {
            callbackContext.error(e.getMessage());
            return false;
        }

        if (cachedMessage != null) {
            Log.v(TAG, "sending cached extras");
            sendMessage(cachedMessage);
            cachedMessage = null;
        }

        return true;
    } else if (UNREGISTER.equals(action)) {

        unRegister(callbackContext);
        return true;
    } else {
        callbackContext.error("Invalid action : " + action);
    }

    return false;
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPush.java

/**
 * Get the list of tags/*from   w  w  w  . j  ava 2  s.co  m*/
 *
 * @param listener Mandatory listener class. When the list of tags are
 *                 successfully retrieved the {@link MFPPushResponseListener}
 *                 .onSuccess method is called with the list of tagNames
 *                 {@link MFPPushResponseListener}.onFailure method is called
 *                 otherwise
 */
public void getTags(final MFPPushResponseListener<List<String>> listener) {
    MFPPushUrlBuilder builder = new MFPPushUrlBuilder(applicationId);
    String path = builder.getTagsUrl();
    MFPPushInvoker invoker = MFPPushInvoker.newInstance(appContext, path, Request.GET, clientSecret);

    invoker.setResponseListener(new ResponseListener() {

        @Override
        public void onSuccess(Response response) {
            logger.info("MFPPush:getTags() - Successfully retreived tags.  The response is: "
                    + response.toString());
            List<String> tagNames = new ArrayList<String>();
            try {
                String responseText = response.getResponseText();
                JSONArray tags = (JSONArray) (new JSONObject(responseText)).get(TAGS);
                Log.d("JSONArray of tags is: ", tags.toString());
                int tagsCnt = tags.length();
                for (int tagsIdx = 0; tagsIdx < tagsCnt; tagsIdx++) {
                    Log.d("Adding tag: ", tags.getJSONObject(tagsIdx).toString());
                    tagNames.add(tags.getJSONObject(tagsIdx).getString(NAME));
                }
                listener.onSuccess(tagNames);
            } catch (JSONException e) {
                logger.error("MFPPush: getTags() - Error while retrieving tags.  Error is: " + e.getMessage());
                listener.onFailure(new MFPPushException(e));
            }
        }

        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
            //Error while subscribing to tags.
            errorString = null;
            statusCode = 0;
            if (response != null) {
                errorString = response.getResponseText();
                statusCode = response.getStatus();
            } else if (errorString == null && throwable != null) {
                errorString = throwable.toString();
            } else if (errorString == null && jsonObject != null) {
                errorString = jsonObject.toString();
            }
            listener.onFailure(new MFPPushException(errorString, statusCode));
        }
    });
    invoker.execute();
}

From source file:com.imos.sample.pi.MotionSensor.java

public void pythonTemperatureSensor() {

    try {/*from w w  w .j  a  v  a 2s  . c om*/
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (!result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, null, "");
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                try (BufferedWriter writer = new BufferedWriter(
                        new FileWriter(builder.toString() + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("src/main/resources/" + dirName);
                    newDir.mkdir();

                    File files = new File("src/main/resources/");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("src/main/resources/" + dirName + file.getName()));
                            file.delete();
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(MotionSensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.neomatrix369.examples.twitter.TweetsDataStorageTest.java

@Test
public void shouldBeAbleToWriteAndReadBackMessages() throws JSONException {
    String arrayPartOfTweetAsString = "[{'from_user_name':'someUser', 'from_user_id':'?@someonesTwitterHandle', 'text':'Body of the twitter message #hashtag1 #hashtag2 #hashtag3'}]";
    final String tweetMessageWrittenAsString = "{results: " + arrayPartOfTweetAsString + "}";
    storage.saveTweetMessage(tweetMessageWrittenAsString);

    final JSONArray tweetMessageRead = storage.loadTweetMessage();

    final JSONArray tweetMessageWrittenAsArray = new JSONArray(arrayPartOfTweetAsString);
    assertThat(READ_WRITE_MISMATCH_ERROR_MESSAGE, tweetMessageRead.toString(),
            is(tweetMessageWrittenAsArray.toString()));
}

From source file:ch.ethz.inf.vs.android.g54.a4.util.SnapshotCache.java

public static void storeSnapshot(List<WifiReading> readings, String fileName, Context c) {

    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the external storage
        try {/*from  w  w w  . j  a v a  2 s.c om*/
            JSONArray json = readingsToJson(readings);
            File root = c.getExternalCacheDir();
            File jsonFile = new File(root, constructFileName(fileName));
            FileOutputStream out;
            out = new FileOutputStream(jsonFile);
            out.write(json.toString().getBytes());
            out.close();
            U.showToast(constructFileName(fileName));
            Log.d(TAG, "Successfully stored snapshot to SDCard");
        } catch (Exception e) {
            U.showToast("Could not save the snapshot on the SDCard.");
            Log.e(TAG, "Could not save the snapshot on the SDCard.", e);
        }
    } else {
        U.showToast("Cannot write to external storage.");
    }
}

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

public void removeAccount(String accountKey) {
    final Editor edit = mPreferences.edit();
    String accountIndices = mPreferences.getString(SharedPreferencesConstants.ACCOUNT_INDICES, null);
    if (accountIndices != null) {
        try {/*from w  ww.  ja v  a2s.c o m*/
            JSONArray jsonArray = new JSONArray(accountIndices);
            JSONArray newIndicies = new JSONArray();
            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 (!account.getAccountKey().equals(accountKey)) {
                        newIndicies.put(Long.toString(id));
                    } else {
                        ArrayList<LaneDescriptor> lanes = account.getAllLaneDefinitions();
                        for (LaneDescriptor lane : lanes) {
                            String lanekey = lane.getCacheKey(account.getScreenName() + account.getId());
                            edit.remove(lanekey);
                        }

                        edit.remove(key);
                        mAccounts.remove(account);
                    }
                }
            }

            accountIndices = newIndicies.toString();
            edit.putString(SharedPreferencesConstants.ACCOUNT_INDICES, accountIndices);

            edit.commit();

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

    updateTwitterAccountCount();
}

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

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

    if (user != null) {

        try {/*from  w ww.j  a  va  2s .c o  m*/

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

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

            String accountIndices = mPreferences.getString(SharedPreferencesConstants.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) {
                    jsonArray.put(userIdAsString);
                    mAccounts.add(account);
                }
            }

            accountIndices = jsonArray.toString();
            edit.putString(SharedPreferencesConstants.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:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * @param response {@link CloseableHttpResponse}
 * @return null if response is invalid. Json as string, if it is a valid response.
 * @throws MLHttpClientException/* w w  w .  j  a  v  a 2 s.  c  om*/
 */
public String getResponseAsString(CloseableHttpResponse response) throws MLHttpClientException {
    if (response == null || response.getEntity() == null) {
        return null;
    }
    String reply = null;
    try {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        String line = bufferedReader.readLine();
        try {
            JSONObject responseJson = new JSONObject(line);
            reply = responseJson.toString();
        } catch (JSONException e) {
            JSONArray responseArray = new JSONArray(line);
            reply = responseArray.toString();
        }
        bufferedReader.close();
        response.close();
        return reply;
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to extract the response body.", e);
    }
}