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(Object array) throws JSONException 

Source Link

Document

Construct a JSONArray from an array

Usage

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;/* w  ww . j a v a 2  s. c o  m*/
    }

    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:org.wso2.carbon.connector.clevertim.CreateCase.java

/**
 * Create JSON request for CreateCase.// w w w  .j a  va2  s.c o m
 *
 * @return JSON payload.
 * @throws JSONException thrown when parsing JSON String.
 */
private String getJsonPayload() throws JSONException {

    JSONObject jsonPayload = new JSONObject();

    String name = (String) messageContext.getProperty(Constants.NAME);
    if (name != null && !name.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.NAME, name);
    }
    String description = (String) messageContext.getProperty(Constants.DESCRIPTION);
    if (description != null && !description.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.DESCRIPTION, description);
    }
    String tags = (String) messageContext.getProperty(Constants.TAGS);
    if (tags != null && !tags.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.TAGS, new JSONArray(tags));
    }
    String leadUser = (String) messageContext.getProperty(Constants.LEAD_USER);
    if (leadUser != null && !leadUser.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.LEAD_USER, leadUser);
    }
    String customer = (String) messageContext.getProperty(Constants.CUSTOMER);
    if (customer != null && !customer.isEmpty()) {
        jsonPayload.put(Constants.JSONKeys.CUSTOMER, customer);
    }
    String customFields = (String) messageContext.getProperty(Constants.CUSTOM_FIELDS);
    if (customFields != null && !customFields.isEmpty()) {

        jsonPayload.put(Constants.JSONKeys.CUSTOM_FIELD, new JSONObject(customFields));
    }

    return jsonPayload.toString();

}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFiles() {
    URL urlO = null;/*w w  w  . ja va 2 s  . c o  m*/
    try {
        urlO = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(fileJson.get("_id").toString());

                if (file == null) {
                    file = new File(fileJson, false);
                } else {
                    file.setName(fileJson.getString("name"));
                    file.setPath(fileJson.getString("path"));
                    file.setCreationDate(fileJson.getString("creationDate"));
                    file.setLastModification(fileJson.getString("lastModification"));
                    file.setTags(fileJson.getString("tags"));

                    if (fileJson.has("binary")) {
                        file.setBinary(fileJson.getJSONObject("binary").toString());
                    }

                    file.setIsFile(true);
                    file.setFileClass(fileJson.getString("class"));
                    file.setMimeType(fileJson.getString("mime"));
                    file.setSize(fileJson.getLong("size"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing file : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName()));

                file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory()
                        + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files"
                        + file.getPath() + "/" + file.getName()));
                file.save();

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault()
                    .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error")));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFolders() {
    //File.deleteAllFolders();

    URL urlO = null;/*from w ww  .  j a  v a 2s.  c om*/
    try {
        urlO = new URL(folderUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject folderJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(folderJson.get("_id").toString());

                if (file == null) {
                    file = new File(folderJson, true);
                } else {
                    file.setName(folderJson.getString("name"));
                    file.setPath(folderJson.getString("path"));
                    file.setCreationDate(folderJson.getString("creationDate"));
                    file.setLastModification(folderJson.getString("lastModification"));
                    file.setTags(folderJson.getString("tags"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing remote folder : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName()));

                file.save();
                createFolder(file.getPath(), file.getName());

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:org.hydracache.client.partition.PartitionAwareClient.java

@Override
public synchronized List<Identity> listNodes() throws Exception {
    log.info("Retrieving list of nodes.");

    RequestMessage requestMessage = new RequestMessage();
    requestMessage.setMethod(GET);// ww  w.  j  a va  2s  .c o m
    requestMessage.setPath("registry");

    // Pick a random node to connect to
    Random rnd = new Random();
    int nextInt = rnd.nextInt(seedServerIds.size());
    Identity identity = seedServerIds.get(nextInt);

    ResponseMessage responseMessage = messager.sendMessage(identity, nodePartition, requestMessage);

    if (responseMessage == null)
        throw new ClientException("Failed to retrieve node registry.");

    List<Identity> identities = new LinkedList<Identity>();

    String registry = new String(responseMessage.getResponseBody());
    log.debug("Received registry: " + registry);
    JSONArray seedServerArray = new JSONArray(registry);
    for (int i = 0; i < seedServerArray.length(); i++) {
        JSONObject seedServer = seedServerArray.getJSONObject(i);

        identities.add(new Identity(InetAddress.getByName(seedServer.getString(IP)), seedServer.getInt(PORT)));
    }
    return identities;
}

From source file:com.endiansoftware.echo.remotewatch.MainActivity.java

public void callback(String response) {
    StringBuffer sb = new StringBuffer();
    try {// w  w  w  . j a v  a2  s  .c  om
        // "kkt_list"   ? JSON ?
        JSONArray Array = new JSONArray(response);
        for (int i = 0; i < Array.length(); i++) {
            // bodylist ?  JSON ? JSON  ? ?
            JSONObject insideObject = Array.getJSONObject(i);

            sb.append(insideObject.getString("m_Key")).append(" : ").append(insideObject.getString("m_Value"))
                    .append("\n");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    mDisplay.setText(sb.toString());
}

From source file:com.guipenedo.pokeradar.activities.settings.PokemonFilterSettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getDelegate().installViewFactory();/*  www . ja  va 2 s  .co m*/
    getDelegate().onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);
    PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(this);
    PreferenceCategory category = new PreferenceCategory(this);
    category.setTitle(R.string.filter_pokemons);
    screen.addPreference(category);
    try {
        JSONArray pokemonList = new JSONArray(Utils.loadJSONFromFile(this, "pokemon.json"));
        for (int i = 0; i < pokemonList.length(); i++) {
            JSONObject pokemon = pokemonList.getJSONObject(i);
            CheckBoxPreference checkBox = new CheckBoxPreference(this);
            checkBox.setTitle(pokemon.getString("Name"));
            checkBox.setIcon(new BitmapDrawable(getResources(),
                    Utils.bitmapForPokemon(this, Integer.parseInt(pokemon.getString("Number")))));
            checkBox.setDefaultValue(true);
            checkBox.setSummary(String.format(getString(R.string.setting_filter_pokemon_summary),
                    pokemon.getString("Name")));
            checkBox.setKey("pref_key_show_pokemon_" + Integer.parseInt(pokemon.getString("Number")));
            category.addPreference(checkBox);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    setPreferenceScreen(screen);
}

From source file:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * Uses Bluemix Mobile Services SDK to GET the TodoItems from Bluemix and updates the local list.
 *///from   ww w. ja  v  a  2  s . com
private void loadList() {

    // Send GET Request to Bluemix backend to retreive item list with response listener
    Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.GET);
    request.send(getApplicationContext(), new ResponseListener() {
        // Loop through JSON response and create local TodoItems if successful
        @Override
        public void onSuccess(Response response) {
            if (response.getStatus() != 200) {
                Log.e(TAG, "Error pulling items from Bluemix: " + response.toString());
            } else {

                try {

                    mTodoItemList.clear();

                    JSONArray jsonArray = new JSONArray(response.getResponseText());

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject tempTodoJSON = jsonArray.getJSONObject(i);
                        TodoItem tempTodo = new TodoItem();

                        tempTodo.idNumber = tempTodoJSON.getInt("id");
                        tempTodo.text = tempTodoJSON.getString("text");
                        tempTodo.isDone = tempTodoJSON.getBoolean("isDone");

                        mTodoItemList.add(tempTodo);
                    }

                    // Need to notify adapter on main thread in order for list changes to update visually
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTodoItemAdapter.notifyDataSetChanged();

                            Log.i(TAG, "List updated successfully");

                            if (mSwipeLayout.isRefreshing()) {
                                mSwipeLayout.setRefreshing(false);
                            }
                        }
                    });

                } catch (Exception exception) {
                    Log.e(TAG, "Error reading response JSON: " + exception.getLocalizedMessage());
                }
            }
        }

        // Log Errors on failure
        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {
            String errorMessage = "";

            if (response != null) {
                errorMessage += response.toString() + "\n";
            }

            if (throwable != null) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                errorMessage += "THROWN" + sw.toString() + "\n";
            }

            if (extendedInfo != null) {
                errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
            }

            if (errorMessage.isEmpty())
                errorMessage = "Request Failed With Unknown Error.";

            Log.e(TAG, "loadList failed with error: " + errorMessage);
        }
    });

}

From source file:com.polyvi.xface.view.XWebChromeClient.java

@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
        JsPromptResult result) {/*from   w w  w  .  j  a v a 2s .co  m*/
    boolean reqOk = false;
    if (url.startsWith("file://") || Config.isUrlWhiteListed(url)) {
        reqOk = true;
    }
    if (reqOk && defaultValue != null && defaultValue.equals("xFace_close_application:")) {
        XAppWebView appView = ((XAppWebView) view);
        int viewId = appView.getViewId();
        XEvent evt = XEvent.createEvent(XEventType.CLOSE_APP, viewId);
        ((XFaceMainActivity) mInterface.getActivity()).getEventCenter().sendEventSync(evt);
        result.confirm("");
        return true;
    } else if (reqOk && defaultValue != null && defaultValue.equals("xFace_app_send_message:")) {
        try {
            JSONArray args = new JSONArray(message);
            Pair<XAppWebView, String> appMessage = new Pair<XAppWebView, String>((XAppWebView) view,
                    args.getString(0));
            XEvent evt = XEvent.createEvent(XEventType.XAPP_MESSAGE, appMessage);
            ((XFaceMainActivity) mInterface.getActivity()).getEventCenter().sendEventSync(evt);
        } catch (JSONException e) {
            XLog.e(CLASS_NAME, "");
            XLog.e(CLASS_NAME, e.getMessage());
        }
        result.confirm("");
        return true;
    }
    return super.onJsPrompt(view, url, message, defaultValue, result);
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static JSONObject makeResponseJSONObject(String data) {

    JSONArray product = null;/* w w  w.  j a v  a 2s  .  c  o  m*/
    JSONObject ret = null;
    try {
        product = new JSONArray(data);
        ret = (JSONObject) product.get(0);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return ret;
}