Java Code Examples for org.json.JSONObject.optJSONObject()

The following are Jave code examples for showing how to use optJSONObject() of the org.json.JSONObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Shadbot   File: DBUser.java   View Source Code Vote up 6 votes
private void load() {
	StatsManager.increment(DatabaseEnum.USER_LOADED);

	JSONObject guildObj = Database.opt(guild.getStringID());
	if(guildObj == null) {
		return;
	}

	JSONObject usersObj = guildObj.optJSONObject(DBGuild.USERS_KEY);
	if(usersObj == null) {
		return;
	}

	JSONObject userObj = usersObj.optJSONObject(Long.toString(userID));
	if(userObj == null) {
		return;
	}

	this.coins = userObj.optInt(COINS_KEY);
}
 
Example 2
Project: devtools-driver   File: EventFactory.java   View Source Code Vote up 6 votes
private static boolean isFrameOrIFrame(JSONObject message) {
  String method = message.optString("method");
  JSONObject params = message.optJSONObject("params");

  if (NODE_INSERTED.equals(method)
      && params != null
      && "IFRAME".equals(params.optJSONObject("node").optString("nodeName"))) {
    return true;
  }
  if (NODE_INSERTED.equals(method)
      && params != null
      && "FRAME".equals(params.optJSONObject("node").optString("nodeName"))) {
    return true;
  }
  return false;
}
 
Example 3
Project: proc-bridge   File: Protocol.java   View Source Code Vote up 6 votes
@Override
void decode(JSONObject object) throws ProcBridgeException {
    try {
        String api = object.getString(Protocol.KEY_API);
        if (api.isEmpty()) {
            throw ProcBridgeException.malformedInputData();
        }
        this.api = api;

        JSONObject body = object.optJSONObject(Protocol.KEY_BODY);
        if (body != null) {
            this.body = body;
        }

    } catch (JSONException ex) {
        throw ProcBridgeException.malformedInputData();
    }
}
 
Example 4
Project: pullstring-android   File: BehaviorOutput.java   View Source Code Vote up 5 votes
public BehaviorOutput(JSONObject json) {
    mGuid = json.optString(Keys.Guid);
    mBehavior = json.optString(Keys.Behavior);

    JSONObject params = json.optJSONObject(Keys.Parameters);
    if (params != null && params.length() > 0) {
        mParameters = ParameterValue.getParameterValueDict(params);
    }
}
 
Example 5
Project: Shadbot   File: DBGuild.java   View Source Code Vote up 5 votes
private void load() {
	StatsManager.increment(DatabaseEnum.GUILD_LOADED);

	JSONObject guildObj = Database.opt(guild.getStringID());
	if(guildObj == null) {
		return;
	}

	JSONObject settingsObj = guildObj.optJSONObject(SETTINGS_KEY);
	if(settingsObj != null) {
		for(String settingKey : settingsObj.keySet()) {
			settingsMap.put(SettingEnum.valueOf(settingKey.toUpperCase()), settingsObj.get(settingKey));
		}
	}
}
 
Example 6
Project: logistimo-web-service   File: EventSpec.java   View Source Code Vote up 5 votes
public NotifyOptions(String subscriberType, JSONObject json) throws JSONException {
  String idsStr = json.optString(Subscriber.IDS);
  subscriber = new Subscriber(subscriberType, StringUtil.getList(idsStr));
  frequency = json.getInt(FREQUENCY);
  method = json.getString(METHOD);
  smsNotify = json.optBoolean(SMS_NOTIFY);
  JSONObject repeatOptionsJson = json.optJSONObject(REPEAT_OPTIONS);
  if (repeatOptionsJson != null) {
    repeatOptions = new RepeatOptions(repeatOptionsJson);
  }
}
 
Example 7
Project: letv   File: ParserCashier.java   View Source Code Vote up 5 votes
public BaseBean Json2Entity(String content) {
    this.cashierInfo = new CashierInfo();
    EALogger.i(IDataSource.SCHEME_HTTP_TAG, "收银台接口数据:" + content);
    try {
        JSONObject jo = new JSONObject(content);
        this.cashierInfo.setStatus(jo.optString("status"));
        this.cashierInfo.setMessage(jo.optString("message"));
        JSONObject result = jo.optJSONObject("result");
        if (result == null) {
            return this.cashierInfo;
        }
        JSONObject object = result.optJSONObject("payMentResult");
        if (object != null) {
            this.cashierInfo.setVersion(object.optString("version"));
            this.cashierInfo.setService(object.optString(NotificationCompat.CATEGORY_SERVICE));
            this.cashierInfo.setMerchant_business_id(object.optString("merchantBusinessId"));
            this.cashierInfo.setUser_id(object.optString(UserInfoDb.USER_ID));
            this.cashierInfo.setNotify_url(object.optString("notifyUrl"));
            this.cashierInfo.setMerchant_no(object.optString("merchantNo"));
            this.cashierInfo.setOut_trade_no(object.optString("outTradeNo"));
            this.cashierInfo.setPrice(object.optString("price"));
            this.cashierInfo.setCurrency(object.optString("currency"));
            this.cashierInfo.setPay_expire(object.optString("payExpire"));
            this.cashierInfo.setProduct_id(object.optString("productId"));
            this.cashierInfo.setProduct_name(object.optString("productName"));
            this.cashierInfo.setProduct_desc(object.optString("productDesc"));
            this.cashierInfo.setTimestamp(object.optString("timestamp"));
            this.cashierInfo.setKey_index(object.optString("keyIndex"));
            this.cashierInfo.setInput_charset(object.optString("inputCharset"));
            this.cashierInfo.setIp(object.optString("ip"));
            this.cashierInfo.setSign_type(object.optString("signType"));
            this.cashierInfo.setSign(object.optString(TradeInfo.SIGN));
            this.cashierInfo.setHb_fq(object.optString("hbFq"));
        }
        return this.cashierInfo;
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: discord-bot-gateway   File: ServerJDA.java   View Source Code Vote up 5 votes
@Override
public void login(String token, ShardInfo shardInfo, SessionReconnectQueue reconnectQueue) throws LoginException, RateLimitedException {
    setStatus(Status.LOGGING_IN);
    if(token == null || token.isEmpty()) throw new LoginException("Provided token was null or empty!");

    setToken(token);
    verifyToken();
    this.shardInfo = shardInfo;
    JDAImpl.LOG.info("Login Successful!");

    client = new ServerWebSocketClient(this, reconnectQueue, gatewayServer);

    JSONObject cachedPresence = gatewayServer.cachedPresence;
    if(cachedPresence != null) {
        JSONObject game = cachedPresence.optJSONObject("game");
        if(game != null) {
            getPresence().setPresence(
                    OnlineStatus.fromKey(cachedPresence.getString("status")),
                    Game.of(game.getString("name"), game.optString("url")),
                    cachedPresence.getBoolean("afk")
            );
        } else {
            getPresence().setPresence(
                    OnlineStatus.fromKey(cachedPresence.getString("status")),
                    null,
                    cachedPresence.getBoolean("afk")
            );
        }
        gatewayServer.cachedPresence = null;
    }

    if(shutdownHook != null) {
        Runtime.getRuntime().addShutdownHook(shutdownHook);
    }
}
 
Example 9
Project: letv   File: LetvBaseParser.java   View Source Code Vote up 5 votes
private boolean isHotPointTokenInvalid(JSONObject object) {
    boolean isInvalid = false;
    JSONObject body = object.optJSONObject("body");
    if (!isNull(body) && TextUtils.equals(body.optString("code"), "403")) {
        isInvalid = true;
    }
    LogInfo.log("isHotPointTokenInvalid", "isInvalid : " + isInvalid);
    return isInvalid;
}
 
Example 10
Project: letv   File: LetvBaseParser.java   View Source Code Vote up 5 votes
private boolean isPlayRecordTokenInvalid(JSONObject object) {
    boolean isInvalid = false;
    JSONObject header = object.optJSONObject("header");
    if (!isNull(header) && TextUtils.equals(header.optString("status"), "5")) {
        isInvalid = true;
    }
    LogInfo.log("playRecordTokenInvalid", "isInvalid : " + isInvalid);
    return isInvalid;
}
 
Example 11
Project: kognitivo   File: GraphRequest.java   View Source Code Vote up 4 votes
/**
 * Sets the callback which will be called when the request finishes.
 *
 * @param callback the callback
 */
public final void setCallback(final Callback callback) {
    // Wrap callback to parse debug response if Graph Debug Mode is Enabled.
    if (FacebookSdk.isLoggingBehaviorEnabled(LoggingBehavior.GRAPH_API_DEBUG_INFO)
            || FacebookSdk.isLoggingBehaviorEnabled(LoggingBehavior.GRAPH_API_DEBUG_WARNING)) {
        Callback wrapper = new Callback() {
            @Override
            public void onCompleted(GraphResponse response) {
                JSONObject responseObject = response.getJSONObject();
                JSONObject debug =
                        responseObject != null ? responseObject.optJSONObject(DEBUG_KEY) : null;
                JSONArray debugMessages =
                        debug != null ? debug.optJSONArray(DEBUG_MESSAGES_KEY) : null;
                if (debugMessages != null) {
                    for (int i = 0; i < debugMessages.length(); ++i) {
                        JSONObject debugMessageObject = debugMessages.optJSONObject(i);
                        String debugMessage = debugMessageObject != null
                                ? debugMessageObject.optString(DEBUG_MESSAGE_KEY)
                                : null;
                        String debugMessageType = debugMessageObject != null
                                ? debugMessageObject.optString(DEBUG_MESSAGE_TYPE_KEY)
                                : null;
                        String debugMessageLink = debugMessageObject != null
                                ? debugMessageObject.optString(DEBUG_MESSAGE_LINK_KEY)
                                : null;
                        if (debugMessage != null && debugMessageType != null) {
                            LoggingBehavior behavior = LoggingBehavior.GRAPH_API_DEBUG_INFO;
                            if (debugMessageType.equals("warning")) {
                                behavior = LoggingBehavior.GRAPH_API_DEBUG_WARNING;
                            }
                            if (!Utility.isNullOrEmpty(debugMessageLink)) {
                                debugMessage += " Link: " + debugMessageLink;
                            }
                            Logger.log(behavior, TAG, debugMessage);
                        }
                    }
                }
                if (callback != null) {
                    callback.onCompleted(response);
                }
            }
        };
        this.callback = wrapper;
    } else {
        this.callback = callback;
    }

}
 
Example 12
Project: amap   File: SettingActivity.java   View Source Code Vote up 4 votes
@Override
public void onResponse(Call call, Response response) throws IOException {
    if (response.code() != 200) {
        // Toast.makeText(SettingActivity.this, "服务器连接失败!", Toast.LENGTH_SHORT).show();
        return;
    }
    String result = response.body().string();
    LogUtil.d("result:" + result);
    try {
        JSONObject jsonObj = new JSONObject(result);
        if (jsonObj != null) {
            String retCode = jsonObj.optString("retCode");
            if (retCode != null && retCode.equals("0")) {
                // 在此处理业务逻辑
                JSONObject bizDataJsonObj = jsonObj.optJSONObject("bizData");
                if (bizDataJsonObj != null) {
                    final String retVersionCode = bizDataJsonObj.optString("retVersionCode");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            swipRefreshLayout.setRefreshing(false);

                            if ("0".equals(retVersionCode)) {
                                //不需要更新
                                SimpleDialog.show(SettingActivity.this, "已是最新版本,无需更新!");
                            } else if ("1".equals(retVersionCode)) {

                                SimpleDialog.forceShow(SettingActivity.this, "检查到新版本,是否立刻升级?", null, new SimpleDialog.OnPositiveClickListener() {
                                    @Override
                                    public void onPositiveClick() {
                                        getAppDownloadUrl();
                                    }
                                });

                            }
                        }
                    });
                }
                return;
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 13
Project: Tangram-Android   File: Card.java   View Source Code Vote up 4 votes
public void parseWith(@NonNull JSONObject data, @NonNull final MVHelper resolver, boolean isParseCell) {
    if (TangramBuilder.isPrintLog()) {
        if (serviceManager == null) {
            throw new RuntimeException("serviceManager is null when parsing card");
        }
    }

    this.extras = data;
    this.type = data.optInt(KEY_TYPE, type);
    this.stringType = data.optString(KEY_TYPE);
    id = data.optString(KEY_ID, id == null ? "" : id);

    loadMore = data.optInt(KEY_LOAD_TYPE, 0) == LOAD_TYPE_LOADMORE;
    //you should alway assign hasMore to indicate there's more data explicitly
    if (data.has(KEY_HAS_MORE)) {
        hasMore = data.optBoolean(KEY_HAS_MORE);
    } else {
        if (data.has(KEY_LOAD_TYPE)) {
            hasMore = data.optInt(KEY_LOAD_TYPE) == LOAD_TYPE_LOADMORE;
        }
    }
    load = data.optString(KEY_API_LOAD, null);
    loadParams = data.optJSONObject(KEY_API_LOAD_PARAMS);
    loaded = data.optBoolean(KEY_LOADED, false);

    maxChildren = data.optInt(KEY_MAX_CHILDREN, maxChildren);
    // parsing header
    if (Utils.isSupportHeaderFooter(stringType) && isParseCell) {
        JSONObject header = data.optJSONObject(KEY_HEADER);
        parseHeaderCell(resolver, header);
    }

    // parsing body
    JSONArray componentArray = data.optJSONArray(KEY_ITEMS);
    if (componentArray != null && isParseCell) {
        final int cellLength = Math.min(componentArray.length(), maxChildren);
        for (int i = 0; i < cellLength; i++) {
            final JSONObject cellData = componentArray.optJSONObject(i);
            createCell(resolver, cellData, true);
        }
    }
    // parsing footer
    if (Utils.isSupportHeaderFooter(stringType) && isParseCell) {
        JSONObject footer = data.optJSONObject(KEY_FOOTER);
        parseFooterCell(resolver, footer);
    }

    JSONObject styleJson = data.optJSONObject(KEY_STYLE);

    parseStyle(styleJson);

}
 
Example 14
Project: boohee_v5.6   File: SportCourseActivity.java   View Source Code Vote up 4 votes
private void handleData(JSONObject object) {
    if (object != null) {
        this.mIntroduceURL = object.optString("link_url");
        this.mCourseID = object.optInt("sports_course_id");
        setTitle(object.optString("name"));
        JSONObject data = object.optJSONObject("sports_days");
        int total = data.optInt("total");
        int finished = data.optInt("finished");
        this.tv_course_count.setText(String.valueOf(total));
        this.tv_course_finished.setText(String.valueOf(finished));
        this.view_course_finish.setVisibility(total == finished ? 0 : 8);
        this.viewCourseProgress.setMax(total);
        this.viewCourseProgress.setProgress(finished);
        this.imageLoader.displayImage(data.optString("pic_url"), this.iv_header_bg,
                ImageLoaderOptions.randomColor());
        List<CourseInfo> courseInfos = FastJsonUtils.parseList(data.optString("sports_days"),
                CourseInfo.class);
        if (courseInfos != null && courseInfos.size() != 0) {
            this.mDataList.clear();
            this.mDataList.addAll(courseInfos);
            int todayID = data.optInt("today_id");
            int index = 1;
            List<FinishedCourseDay> finishedDayList = FastJsonUtils.parseList(data.optString
                    ("finish_days"), FinishedCourseDay.class);
            for (CourseInfo course : this.mDataList) {
                for (CourseItemInfo item : course.items) {
                    int index2 = index + 1;
                    item.index = index;
                    item.download = DownloadHelper.getInstance().hasDownload(item.video_url);
                    if (item.id == todayID) {
                        item.today = true;
                        if (this.mTabIndex == 0) {
                            this.mTabIndex = this.mDataList.indexOf(course);
                        }
                    } else {
                        item.today = false;
                    }
                    if (finishedDayList != null && finishedDayList.size() > 0) {
                        for (FinishedCourseDay day : finishedDayList) {
                            if (item.id == day.id) {
                                item.date = day.date;
                            }
                        }
                    }
                    index = index2;
                }
            }
            initView();
        }
    }
}
 
Example 15
Project: limitjson   File: MainActivity.java   View Source Code Vote up 4 votes
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Entity$$CREATOR.create("", false);
    limitJsonTv = (TextView) findViewById(R.id.limitjson_ms);
    try {
        JSONObject root = new JSONObject("");
        root.opt("");
        root.optInt("");
        root.optBoolean("");
        root.optLong("");
        float aa = (float) root.optDouble("");
        root.optString("");

        root.optJSONObject("");
        root.optJSONArray("");
        int[] a;
        if (root.has("arr")) {
            JSONArray array = root.optJSONArray("");
            int size = array.length();
            a = new int[size];
            for (int i = 0; i < size; i++) {
                a[i] = array.optInt(i);
            }
        }


    } catch (JSONException e) {
        e.printStackTrace();
    }

    testLimitJson();

    LinearGraphView tu = (LinearGraphView) findViewById(R.id.line_graphic);

    ArrayList<Double> yList = new ArrayList<Double>();
    yList.add((double) 2.103);
    yList.add(4.05);
    yList.add(6.60);
    yList.add(3.08);
    yList.add(4.32);
    yList.add(2.0);
    yList.add(1115.0);

    ArrayList<String> xRawDatas = new ArrayList<String>();
    xRawDatas.add("05-19");
    xRawDatas.add("05-20");
    xRawDatas.add("05-21");
    xRawDatas.add("05-22");
    xRawDatas.add("05-23");
    xRawDatas.add("05-24");
    xRawDatas.add("05-25");
    xRawDatas.add("05-26");
    tu.setData(yList, xRawDatas, 8, 2);
}
 
Example 16
Project: boohee_v5.6   File: MeiQiaService.java   View Source Code Vote up 4 votes
private void a(JSONObject jSONObject) {
    JSONObject optJSONObject = jSONObject.optJSONObject("body");
    if (optJSONObject != null) {
        a(c.a(optJSONObject));
    }
}
 
Example 17
Project: pullstring-android   File: Response.java   View Source Code Vote up 4 votes
public Response(JSONObject json) {
    // status defaults to success
    mStatus = new Status();
    JSONObject error = json.optJSONObject(Keys.Error);
    if (error != null) {
        mStatus.setSuccess(false);
        mStatus.setErrorMessage(error.optString(Keys.Message, "Unknown Error"));
        mStatus.setStatusCode(error.optInt(Keys.Status, 500));
    }

    // top-level JSON properties
    mConversationId = json.optString(Keys.ConversationId);
    mParticipantId = json.optString(Keys.ParticipantId);
    mETag = json.optString(Keys.ETag);
    mAsrHypothesis = json.optString(Keys.AsrHypothesis);
    mEndpoint = json.optString(Keys.EndpointHeader);
    mTimedResponseInterval = json.optDouble(Keys.TimedResponseInterval, 0);

    // last modified
    String interval = json.optString(Keys.LastModified);
    if (!interval.isEmpty()) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);
        try {
            mLastModified = dateFormat.parse(interval);
        } catch (ParseException e) {
            e.printStackTrace();
            mLastModified = null;
        }
    }

    // outputs
    mOutputs = new ArrayList<>();
    JSONArray outputs = json.optJSONArray(Keys.Outputs);
    if (outputs != null) {
        for (int i = 0; i < outputs.length(); i++) {
            JSONObject output = outputs.optJSONObject(i);
            if (output == null || !output.has(Keys.OutputType)) {
                continue;
            }

            String type = output.optString(Keys.OutputType);

            if (type.equals(OutputType.BEHAVIOR.toString())) {
                mOutputs.add(new BehaviorOutput(output));
            } else if (type.equals(OutputType.DIALOG.toString())) {
                mOutputs.add(new DialogOutput(output));
            }
        }
    }

    // entities -- convert from JSON dictionary to an array
    mEntities = new ArrayList<>();
    JSONObject entities = json.optJSONObject(Keys.Entities);
    if (entities != null) {
        Iterator<String> keys = entities.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            Object entity = entities.opt(key);

            if (entity == null) {
                continue;
            }

            if (entity instanceof String) {
                mEntities.add(new Label(key, (String)entity));
            } else if (entity instanceof JSONArray) {
                JSONArray arr = (JSONArray) entity;
                ArrayList<Object> list = new ArrayList<>();
                for (int i = 0; i < arr.length(); i++) {
                    Object item = arr.opt(i);
                    if (item != null) list.add(item);
                }
                mEntities.add(new List(key, list));
            } else if (entity instanceof Boolean) {
                mEntities.add(new Flag(key, (boolean)entity));
            } else if (entity instanceof Number) {
                mEntities.add(new Counter(key, ((Number)entity).doubleValue()));
            }
        }
    }
}
 
Example 18
Project: Simpler   File: SearchActivity.java   View Source Code Vote up 4 votes
public void queryDailyHotTopic(String nextPage, final boolean refresh) {
        String url;
        if (nextPage == null) {
            url = TOPIC_URL;
        } else {
            url = TOPIC_URL + "&since_id=" + nextPage;
        }

        if (!TextUtils.isEmpty(mCookie)) {
            HttpGetTask task = new HttpGetTask(true, new HttpListener() {
                @Override
                public void onResponse(String response) {
                    mSwipeRefresh.setRefreshing(false);
//                    Log.d("Topic", response);
                    if (!TextUtils.isEmpty(response)) {
                        try {
                            List<Topic> topicList = new ArrayList<>();
                            JSONObject obj = new JSONObject(response);
                            JSONArray cards = obj.optJSONArray("cards");
                            JSONObject cardlistInfo = obj.optJSONObject("cardlistInfo");
                            if (cardlistInfo != null) {
                                mNextPage = cardlistInfo.optString("since_id", null);
                            } else {
                                mNextPage = null;
                            }
                            if (cards != null && cards.length() > 0) {
                                JSONArray array = cards.optJSONObject(0).optJSONArray("card_group");
                                if (array != null && array.length() > 0) {
                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject topic = array.optJSONObject(i);
                                        topicList.add(Topic.parse(topic));
                                    }
                                }
                            }
                            if (refresh) {
                                mAdapter.setTopics(topicList);
                            } else {
                                mAdapter.addTopics(topicList);
                            }
                            if (mNextPage != null) {
                                mAdapter.setFooterInfo(getString(R.string.pull_up_to_load_more));
                            } else {
                                mAdapter.setFooterInfo(getString(R.string.no_more_data));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            AppToast.showToast(R.string.update_web_wb_cookie);
                            startActivity(WebWBActivity.newIntent(SearchActivity.this, true));
                        }
                    }
                }

                @Override
                public void onFailure() {
                    mSwipeRefresh.setRefreshing(false);
                    AppToast.showToast("获取热门话题失败");
                }
            });
            task.execute(url, mCookie);
            registerAsyncTask(SearchActivity.class, task);
        } else {
            // Cookie为空
            mSwipeRefresh.setRefreshing(false);
        }
    }
 
Example 19
Project: Weather-Android   File: MainActivity.java   View Source Code Vote up 4 votes
public ParseResult parseLongTermJson(String result) {
    int i;
    try {
        JSONObject reader = new JSONObject(result);

        final String code = reader.optString("cod");
        if ("404".equals(code)) {
            if (longTermWeather == null) {
                longTermWeather = new ArrayList<>();
                longTermTodayWeather = new ArrayList<>();
                longTermTomorrowWeather = new ArrayList<>();
            }
            return ParseResult.CITY_NOT_FOUND;
        }

        longTermWeather = new ArrayList<>();
        longTermTodayWeather = new ArrayList<>();
        longTermTomorrowWeather = new ArrayList<>();

        JSONArray list = reader.getJSONArray("list");
        for (i = 0; i < list.length(); i++) {
            Weather weather = new Weather();

            JSONObject listItem = list.getJSONObject(i);
            JSONObject main = listItem.getJSONObject("main");

            weather.setDate(listItem.getString("dt"));
            weather.setTemperature(main.getString("temp"));
            weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
            JSONObject windObj = listItem.optJSONObject("wind");
            if (windObj != null) {
                weather.setWind(windObj.getString("speed"));
                weather.setWindDirectionDegree(windObj.getDouble("deg"));
            }
            weather.setPressure(main.getString("pressure"));
            weather.setHumidity(main.getString("humidity"));

            JSONObject rainObj = listItem.optJSONObject("rain");
            String rain = "";
            if (rainObj != null) {
                rain = getRainString(rainObj);
            } else {
                JSONObject snowObj = listItem.optJSONObject("snow");
                if (snowObj != null) {
                    rain = getRainString(snowObj);
                } else {
                    rain = "0";
                }
            }
            weather.setRain(rain);

            final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
            weather.setId(idString);

            final String dateMsString = listItem.getString("dt") + "000";
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(Long.parseLong(dateMsString));
            weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));

            Calendar today = Calendar.getInstance();
            if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
                longTermTodayWeather.add(weather);
            } else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
                longTermTomorrowWeather.add(weather);
            } else {
                longTermWeather.add(weather);
            }
        }
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
        editor.putString("lastLongterm", result);
        editor.commit();
    } catch (JSONException e) {
        Log.e("JSONException Data", result);
        e.printStackTrace();
        return ParseResult.JSON_EXCEPTION;
    }

    return ParseResult.OK;
}
 
Example 20
Project: atlas   File: AnimatableTransform.java   View Source Code Vote up 4 votes
static AnimatableTransform newInstance(JSONObject json, LottieComposition composition) {
  AnimatablePathValue anchorPoint = null;
  AnimatableValue<PointF> position = null;
  AnimatableScaleValue scale;
  AnimatableFloatValue rotation = null;
  AnimatableIntegerValue opacity;
  JSONObject anchorJson = json.optJSONObject("a");
  if (anchorJson != null) {
    anchorPoint = new AnimatablePathValue(anchorJson.opt("k"), composition);
  } else {
    throwMissingTransform("anchor");
  }

  JSONObject positionJson = json.optJSONObject("p");
  if (positionJson != null) {
    position =
        AnimatablePathValue.createAnimatablePathOrSplitDimensionPath(positionJson, composition);
  } else {
    throwMissingTransform("position");
  }

  JSONObject scaleJson = json.optJSONObject("s");
  if (scaleJson != null) {
    scale = AnimatableScaleValue.Factory.newInstance(scaleJson, composition);
  } else {
    // Somehow some community animations don't have scale in the transform.
    scale = new AnimatableScaleValue(Collections.<Keyframe<ScaleXY>>emptyList(), new ScaleXY());
  }

  JSONObject rotationJson = json.optJSONObject("r");
  if (rotationJson == null) {
    rotationJson = json.optJSONObject("rz");
  }
  if (rotationJson != null) {
    rotation = AnimatableFloatValue.Factory.newInstance(rotationJson, composition, false);
  } else {
    throwMissingTransform("rotation");
  }

  JSONObject opacityJson = json.optJSONObject("o");
  if (opacityJson != null) {
    opacity = AnimatableIntegerValue.Factory.newInstance(opacityJson, composition);
  } else {
    // Somehow some community animations don't have opacity in the transform.
    opacity = new AnimatableIntegerValue(Collections.<Keyframe<Integer>>emptyList(), 100);
  }
  return new AnimatableTransform(anchorPoint, position, scale, rotation, opacity);
}