Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject getJSONArray.

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java

private void createFilteredDeck(JSONArray delays, Object[] terms, Boolean resched) {
    JSONObject dyn;
    if (AnkiDroidApp.colIsOpen()) {
        Collection col = AnkiDroidApp.getCol();
        try {/*w ww.ja va2 s. co m*/
            String deckName = col.getDecks().current().getString("name");
            String customStudyDeck = getResources().getString(R.string.custom_study_deck_name);
            JSONObject cur = col.getDecks().byName(customStudyDeck);
            if (cur != null) {
                if (cur.getInt("dyn") != 1) {
                    StyledDialog.Builder builder = new StyledDialog.Builder(getActivity());
                    builder.setMessage(R.string.custom_study_deck_exists);
                    builder.setNegativeButton(getResources().getString(R.string.cancel), new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //
                        }
                    });
                    builder.create().show();
                    return;
                } else {
                    // safe to empty
                    col.getSched().emptyDyn(cur.getLong("id"));
                    // reuse; don't delete as it may have children
                    dyn = cur;
                    col.getDecks().select(cur.getLong("id"));
                }
            } else {
                long did = col.getDecks().newDyn(customStudyDeck);
                dyn = col.getDecks().get(did);
            }
            // and then set various options
            dyn.put("delays", delays);
            JSONArray ar = dyn.getJSONArray("terms");
            ar.getJSONArray(0).put(0,
                    new StringBuilder("deck:\"").append(deckName).append("\" ").append(terms[0]).toString());
            ar.getJSONArray(0).put(1, terms[1]);
            ar.getJSONArray(0).put(2, terms[2]);
            dyn.put("resched", resched);

            if (mFragmented) {
                Bundle config = new Bundle();
                config.putString("searchSuffix", "'deck:" + dyn.getString("name") + "'");
                initAllContentViews(getLayoutInflater(config));
                finishCongrats();
            } else {
                // Load a new fragment with the filtered deck view. The config passed is null, so it uses the
                // current deck. The deck we just created is internally set as the current deck.
                ((StudyOptionsActivity) getActivity()).loadContent(false, null);
            }

            // Initial rebuild
            mProgressDialog = StyledProgressDialog.show(getActivity(), "",
                    getResources().getString(R.string.rebuild_custom_study_deck), true);
            DeckTask.launchDeckTask(DeckTask.TASK_TYPE_REBUILD_CRAM, mRebuildCustomStudyListener,
                    new DeckTask.TaskData(AnkiDroidApp.getCol(), AnkiDroidApp.getCol().getDecks().selected(),
                            mFragmented));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:org.runnerup.export.format.RunKeeper.java

public static ActivityEntity parseToActivity(JSONObject response, double unitMeters) throws JSONException {
    ActivityEntity newActivity = new ActivityEntity();
    newActivity.setSport(RunKeeperSynchronizer.runkeeper2sportMap.get(response.getString("type")).getDbValue());
    if (response.has("notes")) {
        newActivity.setComment(response.getString("notes"));
    }/*  w  w  w. ja v  a 2s.co  m*/
    newActivity.setTime((long) Float.parseFloat(response.getString("duration")));
    newActivity.setDistance(Float.parseFloat(response.getString("total_distance")));

    String startTime = response.getString("start_time");
    SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US);
    try {
        newActivity.setStartTime(format.parse(startTime));
    } catch (ParseException e) {
        Log.e(Constants.LOG, e.getMessage());
        return null;
    }

    List<LapEntity> laps = new ArrayList<LapEntity>();
    List<LocationEntity> locations = new ArrayList<LocationEntity>();

    JSONArray distance = response.getJSONArray("distance");
    JSONArray path = response.getJSONArray("path");
    JSONArray hr = response.getJSONArray("heart_rate");

    SortedMap<Long, HashMap<String, String>> pointsValueMap = createPointsMap(distance, path, hr);
    Iterator<Map.Entry<Long, HashMap<String, String>>> points = pointsValueMap.entrySet().iterator();

    //lap hr
    int maxHr = 0;
    int sumHr = 0;
    int count = 0;
    //point speed
    long time = 0;
    float meters = 0.0f;
    //activity hr
    int maxHrOverall = 0;
    int sumHrOverall = 0;
    int countOverall = 0;

    while (points.hasNext()) {
        Map.Entry<Long, HashMap<String, String>> timePoint = points.next();
        HashMap<String, String> values = timePoint.getValue();

        LocationEntity lv = new LocationEntity();
        lv.setActivityId(newActivity.getId());
        lv.setTime(TimeUnit.SECONDS.toMillis(newActivity.getStartTime()) + timePoint.getKey());

        String dist = values.get("distance");
        if (dist == null) {
            continue;
        }
        String lat = values.get("latitude");
        String lon = values.get("longitude");
        String alt = values.get("altitude");
        String heart = values.get("heart_rate");
        String type = values.get("type");

        if (lat == null || lon == null) {
            continue;
        } else {
            lv.setLatitude(Double.valueOf(lat));
            lv.setLongitude(Double.valueOf(lon));
        }
        if (alt != null) {
            lv.setAltitude(Double.valueOf(alt));
        }

        if (pointsValueMap.firstKey().equals(timePoint.getKey())) {
            lv.setType(DB.LOCATION.TYPE_START);
        } else if (!points.hasNext()) {
            lv.setType(DB.LOCATION.TYPE_END);
        } else if (type != null) {
            lv.setType(RunKeeperSynchronizer.POINT_TYPE.get(type));
        }
        // lap and activity max and avg hr
        if (heart != null) {
            lv.setHr(Integer.valueOf(heart));
            maxHr = Math.max(maxHr, lv.getHr());
            maxHrOverall = Math.max(maxHrOverall, lv.getHr());
            sumHr += lv.getHr();
            sumHrOverall += lv.getHr();
            count++;
            countOverall++;
        }

        meters = Float.valueOf(dist) - meters;
        time = timePoint.getKey() - time;
        if (time > 0) {
            float speed = meters / (float) TimeUnit.MILLISECONDS.toSeconds(time);
            BigDecimal s = new BigDecimal(speed);
            s = s.setScale(2, BigDecimal.ROUND_UP);
            lv.setSpeed(s.floatValue());
        }

        // create lap if distance greater than configured lap distance

        if (Float.valueOf(dist) >= unitMeters * laps.size()) {
            LapEntity newLap = new LapEntity();
            newLap.setLap(laps.size());
            newLap.setDistance(Float.valueOf(dist));
            newLap.setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()));
            newLap.setActivityId(newActivity.getId());
            laps.add(newLap);

            // update previous lap with duration and distance
            if (laps.size() > 1) {
                LapEntity previousLap = laps.get(laps.size() - 2);
                previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance());
                previousLap.setTime(
                        (int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime());

                if (hr != null && hr.length() > 0) {
                    previousLap.setMaxHr(maxHr);
                    previousLap.setAvgHr(sumHr / count);
                }
                maxHr = 0;
                sumHr = 0;
                count = 0;
            }
        }
        // update last lap with duration and distance
        if (!points.hasNext()) {
            LapEntity previousLap = laps.get(laps.size() - 1);
            previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance());
            previousLap
                    .setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime());

            if (hr != null && hr.length() > 0) {
                previousLap.setMaxHr(maxHr);
                previousLap.setAvgHr(sumHr / count);
            }
        }

        lv.setLap(laps.size() - 1);

        locations.add(lv);
    }
    // calculate avg and max hr
    // update the activity
    newActivity.setMaxHr(maxHrOverall);
    if (countOverall > 0) {
        newActivity.setAvgHr(sumHrOverall / countOverall);
    }

    newActivity.putPoints(locations);
    newActivity.putLaps(laps);

    return newActivity;
}

From source file:com.seunghyo.sunshine.FetchWeatherTask.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.// ww w . j a v  a2 s  .  co m
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
        }

        // Sort order:  Ascending, by date.
        String sortOrder = WeatherEntry.COLUMN_DATE + " ASC";
        Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting,
                System.currentTimeMillis());

        // Students: Uncomment the next lines to display what what you stored in the bulkInsert

        //            Cursor cur = mContext.getContentResolver().query(weatherForLocationUri,
        //                    null, null, null, sortOrder);
        //
        //            cVVector = new Vector<ContentValues>(cur.getCount());
        //            if ( cur.moveToFirst() ) {
        //                do {
        //                    ContentValues cv = new ContentValues();
        //                    DatabaseUtils.cursorRowToContentValues(cur, cv);
        //                    cVVector.add(cv);
        //                } while (cur.moveToNext());
        //            }

        Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted");

        String[] resultStrs = convertContentValuesToUXFormat(cVVector);
        return resultStrs;

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}

From source file:cn.newgxu.android.notty.service.FetchService.java

@Override
protected void onHandleIntent(Intent intent) {
    //      int method = intent.getIntExtra("method", RESTMethod.GET);
    //      switch (method) {
    //      case RESTMethod.GET:
    //         break;
    //      case RESTMethod.POST:
    //         Map<String, Object> params = new HashMap<String, Object>();
    //         params.put(C.notice.TITLE, intent.getStringExtra(C.notice.TITLE));
    //         params.put(C.notice.CONTENT, intent.getStringExtra(C.notice.CONTENT));
    //         L.d(TAG, "post result: %s", result);
    //         ContentValues values = new ContentValues();
    //         values.put(C.notice.TITLE, intent.getStringExtra(C.notice.TITLE));
    //         values.put(C.notice.CONTENT, intent.getStringExtra(C.notice.CONTENT));
    //         getContentResolver().insert(Uri.parse(C.BASE_URI + C.NOTICES), values);
    //         return;
    //      default:
    //         break;
    //      }//from  w ww  .j  a v  a 2  s .c o m
    if (NetworkUtils.connected(getApplicationContext())) {
        Cursor c = getContentResolver().query(Uri.parse(C.BASE_URI + C.NOTICES), C.notice.LATEST_NOTICE_ID,
                null, null, null);
        String uri = intent.getStringExtra(C.URI);
        if (c.moveToNext()) {
            uri += "&local_nid=" + c.getLong(0);
        }
        Log.d(TAG, String.format("uri: %s", uri));
        JSONObject result = RESTMethod.get(uri);
        L.d(TAG, "json: %s", result);
        try {
            JSONArray notices = result.getJSONArray(C.NOTICES);
            ContentValues[] noticeValues = new ContentValues[notices.length()];
            ContentValues[] userValues = new ContentValues[notices.length()];
            for (int i = 0; i < userValues.length; i++) {
                JSONObject n = notices.getJSONObject(i);
                JSONObject u = n.getJSONObject(C.USER);
                noticeValues[i] = Processor.json2Notice(n);
                userValues[i] = Processor.json2User(u);
            }
            String[] uris = intent.getStringArrayExtra("uris");
            getContentResolver().bulkInsert(Uri.parse(uris[0]), noticeValues);
            getContentResolver().bulkInsert(Uri.parse(uris[1]), userValues);

            final int newerCount = notices.length();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), getString(R.string.newer_count, newerCount),
                            Toast.LENGTH_SHORT).show();
                }
            });
        } catch (JSONException e) {
            throw new RuntimeException("ERROR when resolving json -> " + result, e);
        }
    } else {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), R.string.network_down, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

From source file:net.chunkyhosting.Roe.computer.CHGManager.gui.panels.ServerList.java

public void retriveServerList() {

    try {//from ww w . j av a  2  s  . c  om

        JSONObject json = CHGManager.getInstance().getGameCPX()
                .performAPICall(new String[] { "command", "service_list" });
        for (int x = 0; x < json.getJSONArray("result").length(); x++) {

            JSONObject server = json.getJSONArray("result").getJSONObject(x);
            Server theServer = new Server();
            ServerDisplay test = new ServerDisplay(server);
            test.setBorder(BorderFactory.createTitledBorder("Server 1"));
            test.setAlignmentX(Component.CENTER_ALIGNMENT);
            test.setMaximumSize(new Dimension(99999, 80));
            add(test);

        }

        /*ServerDisplay test2 = new ServerDisplay();
        test2.setBorder(BorderFactory.createTitledBorder("Server 2"));
        test2.setAlignmentX(Component.CENTER_ALIGNMENT);
        test2.setMaximumSize(new Dimension(99999, 70));
        add(test2);*/

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();

    } catch (EmptyAPIResponseException e) {

        e.printStackTrace();

    }

}

From source file:com.goliathonline.android.kegbot.io.RemoteKegsHandler.java

/** {@inheritDoc} */
@Override// ww w  .j  a  va2s  . c o  m
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {

    if (parser.has("result")) {
        JSONObject events = parser.getJSONObject("result");
        JSONArray resultArray = events.getJSONArray("kegs");
        int numKegs = resultArray.length();
        List<String> kegIDs = new ArrayList<String>();

        JSONObject keg, kegInfo;
        for (int i = 0; i < numKegs; i++) {
            keg = resultArray.getJSONObject(i);
            kegInfo = keg.getJSONObject("keg");
            kegIDs.add(kegInfo.getString("id"));
            ///TODO: new api allows all infromation to be parsed here, and not in a seperate call.
        }
        considerUpdate(kegIDs, Kegs.CONTENT_URI, resolver);
    }

    return Lists.newArrayList();
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createSearchDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_search_tools,
            R.string.search_tools_title);

    final ScrollView scrollView = (ScrollView) dialog.findViewById(R.id.search_tools_dialog_scroll_view);
    final AutoCompleteTextView inputField = (AutoCompleteTextView) dialog
            .findViewById(R.id.search_tools_input_field);
    final LinearLayout rowsContainer = (LinearLayout) dialog.findViewById(R.id.search_tools_row_container);
    final Button viewInMapButton = (Button) dialog.findViewById(R.id.search_tools_view_in_map_button);
    final Button jumpToBottomButton = (Button) dialog.findViewById(R.id.search_tools_jump_to_bottom_button);
    Button dismissButton = (Button) dialog.findViewById(R.id.search_tools_dismiss_button);

    List<PropertyDescription> subscribables;
    PropertyDescription newestSubscribable = null;
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",
            Locale.getDefault());
    Date cachedUpdateDateTime;//w  w w  . jav a  2  s  .c o  m
    Date newestUpdateDateTime;
    SubscriptionEntry cachedEntry;
    Response response;
    final JSONArray toolsArray;
    ArrayAdapter<String> adapter;
    String format = "JSON";
    String downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString() + "/FiskInfo/Offline/";
    final JSONObject tools;
    final List<String> vesselNames;
    final Map<String, List<Integer>> toolIdMap = new HashMap<>();
    byte[] data = new byte[0];

    cachedEntry = user.getSubscriptionCacheEntry(getString(R.string.fishing_facility_api_name));

    if (fiskInfoUtility.isNetworkAvailable(getActivity())) {
        subscribables = barentswatchApi.getApi().getSubscribable();
        for (PropertyDescription subscribable : subscribables) {
            if (subscribable.ApiName.equals(getString(R.string.fishing_facility_api_name))) {
                newestSubscribable = subscribable;
                break;
            }
        }
    } else if (cachedEntry == null) {
        Dialog infoDialog = dialogInterface.getAlertDialog(getActivity(), R.string.tools_search_no_data_title,
                R.string.tools_search_no_data, -1);

        infoDialog.show();
        return;
    }

    if (cachedEntry != null) {
        try {
            cachedUpdateDateTime = simpleDateFormat
                    .parse(cachedEntry.mLastUpdated.equals(getActivity().getString(R.string.abbreviation_na))
                            ? "2000-00-00T00:00:00"
                            : cachedEntry.mLastUpdated);
            newestUpdateDateTime = simpleDateFormat
                    .parse(newestSubscribable != null ? newestSubscribable.LastUpdated : "2000-00-00T00:00:00");

            if (cachedUpdateDateTime.getTime() - newestUpdateDateTime.getTime() < 0) {
                response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
                try {
                    data = FiskInfoUtility.toByteArray(response.getBody().in());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                        newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath,
                        false)) {
                    SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
                    entry.mLastUpdated = newestSubscribable.LastUpdated;
                    user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
                    user.writeToSharedPref(getActivity());
                }
            } else {
                String directoryFilePath = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()
                        + "/FiskInfo/Offline/";

                File file = new File(directoryFilePath + newestSubscribable.Name + ".JSON");
                StringBuilder jsonString = new StringBuilder();
                BufferedReader bufferReader = null;

                try {
                    bufferReader = new BufferedReader(new FileReader(file));
                    String line;

                    while ((line = bufferReader.readLine()) != null) {
                        jsonString.append(line);
                        jsonString.append('\n');
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bufferReader != null) {
                        try {
                            bufferReader.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                data = jsonString.toString().getBytes();
            }

        } catch (ParseException e) {
            e.printStackTrace();
            Log.e(TAG, "Invalid datetime provided");
        }
    } else {
        response = barentswatchApi.getApi().geoDataDownload(newestSubscribable.ApiName, format);
        try {
            data = FiskInfoUtility.toByteArray(response.getBody().in());
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (new FiskInfoUtility().writeMapLayerToExternalStorage(getActivity(), data,
                newestSubscribable.Name.replace(",", "").replace(" ", "_"), format, downloadPath, false)) {
            SubscriptionEntry entry = new SubscriptionEntry(newestSubscribable, true);
            entry.mLastUpdated = newestSubscribable.LastUpdated;
            user.setSubscriptionCacheEntry(newestSubscribable.ApiName, entry);
        }
    }

    try {
        tools = new JSONObject(new String(data));
        toolsArray = tools.getJSONArray("features");
        vesselNames = new ArrayList<>();
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, vesselNames);

        for (int i = 0; i < toolsArray.length(); i++) {
            JSONObject feature = toolsArray.getJSONObject(i);
            String vesselName = (feature.getJSONObject("properties").getString("vesselname") != null
                    && !feature.getJSONObject("properties").getString("vesselname").equals("null"))
                            ? feature.getJSONObject("properties").getString("vesselname")
                            : getString(R.string.vessel_name_unknown);
            List<Integer> toolsIdList = toolIdMap.get(vesselName) != null ? toolIdMap.get(vesselName)
                    : new ArrayList<Integer>();

            if (vesselName != null && !vesselNames.contains(vesselName)) {
                vesselNames.add(vesselName);
            }

            toolsIdList.add(i);
            toolIdMap.put(vesselName, toolsIdList);
        }

        inputField.setAdapter(adapter);
    } catch (JSONException e) {
        dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                R.string.search_tools_init_info, -1).show();
        Log.e(TAG, "JSON parse error");
        e.printStackTrace();

        return;
    }

    if (searchToolsButton.getTag() != null) {
        inputField.requestFocus();
        inputField.setText(searchToolsButton.getTag().toString());
        inputField.selectAll();
    }

    inputField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String selectedVesselName = ((TextView) view).getText().toString();
            List<Integer> selectedTools = toolIdMap.get(selectedVesselName);
            Gson gson = new Gson();
            String toolSetDateString;
            Date toolSetDate;

            rowsContainer.removeAllViews();

            for (int toolId : selectedTools) {
                JSONObject feature;
                Feature toolFeature;

                try {
                    feature = toolsArray.getJSONObject(toolId);

                    if (feature.getJSONObject("geometry").getString("type").equals("LineString")) {
                        toolFeature = gson.fromJson(feature.toString(), LineFeature.class);
                    } else {
                        toolFeature = gson.fromJson(feature.toString(), PointFeature.class);
                    }

                    toolSetDateString = toolFeature.properties.setupdatetime != null
                            ? toolFeature.properties.setupdatetime
                            : "2038-00-00T00:00:00";
                    toolSetDate = simpleDateFormat.parse(toolSetDateString);

                } catch (JSONException | ParseException e) {
                    dialogInterface.getAlertDialog(getActivity(), R.string.search_tools_init_error,
                            R.string.search_tools_init_info, -1).show();
                    e.printStackTrace();

                    return;
                }

                ToolSearchResultRow row = rowsInterface.getToolSearchResultRow(getActivity(),
                        R.drawable.ikon_kystfiske, toolFeature);
                long toolTime = System.currentTimeMillis() - toolSetDate.getTime();
                long highlightCutoff = ((long) getResources().getInteger(R.integer.milliseconds_in_a_day))
                        * ((long) getResources().getInteger(R.integer.days_to_highlight_active_tool));

                if (toolTime > highlightCutoff) {
                    int colorId = ContextCompat.getColor(getActivity(), R.color.error_red);
                    row.setDateTextViewTextColor(colorId);
                }

                rowsContainer.addView(row.getView());
            }

            viewInMapButton.setEnabled(true);
            inputField.setTag(selectedVesselName);
            searchToolsButton.setTag(selectedVesselName);
            jumpToBottomButton.setVisibility(View.VISIBLE);
            jumpToBottomButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            scrollView.scrollTo(0, rowsContainer.getBottom());
                        }
                    });
                }
            });

        }
    });

    viewInMapButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String vesselName = inputField.getTag().toString();
            highlightToolsInMap(vesselName);

            dialog.dismiss();
        }
    });

    dismissButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    dialog.show();
}

From source file:net.zorgblub.typhon.dto.PageOffsets.java

public static PageOffsets fromJSON(String json) throws JSONException {
    JSONObject offsetsObject = new JSONObject(json);
    PageOffsets result = new PageOffsets();

    result.fontFamily = offsetsObject.getString(Fields.fontFamily.name());
    result.fontSize = offsetsObject.getInt(Fields.fontSize.name());
    result.vMargin = offsetsObject.getInt(Fields.vMargin.name());
    result.hMargin = offsetsObject.getInt(Fields.hMargin.name());
    result.lineSpacing = offsetsObject.getInt(Fields.lineSpacing.name());
    result.fullScreen = offsetsObject.getBoolean(Fields.fullScreen.name());
    result.algorithmVersion = offsetsObject.optInt(Fields.algorithmVersion.name(), -1);
    result.allowStyling = offsetsObject.optBoolean(Fields.allowStyling.name(), true);

    result.offsets = readOffsets(offsetsObject.getJSONArray(Fields.offsets.name()));

    return result;
}

From source file:com.cooperok.socialuser.fb.FbAccount.java

@Override
public void checkLikePage(String pageId, final LikeCallback callback) {
    new Request(Session.getActiveSession(), "/me/likes/" + pageId, null, HttpMethod.GET,
            new Request.Callback() {
                public void onCompleted(Response response) {
                    boolean result = false;

                    GraphObject object = response.getGraphObject();
                    if (object != null) {
                        JSONObject resp = object.getInnerJSONObject();
                        if (resp != null) {
                            try {
                                JSONArray data = resp.getJSONArray("data");
                                if (data.length() > 0) {
                                    result = true;
                                }//from   w w w . j av  a 2s  .  co m
                            } catch (JSONException e) {
                            }
                        }
                    }
                    callback.onLikeChecked(result);
                }
            }).executeAsync();
}

From source file:be.brunoparmentier.openbikesharing.app.parsers.BikeNetworksListParser.java

public BikeNetworksListParser(String toParse) throws ParseException {
    bikeNetworks = new ArrayList<>();

    try {//from  www  .  j  a v  a  2s .  c om
        JSONObject jsonObject = new JSONObject(toParse);
        JSONArray rawNetworks = jsonObject.getJSONArray("networks");
        for (int i = 0; i < rawNetworks.length(); i++) {
            JSONObject rawNetwork = rawNetworks.getJSONObject(i);

            String id = rawNetwork.getString("id");
            String name = rawNetwork.getString("name");
            String company = rawNetwork.getString("company");
            BikeNetworkLocation location;

            /* network location */
            {
                JSONObject rawLocation = rawNetwork.getJSONObject("location");

                double latitude = rawLocation.getDouble("latitude");
                double longitude = rawLocation.getDouble("longitude");
                String city = rawLocation.getString("city");
                String country = rawLocation.getString("country");

                location = new BikeNetworkLocation(latitude, longitude, city, country);

            }
            bikeNetworks.add(new BikeNetworkInfo(id, name, company, location));
        }
    } catch (JSONException e) {
        throw new ParseException("Error parsing JSON", 0);
    }
}