Java Code Examples for org.json.JSONArray#getString()

The following examples show how to use org.json.JSONArray#getString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SendingTask.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
@Override
public void execute(JSONArray args, CallbackContext ctx) {
    try {
        int id = args.getInt(0);
        String data = args.getString(1);
        boolean binaryString = args.getBoolean(2);
        Connection conn = _map.get(id);

        if (conn != null) {
            if (binaryString) {
                byte[] binary = Base64.decode(data, Base64.NO_WRAP);
                conn.sendMessage(binary, 0, binary.length);
            } else {
                conn.sendMessage(data);
            }
        }
    } catch (Exception e) {
        ctx.error("send");
    }
}
 
Example 2
Source File: TestBase.java    From blue-marlin with Apache License 2.0 6 votes vote down vote up
protected Integer getTBRCount(TargetingChannel tc, boolean matchSingleValues)
        throws FileNotFoundException, JSONException, IllegalAccessException
{
    Integer totalCount = 0;
    boolean matchedTbrDoc = false;
    File[] files = getFiles("docs/tbr");
    ObjectMapper objectMapper = new ObjectMapper();

    for (File file : files)
    {
        String content = readFile(file);
        JSONObject tbrDoc = new JSONObject(content);
        matchedTbrDoc = matchTBR(tc, file, matchSingleValues);
        JSONArray key = ((JSONObject) tbrDoc.get("days")).names();
        if (matchedTbrDoc == true)
        {
            for (int i = 0; i < key.length(); ++i)
            {
                String keys = key.getString(i);
                totalCount += (Integer) ((JSONObject) tbrDoc.get("days")).get(keys);
            }
        }
    }
    return totalCount;
}
 
Example 3
Source File: AddressDialog.java    From AndroidProject with Apache License 2.0 6 votes vote down vote up
/**
 * 获取区域列表
 *
 * @param jsonObject        区域 Json
 */
private static List<AddressBean> getAreaList(JSONObject jsonObject) {
    try {
        JSONArray listArea = jsonObject.getJSONArray("area");
        int length = listArea.length();

        ArrayList<AddressBean> list = new ArrayList<>(length);

        for (int i = 0; i < length; i++) {
            String string = listArea.getString(i);
            list.add(new AddressBean(string, null));
        }
        return list;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 4
Source File: ServiceDiscoveryResult.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
private static Data createFormFromJSONObject(JSONObject o) {
    Data data = new Data();
    JSONArray names = o.names();
    for (int i = 0; i < names.length(); ++i) {
        try {
            String name = names.getString(i);
            JSONArray jsonValues = o.getJSONArray(name);
            ArrayList<String> values = new ArrayList<>(jsonValues.length());
            for (int j = 0; j < jsonValues.length(); ++j) {
                values.add(jsonValues.getString(j));
            }
            data.put(name, values);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return data;
}
 
Example 5
Source File: UmbelSearchConcept.java    From wandora with GNU General Public License v3.0 6 votes vote down vote up
private ArrayList<String> getAsStringArray(Object o) throws JSONException {
    ArrayList<String> array = new ArrayList();
    if(o != null) {
        if(o instanceof String) {
            array.add(o.toString());
        }
        else if(o instanceof JSONArray) {
            JSONArray a = (JSONArray) o;
            for(int i=0; i<a.length(); i++) {
                String typeUri = a.getString(i);
                array.add(typeUri);
            }
        }
    }
    return array;
}
 
Example 6
Source File: CountlyNative.java    From countly-sdk-cordova with MIT License 6 votes vote down vote up
public String updateRemoteConfigForKeysOnly(JSONArray args, final Callback theCallback){
    try {
        this.log("updateRemoteConfigForKeysOnly", args);
        String[] keysOnly = new String[args.length()];
        for (int i = 0, il = args.length(); i < il; i++) {
            keysOnly[i] = args.getString(i);
            ;
        }
        Countly.sharedInstance().remoteConfig().updateForKeysOnly(keysOnly, new RemoteConfigCallback() {
            @Override
            public void callback(String error) {
                if (error == null) {
                    theCallback.callback("Success");
                } else {
                    theCallback.callback("Error: " + error.toString());
                }
            }
        });
        return "updateRemoteConfigForKeysOnly: success";
    }catch (JSONException jsonException){
        return jsonException.toString();
    }
}
 
Example 7
Source File: EaseAtMessageHelper.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
public boolean isAtMeMsg(EMMessage message){
    EaseUser user = EaseUserUtils.getUserInfo(message.getFrom());
    if(user != null){
        try {
            JSONArray jsonArray = message.getJSONArrayAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG);
            
            for(int i = 0; i < jsonArray.length(); i++){
                String username = jsonArray.getString(i);
                if(username.equals(EMClient.getInstance().getCurrentUser())){
                    return true;
                }
            }
        } catch (Exception e) {
            //perhaps is a @ all message
            String atUsername = message.getStringAttribute(EaseConstant.MESSAGE_ATTR_AT_MSG, null);
            if(atUsername != null){
                if(atUsername.toUpperCase().equals(EaseConstant.MESSAGE_ATTR_VALUE_AT_MSG_ALL)){
                    return true;
                }
            }
            return  false;
        }
        
    }
    return false;
}
 
Example 8
Source File: SpellCheckDecisionManagerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private long getCollationHit2(JSONObject resultJson) throws JSONException
{
    JSONObject spellcheck = resultJson.getJSONObject("spellcheck");
    JSONArray collations = spellcheck.getJSONArray("collations");

    for (int key = 0, value = 1, length = collations.length(); value < length; key += 2, value += 2)
    {
        String jsonName = collations.getString(key);

        if ("collation".equals(jsonName))
        {
            JSONObject valueJsonObject = collations.getJSONObject(value);
            long collationHit = valueJsonObject.getLong("hits");
            return collationHit;
        }
    }

    return 0;
}
 
Example 9
Source File: MessageManager.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getValidLang(String _value) {
	JSONArray names = langs.names();
	for (int i = 0; i < names.length(); i++) {
		if (_value.equalsIgnoreCase(names.getString(i)))
			return names.getString(i);
	}
	return "ENGLISH";
}
 
Example 10
Source File: BluetoothPlugin.java    From phonegap-bluetooth-plugin with MIT License 5 votes vote down vote up
/**
 * See if the device is paired with the device in the given address.
 * 
 * @param args			Arguments given. First argument should be the address in String format.
 * @param callbackCtx	Where to send results.
 */
private void isPaired(JSONArray args, CallbackContext callbackCtx)
{
	try
	{
		String address = args.getString(0);
		callbackCtx.sendPluginResult(new PluginResult(PluginResult.Status.OK, _bluetooth.isBonded(address)));
	}
	catch(Exception e)
	{
		this.error(callbackCtx, e.getMessage(), BluetoothError.ERR_UNKNOWN);
	}
}
 
Example 11
Source File: BrowserTab.java    From cordova-plugin-browsertab with Apache License 2.0 5 votes vote down vote up
private void openUrl(JSONArray args, CallbackContext callbackContext) {
  if (args.length() < 1) {
    Log.d(LOG_TAG, "openUrl: no url argument received");
    callbackContext.error("URL argument missing");
    return;
  }

  String urlStr;
  try {
    urlStr = args.getString(0);
  } catch (JSONException e) {
    Log.d(LOG_TAG, "openUrl: failed to parse url argument");
    callbackContext.error("URL argument is not a string");
    return;
  }

  String customTabsBrowser = findCustomTabBrowser();
  if (customTabsBrowser == null) {
    Log.d(LOG_TAG, "openUrl: no in app browser tab available");
    callbackContext.error("no in app browser tab implementation available");
  }

  // Initialize Builder
  CustomTabsIntent.Builder customTabsIntentBuilder = new CustomTabsIntent.Builder();

  // Set tab color
  String tabColor = cordova.getActivity().getString(cordova.getActivity().getResources().getIdentifier("CUSTOM_TAB_COLOR_RGB", "string", cordova.getActivity().getPackageName()));
  customTabsIntentBuilder.setToolbarColor(colorParser.parseColor(tabColor));

  // Create Intent
  CustomTabsIntent customTabsIntent = customTabsIntentBuilder.build();

  // Load URL
  customTabsIntent.launchUrl(cordova.getActivity(), Uri.parse(urlStr));

  Log.d(LOG_TAG, "in app browser call dispatched");
  callbackContext.success();
}
 
Example 12
Source File: JsonUtil.java    From mobile-sdk-android with Apache License 2.0 5 votes vote down vote up
public static String getStringFromArray(JSONArray array, int index) {
    if (array == null) return "";
    try {
        return array.getString(index);
    } catch (JSONException ignored) {}
    return "";
}
 
Example 13
Source File: Preferences.java    From android-vlc-remote with GNU General Public License v3.0 5 votes vote down vote up
private static ArrayList<String> fromJSONArray(String json) {
    try {
        JSONArray array = new JSONArray(json);
        int n = array.length();
        ArrayList<String> list = new ArrayList<String>(n);
        for (int i = 0; i < n; i++) {
            String element = array.getString(i);
            list.add(element);
        }
        return list;
    } catch (JSONException e) {
        return new ArrayList<String>(0);
    }
}
 
Example 14
Source File: P2PPeerConnectionChannel.java    From owt-client-android with Apache License 2.0 5 votes vote down vote up
void processTrackAck(JSONArray tracksData) throws JSONException {
    for (int i = 0; i < tracksData.length(); i++) {
        String trackId = tracksData.getString(i);
        CallbackInfo callbackInfo = publishCallbacks.get(trackId);
        if (callbackInfo != null
                && --callbackInfo.trackNum == 0 && callbackInfo.callback != null) {
            Publication publication = new Publication(callbackInfo.mediaStreamId, this);
            publications.add(publication);
            callbackInfo.callback.onSuccess(publication);
        }
        publishCallbacks.remove(trackId);
    }
}
 
Example 15
Source File: CountlyNative.java    From countly-sdk-cordova with MIT License 5 votes vote down vote up
public String userData_incrementBy(JSONArray args){
    try {
        this.log("userData_incrementBy", args);
        String keyName = args.getString(0);
        int keyIncrement = Integer.parseInt(args.getString(1));
        Countly.userData.incrementBy(keyName, keyIncrement);
        Countly.userData.save();
        return "userData_incrementBy success!";
    }catch (JSONException jsonException){
        return jsonException.toString();
    }
}
 
Example 16
Source File: CountlyNative.java    From countly-sdk-cordova with MIT License 5 votes vote down vote up
public String pushTokenType(JSONArray args){
    try {
        this.log("pushTokenType", args);
        String tokenType = args.getString(0);
        if("2".equals(tokenType)){
            pushTokenTypeVariable = Countly.CountlyMessagingMode.TEST;
        }else{
            pushTokenTypeVariable = Countly.CountlyMessagingMode.PRODUCTION;
        }
        return "pushTokenType: success";
    }catch (JSONException jsonException){
        return jsonException.toString();
    }
}
 
Example 17
Source File: ApiAppOauth.java    From hellosign-java-sdk with MIT License 5 votes vote down vote up
/**
 * Constructor that instantiates an ApiApp OAuth object based on the JSON response from the
 * HelloSign API.
 *
 * @param json JSONObject
 * @throws HelloSignException thrown if there is a problem updating the OAuth scopes.
 */
public ApiAppOauth(JSONObject json) throws HelloSignException {
    super(json, APIAPP_OAUTH_KEY);
    if (has(APIAPP_OAUTH_SCOPES)) {
        try {
            JSONArray scopeArray = (JSONArray) get(APIAPP_OAUTH_SCOPES);
            for (int i = 0; i < scopeArray.length(); i++) {
                String scope = scopeArray.getString(i);
                scopes.add(ApiAppOauthScopeType.valueOf(scope));
            }
        } catch (Exception ex) {
            throw new HelloSignException(ex);
        }
    }
}
 
Example 18
Source File: DataSetResource.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
public String persistDataSets(JSONObject labels) {
	logger.debug("IN");
	Monitor monitor = MonitorFactory.start("spagobi.dataset.persist");
	JSONObject labelsJSON = new JSONObject();

	Iterator<String> keys = labels.keys();
	while (keys.hasNext()) {
		String label = keys.next();
		try {
			IDataSetDAO dataSetDao = DAOFactory.getDataSetDAO();
			dataSetDao.setUserProfile(getUserProfile());
			IDataSet dataSet = dataSetDao.loadDataSetByLabel(label);
			if (dataSet == null) {
				throw new SpagoBIRuntimeException("Impossibile to load dataSet with label [" + label + "]");
			}
			SQLDBCache cache = (SQLDBCache) CacheFactory.getCache(SpagoBICacheConfiguration.getInstance());
			String tableName = null;
			if (dataSet.isPersisted() && dataSet.getDataSourceForWriting().getDsId() == cache.getDataSource().getDsId()) {
				tableName = dataSet.getTableNameForReading();
			} else if (dataSet.isFlatDataset() && dataSet.getDataSource().getDsId() == cache.getDataSource().getDsId()) {
				tableName = dataSet.getTableNameForReading();
			} else {
				DatasetManagementAPI dataSetManagementAPI = getDatasetManagementAPI();
				dataSetManagementAPI.setUserProfile(getUserProfile());
				tableName = dataSetManagementAPI.persistDataset(label);
				Monitor monitorIdx = MonitorFactory.start("spagobi.dataset.persist.indixes");
				if (tableName != null) {
					JSONArray columnsArray = labels.getJSONArray(label);
					Set<String> columns = new HashSet<String>(columnsArray.length());
					for (int i = 0; i < columnsArray.length(); i++) {
						String column = columnsArray.getString(i);
						columns.add(column);
					}
					if (columns.size() > 0) {
						dataSetManagementAPI.createIndexes(label, columns);
					}
				}
				monitorIdx.stop();
			}
			if (tableName != null) {
				logger.debug("Dataset with label " + label + " is stored in table with name " + tableName);
				labelsJSON.put(label, tableName);
			} else {
				logger.debug("Impossible to get dataset with label [" + label + "]");
			}
		} catch (Exception e) {
			logger.error("error in persisting dataset with label: " + label, e);
			throw new RuntimeException("error in persisting dataset with label " + label);
		}
	}

	logger.debug("OUT");
	monitor.stop();
	return labelsJSON.toString();
}
 
Example 19
Source File: App.java    From phonegapbootcampsite with MIT License 4 votes vote down vote up
/**
 * Load the url into the webview.
 *
 * @param url
 * @param props			Properties that can be passed in to the Cordova activity (i.e. loadingDialog, wait, ...)
 * @throws JSONException
 */
public void loadUrl(String url, JSONObject props) throws JSONException {
    LOG.d("App", "App.loadUrl("+url+","+props+")");
    int wait = 0;
    boolean openExternal = false;
    boolean clearHistory = false;

    // If there are properties, then set them on the Activity
    HashMap<String, Object> params = new HashMap<String, Object>();
    if (props != null) {
        JSONArray keys = props.names();
        for (int i = 0; i < keys.length(); i++) {
            String key = keys.getString(i);
            if (key.equals("wait")) {
                wait = props.getInt(key);
            }
            else if (key.equalsIgnoreCase("openexternal")) {
                openExternal = props.getBoolean(key);
            }
            else if (key.equalsIgnoreCase("clearhistory")) {
                clearHistory = props.getBoolean(key);
            }
            else {
                Object value = props.get(key);
                if (value == null) {

                }
                else if (value.getClass().equals(String.class)) {
                    params.put(key, (String)value);
                }
                else if (value.getClass().equals(Boolean.class)) {
                    params.put(key, (Boolean)value);
                }
                else if (value.getClass().equals(Integer.class)) {
                    params.put(key, (Integer)value);
                }
            }
        }
    }

    // If wait property, then delay loading

    if (wait > 0) {
        try {
            synchronized(this) {
                this.wait(wait);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    this.webView.showWebPage(url, openExternal, clearHistory, params);
}
 
Example 20
Source File: CheckBalanceTask.java    From eosio-java-android-example-app with MIT License 4 votes vote down vote up
@Override
protected Void doInBackground(String... params) {
    String nodeUrl = params[0];
    String fromAccount = params[1];

    EosioJavaRpcProviderImpl rpcProvider;
    try {
        this.publishProgress("Checking Account Balance...");
        rpcProvider = new EosioJavaRpcProviderImpl(nodeUrl, ENABLE_NETWORK_LOG);
        String getCurrentBalanceRequestJSON = "{\n" +
                "\t\"code\" : \"eosio.token\"\n" +
                "\t\"account\" : \"" + fromAccount + "\"\n" +
                "}";

        RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), getCurrentBalanceRequestJSON);
        String responseJSON = rpcProvider.getCurrencyBalance(requestBody);

        this.publishProgress("Account Balance Check Successful!");

        JSONArray jsonArray = new JSONArray(responseJSON);
        if (jsonArray.length() == 0) {
            this.publishProgress(Boolean.toString(false), "Invalid Account!");
            return null;
        }

        String accountBalance = jsonArray.getString(0);

        this.publishProgress(Boolean.toString(true), "Current Account Balance: " + accountBalance, accountBalance);
    } catch (EosioJavaRpcProviderInitializerError eosioJavaRpcProviderInitializerError) {
        // Happens if creating EosioJavaRpcProviderImpl unsuccessful
        eosioJavaRpcProviderInitializerError.printStackTrace();

        this.publishProgress(Boolean.toString(false), eosioJavaRpcProviderInitializerError.asJsonString());
    } catch (RpcProviderError rpcProviderError) {
        // Happens if calling getCurrentBalance unsuccessful
        rpcProviderError.printStackTrace();

        // try to get response from backend if the process fail from backend
        RPCResponseError rpcResponseError = ErrorUtils.getBackendError(rpcProviderError);
        if (rpcResponseError != null) {
            String backendErrorMessage = ErrorUtils.getBackendErrorMessageFromResponse(rpcResponseError);
            this.publishProgress(Boolean.toString(false), backendErrorMessage);
            return null;
        }

        this.publishProgress(Boolean.toString(false), rpcProviderError.getMessage());
    } catch (JSONException e) {
        // Happens if parsing JSON response unsuccessful
        e.printStackTrace();
        this.publishProgress(Boolean.toString(false), e.getMessage());
    }

    return null;
}