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

The following examples show how to use org.json.JSONArray#isNull() . 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: LibAVANE.java    From PowerFileExplorer with GNU General Public License v3.0 6 votes vote down vote up
public ArrayList<SampleFormat> getSampleFormats() {
    ArrayList<SampleFormat> vecFormats = new ArrayList<>();
    String json = jni_getSampleFormats();
    if (json != null && !json.isEmpty()) {
        try {
            JSONArray jsonArray = new JSONArray(json);
            JSONObject jsonObject;
            SampleFormat sampleFormat;
            for (int i = 0; i < jsonArray.length(); i++) {
                if (jsonArray.isNull(i)) continue;
                jsonObject = jsonArray.getJSONObject(i);
                sampleFormat = new SampleFormat();
                sampleFormat.name = jsonObject.getString("n");
                sampleFormat.depth = jsonObject.getString("d");
                vecFormats.add(sampleFormat);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return vecFormats;
}
 
Example 2
Source File: Storage.java    From cordova-android-chromeview with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the request and returns PluginResult.
 *
 * @param action
 *            The action to execute.
 * @param args
 *            JSONArry of arguments for the plugin.
 * @param callbackContext
 *            The callback context used when calling back into JavaScript.
 * @return True if the action was valid, false otherwise.
 */
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("openDatabase")) {
        this.openDatabase(args.getString(0), args.getString(1),
                args.getString(2), args.getLong(3));
    } else if (action.equals("executeSql")) {
        String[] s = null;
        if (args.isNull(1)) {
            s = new String[0];
        } else {
            JSONArray a = args.getJSONArray(1);
            int len = a.length();
            s = new String[len];
            for (int i = 0; i < len; i++) {
                s[i] = a.getString(i);
            }
        }
        this.executeSql(args.getString(0), s, args.getString(2));
    }
    else {
        return false;
    }
    callbackContext.success();
    return true;
}
 
Example 3
Source File: Contact.java    From Pix-Art-Messenger with GNU General Public License v3.0 6 votes vote down vote up
public ArrayList<String> getOtrFingerprints() {
    synchronized (this.keys) {
        final ArrayList<String> fingerprints = new ArrayList<String>();
        try {
            if (this.keys.has("otr_fingerprints")) {
                final JSONArray prints = this.keys.getJSONArray("otr_fingerprints");
                for (int i = 0; i < prints.length(); ++i) {
                    final String print = prints.isNull(i) ? null : prints.getString(i);
                    if (print != null && !print.isEmpty()) {
                        fingerprints.add(prints.getString(i).toLowerCase(Locale.US));
                    }
                }
            }
        } catch (final JSONException ignored) {

        }
        return fingerprints;
    }
}
 
Example 4
Source File: JsonUtils.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the float value from the Json Array for specified index
 * 
 * @param jsonArray The {@link JSONArray} to read the index from
 * @param index The key to read
 * @param required Whether the index is required. If <code>true</code>,
 *            attempting to read it when it is <code>null</code> will throw
 *            a {@link JSONException}
 * @param notNull Whether the value is allowed to be <code>null</code>. If
 *            <code>true</code>, will throw a {@link JSONException} if the
 *            value is null
 * @return The read value
 * @throws JSONException If the float was unable to be read, or if the
 *             required/notNull flags were violated
 */
public static float readFloat(final JSONArray jsonArray, final int index,
                final boolean required, final boolean notNull)
                throws JSONException {

    if (required) {
        //Will throw JsonException if mapping doesn't exist
        return (float) jsonArray.getDouble(index);
    }

    if (notNull && jsonArray.isNull(index)) {
        //throw JsonException because key is null
        throw new JSONException(String.format(Locale.US, NULL_VALUE_FORMAT_ARRAY, index));
    }
    float value = 0.0f;
    if (!jsonArray.isNull(index)) {
        value = (float) jsonArray.getDouble(index);
    }
    return value;
}
 
Example 5
Source File: JsonUtils.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the string value from the Json Array for specified index
 * 
 * @param jsonArray The {@link JSONArray} to read the index from
 * @param index The key to read
 * @param required Whether the index is required. If <code>true</code>,
 *            attempting to read it when it is <code>null</code> will throw
 *            a {@link JSONException}
 * @param notNull Whether the value is allowed to be <code>null</code>. If
 *            <code>true</code>, will throw a {@link JSONException} if the
 *            value is null
 * @return The read value
 * @throws JSONException If the String was unable to be read, or if the
 *             required/notNull flags were violated
 */
public static String readString(final JSONArray jsonArray, final int index,
                final boolean required, final boolean notNull)
                throws JSONException {

    if (required) {
        //Will throw JsonException if mapping doesn't exist
        return jsonArray.getString(index);
    }

    if (notNull && jsonArray.isNull(index)) {
        //throw JsonException because key is null
        throw new JSONException(String.format(Locale.US, NULL_VALUE_FORMAT_ARRAY, index));
    }
    String value = null;
    if (!jsonArray.isNull(index)) {
        value = jsonArray.getString(index);
    }
    return value;
}
 
Example 6
Source File: JsonUtils.java    From barterli_android with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the boolean value from the Json Array for specified index
 * 
 * @param jsonArray The {@link JSONArray} to read the index from
 * @param index The key to read
 * @param required Whether the index is required. If <code>true</code>,
 *            attempting to read it when it is <code>null</code> will throw
 *            a {@link JSONException}
 * @param notNull Whether the value is allowed to be <code>null</code>. If
 *            <code>true</code>, will throw a {@link JSONException} if the
 *            value is null
 * @return The read value
 * @throws JSONException If the boolean was unable to be read, or if the
 *             required/notNull flags were violated
 */
public static boolean readBoolean(final JSONArray jsonArray,
                final int index, final boolean required,
                final boolean notNull) throws JSONException {

    if (required) {
        //Will throw JsonException if mapping doesn't exist
        return jsonArray.getBoolean(index);
    }

    if (notNull && jsonArray.isNull(index)) {
        //throw JsonException because key is null
        throw new JSONException(String.format(Locale.US, NULL_VALUE_FORMAT_ARRAY, index));
    }
    boolean value = false;
    if (!jsonArray.isNull(index)) {
        value = jsonArray.getBoolean(index);
    }
    return value;
}
 
Example 7
Source File: VolumeControl.java    From reader with MIT License 5 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
	boolean actionState = true;
	context = cordova.getActivity().getApplicationContext();
	manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
	if (SET.equals(action)) {
		try {
			//Get the volume value to set
			int volume = getVolumeToSet(args.getInt(0));
			boolean play_sound;

			if(args.length() > 1 && !args.isNull(1)) {
				play_sound = args.getBoolean(1);
			} else {
				play_sound = true;
			}

			//Set the volume
			manager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, (play_sound ? AudioManager.FLAG_PLAY_SOUND : 0));
			callbackContext.success();
		} catch (Exception e) {
			LOG.d(TAG, "Error setting volume " + e);
			actionState = false;
		}
	} else if(GET.equals(action)) {
			//Get current system volume
			int currVol = getCurrentVolume();
			String strVol= String.valueOf(currVol);
			callbackContext.success(strVol);
			LOG.d(TAG, "Current Volume is " + currVol);
	} else {
		actionState = false;
	}
	return actionState;
}
 
Example 8
Source File: BoardsAdapter.java    From Dashchan with Apache License 2.0 5 votes vote down vote up
public void update() {
	listItems.clear();
	ChanConfiguration configuration = ChanConfiguration.get(chanName);
	JSONArray jsonArray = configuration.getBoards();
	if (jsonArray != null) {
		try {
			for (int i = 0, length = jsonArray.length(); i < length; i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				String title = CommonUtils.getJsonString(jsonObject, KEY_TITLE);
				if (length > 1) {
					listItems.add(new ListItem(null, title));
				}
				JSONArray boardsArray = jsonObject.getJSONArray(KEY_BOARDS);
				for (int j = 0; j < boardsArray.length(); j++) {
					String boardName = boardsArray.isNull(j) ? null : boardsArray.getString(j);
					if (!StringUtils.isEmpty(boardName)) {
						title = configuration.getBoardTitle(boardName);
						listItems.add(new ListItem(boardName, StringUtils.formatBoardTitle(chanName,
								boardName, title)));
					}
				}
			}
		} catch (JSONException e) {
			// Invalid data, ignore exception
		}
	}
	notifyDataSetChanged();
	if (filterMode) {
		applyFilter(filterText);
	}
}
 
Example 9
Source File: VolumeControl.java    From reader with MIT License 5 votes vote down vote up
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
	boolean actionState = true;
	context = cordova.getActivity().getApplicationContext();
	manager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
	if (SET.equals(action)) {
		try {
			//Get the volume value to set
			int volume = getVolumeToSet(args.getInt(0));
			boolean play_sound;

			if(args.length() > 1 && !args.isNull(1)) {
				play_sound = args.getBoolean(1);
			} else {
				play_sound = true;
			}

			//Set the volume
			manager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, (play_sound ? AudioManager.FLAG_PLAY_SOUND : 0));
			callbackContext.success();
		} catch (Exception e) {
			LOG.d(TAG, "Error setting volume " + e);
			actionState = false;
		}
	} else if(GET.equals(action)) {
			//Get current system volume
			int currVol = getCurrentVolume();
			String strVol= String.valueOf(currVol);
			callbackContext.success(strVol);
			LOG.d(TAG, "Current Volume is " + currVol);
	} else {
		actionState = false;
	}
	return actionState;
}
 
Example 10
Source File: JSONUtils.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static String optString(JSONArray json, int index, String fallback) {
    if (json != null) {
        if (!json.isNull(index)) {
            return json.optString(index, fallback);
        }
        return fallback;
    }
    return null;
}
 
Example 11
Source File: SQLiteAndroidDatabase.java    From AvI with MIT License 5 votes vote down vote up
private void bindArgsToStatement(SQLiteStatement myStatement, JSONArray sqlArgs) throws JSONException {
    for (int i = 0; i < sqlArgs.length(); i++) {
        if (sqlArgs.get(i) instanceof Float || sqlArgs.get(i) instanceof Double) {
            myStatement.bindDouble(i + 1, sqlArgs.getDouble(i));
        } else if (sqlArgs.get(i) instanceof Number) {
            myStatement.bindLong(i + 1, sqlArgs.getLong(i));
        } else if (sqlArgs.isNull(i)) {
            myStatement.bindNull(i + 1);
        } else {
            myStatement.bindString(i + 1, sqlArgs.getString(i));
        }
    }
}
 
Example 12
Source File: DataManager.java    From shinny-futures-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * date: 6/16/17
 * author: chenli
 * description: 刷新登录信息
 */
public void refreshTradeBean(JSONObject accountBeanObject) {
    try {
        JSONArray dataArray = accountBeanObject.getJSONArray(PARSE_TRADE_KEY_DATA);
        for (int i = 0; i < dataArray.length(); i++) {
            if (dataArray.isNull(i)) continue;
            JSONObject dataObject = dataArray.getJSONObject(i);
            Iterator<String> iterator = dataObject.keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (dataObject.isNull(key)) continue;
                JSONObject data = dataObject.getJSONObject(key);
                switch (key) {
                    case PARSE_TRADE_KEY_NOTIFY:
                        parseNotify(data);
                        break;
                    case PARSE_TRADE_KEY_TRADE:
                        parseTrade(data);
                        break;
                    default:
                        break;
                }
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 13
Source File: BookResultInfoRetriever.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 4 votes vote down vote up
@Override
void retrieveSupplementalInfo() throws IOException {

  CharSequence contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
                                                     HttpHelper.ContentType.JSON);

  if (contents.length() == 0) {
    return;
  }

  String title;
  String pages;
  Collection<String> authors = null;

  try {

    JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
    JSONArray items = topLevel.optJSONArray("items");
    if (items == null || items.isNull(0)) {
      return;
    }

    JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
    if (volumeInfo == null) {
      return;
    }

    title = volumeInfo.optString("title");
    pages = volumeInfo.optString("pageCount");

    JSONArray authorsArray = volumeInfo.optJSONArray("authors");
    if (authorsArray != null && !authorsArray.isNull(0)) {
      authors = new ArrayList<>(authorsArray.length());
      for (int i = 0; i < authorsArray.length(); i++) {
        authors.add(authorsArray.getString(i));
      }
    }

  } catch (JSONException e) {
    throw new IOException(e);
  }

  Collection<String> newTexts = new ArrayList<>();
  maybeAddText(title, newTexts);
  maybeAddTextSeries(authors, newTexts);
  maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);
  
  String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
      + "/search?tbm=bks&source=zxing&q=";

  append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}
 
Example 14
Source File: BookResultInfoRetriever.java    From ZXing-Standalone-library with Apache License 2.0 4 votes vote down vote up
@Override
void retrieveSupplementalInfo() throws IOException {

  CharSequence contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
                                                     HttpHelper.ContentType.JSON);

  if (contents.length() == 0) {
    return;
  }

  String title;
  String pages;
  Collection<String> authors = null;

  try {

    JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
    JSONArray items = topLevel.optJSONArray("items");
    if (items == null || items.isNull(0)) {
      return;
    }

    JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
    if (volumeInfo == null) {
      return;
    }

    title = volumeInfo.optString("title");
    pages = volumeInfo.optString("pageCount");

    JSONArray authorsArray = volumeInfo.optJSONArray("authors");
    if (authorsArray != null && !authorsArray.isNull(0)) {
      authors = new ArrayList<>(authorsArray.length());
      for (int i = 0; i < authorsArray.length(); i++) {
        authors.add(authorsArray.getString(i));
      }
    }

  } catch (JSONException e) {
    throw new IOException(e);
  }

  Collection<String> newTexts = new ArrayList<>();
  maybeAddText(title, newTexts);
  maybeAddTextSeries(authors, newTexts);
  maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);
  
  String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
      + "/search?tbm=bks&source=zxing&q=";

  append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}
 
Example 15
Source File: SQLitePlugin.java    From AvI with MIT License 4 votes vote down vote up
private boolean executeAndPossiblyThrow(Action action, JSONArray args, CallbackContext cbc)
        throws JSONException {

    boolean status = true;
    JSONObject o;
    String echo_value;
    String dbname;

    switch (action) {
        case echoStringValue:
            o = args.getJSONObject(0);
            echo_value = o.getString("value");
            cbc.success(echo_value);
            break;

        case open:
            o = args.getJSONObject(0);
            dbname = o.getString("name");
            // open database and start reading its queue
            this.startDatabase(dbname, o, cbc);
            break;

        case close:
            o = args.getJSONObject(0);
            dbname = o.getString("path");
            // put request in the q to close the db
            this.closeDatabase(dbname, cbc);
            break;

        case delete:
            o = args.getJSONObject(0);
            dbname = o.getString("path");

            deleteDatabase(dbname, cbc);

            break;

        case executeSqlBatch:
        case backgroundExecuteSqlBatch:
            JSONObject allargs = args.getJSONObject(0);
            JSONObject dbargs = allargs.getJSONObject("dbargs");
            dbname = dbargs.getString("dbname");
            JSONArray txargs = allargs.getJSONArray("executes");

            if (txargs.isNull(0)) {
                cbc.error("missing executes list");
            } else {
                int len = txargs.length();
                String[] queries = new String[len];
                JSONArray[] jsonparams = new JSONArray[len];

                for (int i = 0; i < len; i++) {
                    JSONObject a = txargs.getJSONObject(i);
                    queries[i] = a.getString("sql");
                    jsonparams[i] = a.getJSONArray("params");
                }

                // put db query in the queue to be executed in the db thread:
                DBQuery q = new DBQuery(queries, jsonparams, cbc);
                DBRunner r = dbrmap.get(dbname);
                if (r != null) {
                    try {
                        r.q.put(q);
                    } catch(Exception e) {
                        Log.e(SQLitePlugin.class.getSimpleName(), "couldn't add to queue", e);
                        cbc.error("couldn't add to queue");
                    }
                } else {
                    cbc.error("database not open");
                }
            }
            break;
    }

    return status;
}
 
Example 16
Source File: d.java    From letv with Apache License 2.0 4 votes vote down vote up
public final String a(WebView webView, String str) {
    if (TextUtils.isEmpty(str)) {
        return a(str, LeMessageIds.MSG_FLOAT_BALL_REQUEST_DATA, z[28]);
    }
    try {
        JSONObject jSONObject = new JSONObject(str);
        String string = jSONObject.getString(z[32]);
        JSONArray jSONArray = jSONObject.getJSONArray(z[31]);
        JSONArray jSONArray2 = jSONObject.getJSONArray(z[30]);
        int length = jSONArray.length();
        Object[] objArr = new Object[(length + 1)];
        int i = 0;
        objArr[0] = webView;
        int i2 = 0;
        while (i2 < length) {
            String str2;
            int i3;
            String optString = jSONArray.optString(i2);
            int i4;
            if (z[34].equals(optString)) {
                optString = string + z[2];
                objArr[i2 + 1] = jSONArray2.isNull(i2) ? null : jSONArray2.getString(i2);
                i4 = i;
                str2 = optString;
                i3 = i4;
            } else if (z[27].equals(optString)) {
                string = string + z[7];
                i3 = ((i * 10) + i2) + 1;
                str2 = string;
            } else if (z[33].equals(optString)) {
                optString = string + z[0];
                objArr[i2 + 1] = Boolean.valueOf(jSONArray2.getBoolean(i2));
                i4 = i;
                str2 = optString;
                i3 = i4;
            } else if (z[29].equals(optString)) {
                optString = string + z[1];
                objArr[i2 + 1] = jSONArray2.isNull(i2) ? null : jSONArray2.getJSONObject(i2);
                i4 = i;
                str2 = optString;
                i3 = i4;
            } else {
                i4 = i;
                str2 = string + z[4];
                i3 = i4;
            }
            i2++;
            string = str2;
            i = i3;
        }
        Method method = (Method) this.a.get(string);
        if (method == null) {
            return a(str, LeMessageIds.MSG_FLOAT_BALL_REQUEST_DATA, new StringBuilder(z[25]).append(string).append(z[24]).toString());
        }
        if (i > 0) {
            Class[] parameterTypes = method.getParameterTypes();
            while (i > 0) {
                i2 = i - ((i / 10) * 10);
                Class cls = parameterTypes[i2];
                if (cls == Integer.TYPE) {
                    objArr[i2] = Integer.valueOf(jSONArray2.getInt(i2 - 1));
                } else if (cls == Long.TYPE) {
                    objArr[i2] = Long.valueOf(Long.parseLong(jSONArray2.getString(i2 - 1)));
                } else {
                    objArr[i2] = Double.valueOf(jSONArray2.getDouble(i2 - 1));
                }
                i /= 10;
            }
        }
        return a(str, 200, method.invoke(null, objArr));
    } catch (Exception e) {
        return e.getCause() != null ? a(str, LeMessageIds.MSG_FLOAT_BALL_REQUEST_DATA, new StringBuilder(z[26]).append(e.getCause().getMessage()).toString()) : a(str, LeMessageIds.MSG_FLOAT_BALL_REQUEST_DATA, new StringBuilder(z[26]).append(e.getMessage()).toString());
    }
}
 
Example 17
Source File: BookResultInfoRetriever.java    From zxingfragmentlib with Apache License 2.0 4 votes vote down vote up
@Override
void retrieveSupplementalInfo() throws IOException {

  CharSequence contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
                                                     HttpHelper.ContentType.JSON);

  if (contents.length() == 0) {
    return;
  }

  String title;
  String pages;
  Collection<String> authors = null;

  try {

    JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
    JSONArray items = topLevel.optJSONArray("items");
    if (items == null || items.isNull(0)) {
      return;
    }

    JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
    if (volumeInfo == null) {
      return;
    }

    title = volumeInfo.optString("title");
    pages = volumeInfo.optString("pageCount");

    JSONArray authorsArray = volumeInfo.optJSONArray("authors");
    if (authorsArray != null && !authorsArray.isNull(0)) {
      authors = new ArrayList<>(authorsArray.length());
      for (int i = 0; i < authorsArray.length(); i++) {
        authors.add(authorsArray.getString(i));
      }
    }

  } catch (JSONException e) {
    throw new IOException(e);
  }

  Collection<String> newTexts = new ArrayList<>();
  maybeAddText(title, newTexts);
  maybeAddTextSeries(authors, newTexts);
  maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);
  
  String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
      + "/search?tbm=bks&source=zxing&q=";

  append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}
 
Example 18
Source File: JsCallJava.java    From AgentWeb with Apache License 2.0 4 votes vote down vote up
public String call(WebView webView, JSONObject jsonObject) {
    long time = 0;
    if (LogUtils.isDebug()) {
        time = android.os.SystemClock.uptimeMillis();
    }
    if (jsonObject != null) {
        try {
            String methodName = jsonObject.getString(KEY_METHOD);
            JSONArray argsTypes = jsonObject.getJSONArray(KEY_TYPES);
            JSONArray argsVals = jsonObject.getJSONArray(KEY_ARGS);
            String sign = methodName;
            int len = argsTypes.length();
            Object[] values = new Object[len];
            int numIndex = 0;
            String currType;

            for (int k = 0; k < len; k++) {
                currType = argsTypes.optString(k);
                if ("string".equals(currType)) {
                    sign += "_S";
                    values[k] = argsVals.isNull(k) ? null : argsVals.getString(k);
                } else if ("number".equals(currType)) {
                    sign += "_N";
                    numIndex = numIndex * 10 + k + 1;
                } else if ("boolean".equals(currType)) {
                    sign += "_B";
                    values[k] = argsVals.getBoolean(k);
                } else if ("object".equals(currType)) {
                    sign += "_O";
                    values[k] = argsVals.isNull(k) ? null : argsVals.getJSONObject(k);
                } else if ("function".equals(currType)) {
                    sign += "_F";
                    values[k] = new JsCallback(webView, mInterfacedName, argsVals.getInt(k));
                } else {
                    sign += "_P";
                }
            }

            Method currMethod = mMethodsMap.get(sign);

            // 方法匹配失败
            if (currMethod == null) {
                return getReturn(jsonObject, 500, "not found method(" + sign + ") with valid parameters", time);
            }
            // 数字类型细分匹配
            if (numIndex > 0) {
                Class[] methodTypes = currMethod.getParameterTypes();
                int currIndex;
                Class currCls;
                while (numIndex > 0) {
                    currIndex = numIndex - numIndex / 10 * 10 - 1;
                    currCls = methodTypes[currIndex];
                    if (currCls == int.class) {
                        values[currIndex] = argsVals.getInt(currIndex);
                    } else if (currCls == long.class) {
                        //WARN: argsJson.getLong(k + defValue) will return a bigger incorrect number
                        values[currIndex] = Long.parseLong(argsVals.getString(currIndex));
                    } else {
                        values[currIndex] = argsVals.getDouble(currIndex);
                    }
                    numIndex /= 10;
                }
            }

            return getReturn(jsonObject, 200, currMethod.invoke(mInterfaceObj, values), time);
        } catch (Exception e) {
            LogUtils.safeCheckCrash(TAG, "call", e);
            //优先返回详细的错误信息
            if (e.getCause() != null) {
                return getReturn(jsonObject, 500, "method execute result:" + e.getCause().getMessage(), time);
            }
            return getReturn(jsonObject, 500, "method execute result:" + e.getMessage(), time);
        }
    } else {
        return getReturn(jsonObject, 500, "call data empty", time);
    }
}
 
Example 19
Source File: BookResultInfoRetriever.java    From BarcodeEye with Apache License 2.0 4 votes vote down vote up
@Override
void retrieveSupplementalInfo() throws IOException {

  CharSequence contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn,
                                                     HttpHelper.ContentType.JSON);

  if (contents.length() == 0) {
    return;
  }

  String title;
  String pages;
  Collection<String> authors = null;

  try {

    JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
    JSONArray items = topLevel.optJSONArray("items");
    if (items == null || items.isNull(0)) {
      return;
    }

    JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
    if (volumeInfo == null) {
      return;
    }

    title = volumeInfo.optString("title");
    pages = volumeInfo.optString("pageCount");

    JSONArray authorsArray = volumeInfo.optJSONArray("authors");
    if (authorsArray != null && !authorsArray.isNull(0)) {
      authors = new ArrayList<String>(authorsArray.length());
      for (int i = 0; i < authorsArray.length(); i++) {
        authors.add(authorsArray.getString(i));
      }
    }

  } catch (JSONException e) {
    throw new IOException(e);
  }

  Collection<String> newTexts = new ArrayList<String>();
  maybeAddText(title, newTexts);
  maybeAddTextSeries(authors, newTexts);
  maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);

  String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
      + "/search?tbm=bks&source=zxing&q=";

  append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}
 
Example 20
Source File: DataManager.java    From shinny-futures-android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * date: 6/16/17
 * author: chenli
 * description: 刷新行情数据,K线数据
 */
public void refreshFutureBean(JSONObject rtnData) {
    try {
        JSONArray dataArray = rtnData.getJSONArray(PARSE_MARKET_KEY_DATA);
        DiffEntity diffEntity = RTN_DATA.getData();
        for (int i = 0; i < dataArray.length(); i++) {
            if (dataArray.isNull(i)) continue;
            JSONObject dataObject = dataArray.getJSONObject(i);
            Iterator<String> iterator = dataObject.keys();
            while (iterator.hasNext()) {
                String key0 = iterator.next();
                if (dataObject.isNull(key0)) continue;
                switch (key0) {
                    case PARSE_MARKET_KEY_QUOTES:
                        parseQuotes(dataObject, diffEntity);
                        break;
                    case PARSE_MARKET_KEY_KLINES:
                        parseKlines(dataObject, diffEntity);
                        break;
                    case PARSE_MARKET_KEY_TICKS:
                        parseTicks(dataObject, diffEntity);
                        break;
                    case PARSE_MARKET_KEY_CHARTS:
                        parseCharts(dataObject, diffEntity);
                        break;
                    case PARSE_MARKET_KEY_INS_LIST:
                        diffEntity.setIns_list(dataObject.optString(key0));
                        break;
                    case PARSE_MARKET_KEY_MDHIS_MORE_DATA:
                        diffEntity.setMdhis_more_data(dataObject.optBoolean(key0));
                        break;
                    default:
                        break;
                }
            }
        }
        sendMessage(MD_MESSAGE, MD_BROADCAST);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}