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:org.span.manager.ChangeSettingsActivity.java

private void updateView() {

    // user id/*from  w  w  w  .  java  2s  .  c  om*/
    EditTextPreference uidEditTextPref = (EditTextPreference) findPreference("uidpref");
    uidEditTextPref.setText(manetcfg.getUserId());

    // wifi group
    wifiGroupPref = (PreferenceGroup) findPreference("wifiprefs");
    boolean bluetoothOn = manetcfg.isUsingBluetooth();
    wifiGroupPref.setEnabled(!bluetoothOn);

    // wifi encryption algorithm
    WifiEncryptionAlgorithmEnum encAlgorithm = manetcfg.getWifiEncryptionAlgorithm();
    ListPreference wifiEncAlgorithmPref = (ListPreference) findPreference("encalgorithmpref");
    wifiEncAlgorithmPref.setEnabled(false); // TODO: disable until tested
    wifiEncAlgorithmPref.setEntries(WifiEncryptionAlgorithmEnum.descriptionValues());
    wifiEncAlgorithmPref.setEntryValues(WifiEncryptionAlgorithmEnum.stringValues());
    wifiEncAlgorithmPref.setValueIndex(encAlgorithm.ordinal());

    // wifi encryption setup method
    ListPreference wifiEncSetupMethodPref = (ListPreference) findPreference("encsetuppref");
    wifiEncSetupMethodPref.setEnabled(false); // TODO: disable until tested
    if (encAlgorithm == WifiEncryptionAlgorithmEnum.NONE) {
        wifiEncSetupMethodPref.setEnabled(false);
    } else {
        wifiEncSetupMethodPref.setEnabled(true);
        if (manetcfg.getWifiDriver().startsWith("softap")
                || manetcfg.getWifiDriver().equals(DeviceConfig.DRIVER_HOSTAP)) {
            if (wifiEncSetupMethodPref != null) {
                wifiGroupPref.removePreference(wifiEncSetupMethodPref);
            }
        } else {
            wifiEncSetupMethodPref.setEntries(WifiEncryptionSetupMethodEnum.descriptionValues());
            wifiEncSetupMethodPref.setEntryValues(WifiEncryptionSetupMethodEnum.stringValues());
            wifiEncSetupMethodPref.setValueIndex(manetcfg.getWifiEncryptionSetupMethod().ordinal());
        }
    }

    // wifi encryption password
    final EditTextPreference wifiEncPasswordEditTextPref = (EditTextPreference) findPreference("passwordpref");
    wifiEncPasswordEditTextPref.setEnabled(false); // TODO: disable until tested
    if (encAlgorithm == WifiEncryptionAlgorithmEnum.NONE) {
        wifiEncPasswordEditTextPref.setEnabled(false);
    } else {
        wifiEncPasswordEditTextPref.setEnabled(true);
        final int origTextColorWifiEncKey = wifiEncPasswordEditTextPref.getEditText().getCurrentTextColor();
        if (manetcfg.getWifiDriver().startsWith("softap")
                || manetcfg.getWifiDriver().equals(DeviceConfig.DRIVER_HOSTAP)) {
            Validation.setupWpaEncryptionValidators(wifiEncPasswordEditTextPref, origTextColorWifiEncKey);
        } else {
            Validation.setupWepEncryptionValidators(wifiEncPasswordEditTextPref, origTextColorWifiEncKey);
        }
        wifiEncPasswordEditTextPref.setText(manetcfg.getWifiEncryptionPassword());
    }

    // wifi SSID
    EditTextPreference wifiSsidEditTextPref = (EditTextPreference) findPreference("ssidpref");
    Validation.setupWifiSsidValidator(wifiSsidEditTextPref);
    wifiSsidEditTextPref.setText(manetcfg.getWifiSsid());

    // wifi channel
    ListPreference channelpref = (ListPreference) findPreference("channelpref");
    channelpref.setEnabled(false); // TODO: disable until tested
    String[] channelStrValues = WifiChannelEnum.stringValues();
    String[] channelDescValues = WifiChannelEnum.descriptionValues();
    // remove auto channel option if not supported by device
    if (!manetcfg.getWifiDriver().startsWith("softap")
            || !manetcfg.getWifiDriver().equals(DeviceConfig.DRIVER_HOSTAP)) {
        // auto channel option at first index
        String[] newChannelStrValues = new String[channelStrValues.length - 1];
        String[] newChannelDescValues = new String[channelStrValues.length - 1];
        for (int i = 1; i < channelStrValues.length; i++) {
            newChannelStrValues[i - 1] = channelStrValues[i];
            newChannelDescValues[i - 1] = channelDescValues[i];
        }
        channelpref.setEntries(newChannelDescValues);
        channelpref.setEntryValues(newChannelStrValues);
        WifiChannelEnum wifiChannel = manetcfg.getWifiChannel();
        if (wifiChannel == WifiChannelEnum.AUTO) {
            channelpref.setValueIndex(WifiChannelEnum.CHANNEL_1.ordinal() - 1);
        } else {
            channelpref.setValueIndex(wifiChannel.ordinal() - 1);
        }
    } else {
        channelpref.setEntries(channelDescValues);
        channelpref.setEntryValues(channelStrValues);
        channelpref.setValueIndex(manetcfg.getWifiChannel().ordinal());
    }

    // wifi transmit power
    ListPreference txpowerPreference = (ListPreference) findPreference("txpowerpref");
    if (!manetcfg.isTransmitPowerSupported()) { // DEBUG
        if (txpowerPreference != null) {
            wifiGroupPref.removePreference(txpowerPreference);
        }
    } else {
        txpowerPreference.setEntries(WifiTxpowerEnum.descriptionValues());
        txpowerPreference.setEntryValues(WifiTxpowerEnum.stringValues());
        txpowerPreference.setValueIndex(manetcfg.getWifiTxpower().ordinal());
    }

    // bluetooth group        
    // disable bluetooth adhoc if not supported by the kernel
    if (true) { // !manetcfg.isBluetoothSupported() // TODO: disable until tested
        PreferenceGroup btGroup = (PreferenceGroup) findPreference("btprefs");
        btGroup.setEnabled(false);
    }

    // bluetooth
    // NOTE: bluetooth dependencies are specified in the layout XML
    // CheckBoxPreference bluetoothCheckboxPref = (CheckBoxPreference)findPreference("bluetoothonpref");

    // bluetooth keep wifi
    CheckBoxPreference btKeepWifiCheckBoxPref = (CheckBoxPreference) findPreference("bluetoothkeepwifipref");
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.ECLAIR) {
        PreferenceGroup btGroup = (PreferenceGroup) findPreference("btprefs");
        if (btKeepWifiCheckBoxPref != null) {
            btGroup.removePreference(btKeepWifiCheckBoxPref);
        }
    } else {
        btKeepWifiCheckBoxPref.setChecked(!manetcfg.isWifiDisabledWhenUsingBluetooth());
    }

    // bluetooth discoverable
    CheckBoxPreference btdiscoverablePreference = (CheckBoxPreference) findPreference(
            "bluetoothdiscoverablepref");
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.ECLAIR) {
        PreferenceGroup btGroup = (PreferenceGroup) findPreference("btprefs");
        if (btdiscoverablePreference != null) {
            btGroup.removePreference(btdiscoverablePreference);
        }
    } else {
        btdiscoverablePreference.setChecked(manetcfg.isBluetoothDiscoverableWhenInAdhocMode());
    }

    // ip address
    EditTextPreference ipAddressEditTextPref = (EditTextPreference) findPreference("ippref");
    Validation.setupIpAddressValidator(ipAddressEditTextPref);
    ipAddressEditTextPref.setText(manetcfg.getIpAddress());

    // dns server
    EditTextPreference dnsServerEditTextPref = (EditTextPreference) findPreference("dnspref");
    Validation.setupIpAddressValidator(dnsServerEditTextPref);
    dnsServerEditTextPref.setText(manetcfg.getDnsServer());

    // routing protocol
    String currRoutingProtocol = manetcfg.getRoutingProtocol();
    List<String> routingProtocolList = CoreTask.getRoutingProtocols();
    String[] routingProtocols = new String[routingProtocolList.size()];
    routingProtocolList.toArray(routingProtocols);

    ListPreference routingProtocolPreference = (ListPreference) findPreference("routingprotocolpref");
    routingProtocolPreference.setEntries(routingProtocols);
    routingProtocolPreference.setEntryValues(routingProtocols);
    routingProtocolPreference.setValue(currRoutingProtocol);

    // routing ignore list
    JSONArray array = new JSONArray(manetcfg.getRoutingIgnoreList());
    sharedPreferences.edit().putString("ignorepref", array.toString()).commit();

    // wifi interface
    String currInterface = manetcfg.getWifiInterface();
    String defaultInterface = DeviceConfig.getWifiInterface(manetcfg.getDeviceType());
    List<String> interfaceList = CoreTask.getNetworkInterfaces();
    if (!interfaceList.contains(defaultInterface)) {
        interfaceList.add(defaultInterface);
    }
    String[] interfaces = new String[interfaceList.size()];
    interfaceList.toArray(interfaces);

    ListPreference interfacePreference = (ListPreference) findPreference("interfacepref");
    interfacePreference.setEntries(interfaces);
    interfacePreference.setEntryValues(interfaces);

    if (interfaceList.contains(currInterface)) {
        interfacePreference.setValue(currInterface);
    } else {
        interfacePreference.setValue(defaultInterface);
        currInterface = defaultInterface;
    }

    // routing gateway
    String currGatewayInterface = manetcfg.getGatewayInterface();
    interfaceList.remove(currInterface); // remove ad-hoc interface
    interfaceList.add(0, ManetConfig.GATEWAY_INTERFACE_NONE);
    interfaces = new String[interfaceList.size()];
    interfaceList.toArray(interfaces);

    ListPreference gatewayPreference = (ListPreference) findPreference("gatewaypref");
    gatewayPreference.setEntries(interfaces);
    gatewayPreference.setEntryValues(interfaces);
    gatewayPreference.setValue(currGatewayInterface);

    if (interfaceList.contains(currGatewayInterface)) {
        gatewayPreference.setValue(currGatewayInterface);
    } else {
        gatewayPreference.setValue(ManetConfig.GATEWAY_INTERFACE_NONE);
    }

    // screen on
    CheckBoxPreference screenOnPreference = (CheckBoxPreference) findPreference("screenonpref");
    screenOnPreference.setChecked(manetcfg.isScreenOnWhenInAdhocMode());

    // battery temperature

    setupFlag = true;
}

From source file:com.google.testing.testify.risk.frontend.server.api.impl.UploadApiImpl.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    BufferedReader reader = req.getReader();
    StringBuilder input = new StringBuilder();
    while (reader.ready()) {
        input.append(req.getReader().readLine());
    }// www  .  j  a v  a  2 s .  co  m
    LOG.info("Input received: " + input.toString());
    JSONArray json;
    try {
        json = new JSONArray(input.toString());
    } catch (JSONException e) {
        LOG.warning("Couldn't parse JSON: " + e.toString());
        error(resp, "Malformed JSON could not be parsed: " + e.toString());
        return;
    }
    LOG.info("JSON received: " + json.toString());
    JSONObject o;
    TaskOptions task;
    String email = userService.getEmail();
    for (int i = 0; i < json.length(); i++) {
        try {
            o = json.getJSONObject(i);
            task = TaskOptions.Builder.withUrl(UploadDataTask.URL).method(Method.POST)
                    .param("json", o.toString()).param("user", email);
            ServletUtils.queueWithRetries(UploadDataTask.QUEUE, task, "Processing data item upload");
        } catch (JSONException e) {
            LOG.warning("Couldn't parse item " + i + " in JSON array: " + e.toString());
            resp.getOutputStream().print("<p>Couldn't parse item " + i + "</p>\n");
        }
    }
}

From source file:com.app.swaedes.swaedes.MapPage.java

public void getJsonMarkers() {

    JsonArrayRequest getMarkers = new JsonArrayRequest(Config.GET_MARKERS, new Response.Listener<JSONArray>() {
        @Override//from   www .ja  v  a2s  .co  m
        public void onResponse(JSONArray response) {
            Log.d("TAG", response.toString());

            try {

                for (int i = 0; i < response.length(); i++) {

                    JSONObject marker = (JSONObject) response.get(i);
                    String name = marker.getString("name");
                    Double latitude = marker.getDouble("lat");
                    Double longitude = marker.getDouble("lng");
                    markersList.add(new OverlayItem(name, name, new GeoPoint(latitude, longitude)));
                    Log.d("TAG", marker.toString());
                }

                ItemizedIconOverlay<OverlayItem> mapMarkersOverlay = new ItemizedIconOverlay<>(
                        getApplicationContext(), markersList, null);
                mapView.getOverlays().add(mapMarkersOverlay);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MapPage.this, error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    //Getting the request queue of the app, add the request to it
    Swaedes swaedes = (Swaedes) getApplication();
    RequestQueue mVolleyRequestQueue = swaedes.getVolleyRequestQueue();
    mVolleyRequestQueue.add(getMarkers);

}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

private void addGeofences(CallbackContext callbackContext, JSONArray geofences) {

    final Bundle event = new Bundle();
    event.putString("name", BackgroundGeolocationService.ACTION_ADD_GEOFENCES);
    event.putBoolean("request", true);

    event.putString("geofences", geofences.toString());
    addGeofenceCallbacks.put(BackgroundGeolocationService.ACTION_ADD_GEOFENCES, callbackContext);

    postEvent(event);//from w ww  . j a  v a2s.  c  o m
}

From source file:org.droidparts.net.http.RESTClient2.java

public HTTPResponse put(String uri, JSONArray data) throws HTTPException {
    return put(uri, ContentType.APPLICATION_JSON, data.toString());
}

From source file:org.droidparts.net.http.RESTClient2.java

public HTTPResponse post(String uri, JSONArray data) throws HTTPException {
    return post(uri, ContentType.APPLICATION_JSON, data.toString());
}

From source file:org.lafs.hdfs.LAFS.java

private FileStatus getStatusFromJSON(JSONArray ja, Path path) throws IOException {
    FileStatus stat;/* ww  w  .jav a 2 s.com*/

    String flag;
    try {
        flag = ja.getString(0);

        boolean isDir = flag.equals("dirnode");

        JSONObject data = ja.getJSONObject(1);

        long mtime = 0L;
        if (data.has("metadata"))
            mtime = (long) data.getJSONObject("metadata").getJSONObject("tahoe").getDouble("linkmotime");

        // each file consists of 1 block of a size the entire length of the file

        long size = 0L;

        if (!isDir) {
            try {
                size = (long) data.getInt("size");
            } catch (JSONException joe) {
                logger.warning("size was null");
            }
        }
        //else 
        //   size = data.getJSONObject("children").length();

        stat = new FileStatus(isDir ? 0 : size, isDir, 1, size, mtime, path);
    } catch (JSONException e) {
        logger.severe(ja.toString());
        throw new IOException(e.getMessage());
    }

    return stat;
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffWriter.java

private void writeDisplaySettings() throws IOException {
    JSONArray displaySettings;
    try {/*  www  .  ja  v  a  2s  .  c o m*/
        displaySettings = masterMPTiffStorage_.getDisplayAndComments().getJSONArray("Channels");
    } catch (JSONException ex) {
        displaySettings = new JSONArray();
    }
    int numReservedBytes = numChannels_ * DISPLAY_SETTINGS_BYTES_PER_CHANNEL;
    ByteBuffer header = ByteBuffer.allocate(8).order(BYTE_ORDER);
    ByteBuffer buffer = ByteBuffer.wrap(getBytesFromString(displaySettings.toString()));
    header.putInt(0, DISPLAY_SETTINGS_HEADER);
    header.putInt(4, numReservedBytes);
    fileChannel_.write(header, filePosition_);
    fileChannel_.write(buffer, filePosition_ + 8);

    ByteBuffer offsetHeader = ByteBuffer.allocate(8).order(BYTE_ORDER);
    offsetHeader.putInt(0, DISPLAY_SETTINGS_OFFSET_HEADER);
    offsetHeader.putInt(4, (int) filePosition_);
    fileChannel_.write(offsetHeader, 16);
    filePosition_ += numReservedBytes + 8;
}

From source file:org.apps8os.contextlogger3.android.clientframework.ActivityRecognitionService.java

private void handleActivityRecognitionResult(final ActivityRecognitionResult result) {
    Bundle data = new Bundle();
    // Get the most probable activity
    DetectedActivity mostProbableActivity = result.getMostProbableActivity();
    String activityName = ActivityType.getActivityTypeByReference(mostProbableActivity.getType());
    data.putString("Activity", activityName);
    data.putString("ActivityConfidence", String.valueOf(mostProbableActivity.getConfidence()));
    try {//from  w w  w.jav a2s. c  o m
        List<DetectedActivity> daList = result.getProbableActivities();
        if ((daList != null) && (!daList.isEmpty())) {
            JSONArray jsonArray = new JSONArray();
            for (DetectedActivity da : daList) {
                JSONObject daObject = new JSONObject();
                daObject.put("Activity", ActivityType.getActivityTypeByReference(da.getType()));
                daObject.put("ActivityConfidence", String.valueOf(da.getConfidence()));
                jsonArray.put(daObject);
            }
            if (jsonArray.length() > 0) {
                data.putString("ProbableActivities", jsonArray.toString());
            }
        }

    } catch (Exception e) {
        Log.e(ActivityRecognitionService.class.getCanonicalName(), "error: ", e);
        String probableActivities = TextUtils.join("|", result.getProbableActivities());
        data.putString("ProbableActivities", probableActivities);
    }
    data.putString("timestamp", String.valueOf(result.getTime()));
    Intent intent = new Intent(GoogleActivityRecognitionProbe.INTENT_ACTION);
    intent.putExtras(data);
    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}

From source file:net.qiujuer.common.okhttp.impl.RequestCallBuilder.java

@Override
public Request.Builder builderPost(String url, JSONArray jsonArray) {
    RequestBody body = RequestBody.create(
            MediaType.parse(String.format("application/json; charset=%s", mProtocolCharset)),
            jsonArray.toString());

    return builderPost(url, body);
}