Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:org.cgiar.ilri.odk.pull.backend.services.FetchFormDataService.java

/**
 * This method is called whenever the service is called. Note that the service might have
 * already been running when it was called
 *
 * @param intent The intent used to call the service
 *///from  w w w .ja va2 s .  c o  m
@Override
protected void onHandleIntent(Intent intent) {
    formName = intent.getStringExtra(KEY_FORM_NAME);
    if (formName != null) {
        //fetch data on the form
        try {
            String jsonString = DataHandler.sendDataToServer(this, null,
                    DataHandler.URI_FETCH_FORM_DATA + URLEncoder.encode(formName, "UTF-8"));
            if (jsonString != null) {
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    JSONObject fileData = jsonObject.getJSONObject("files");
                    Iterator<String> keys = fileData.keys();
                    String fetchedFilesString = "";
                    while (keys.hasNext()) {
                        String currFileName = keys.next();
                        Log.d(TAG, "Processing " + currFileName);
                        JSONArray currFileData = fileData.getJSONArray(currFileName);
                        if (currFileName.equals(Form.DEFAULT_CSV_FILE_NAME)) {
                            Log.d(TAG, "Treating " + currFileName + " like a itemset file");
                            Log.d(TAG, currFileName + " data = " + currFileData.toString());
                            String csv = getCSVString(currFileData);
                            if (csv != null) {
                                saveCSVInFile(currFileName + Form.SUFFIX_CSV, csv);
                                fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName
                                        + Form.SUFFIX_CSV;
                            } else {
                                Log.w(TAG, Form.DEFAULT_CSV_FILE_NAME
                                        + " from the server is null. Unable to save this on the device");
                                Toast.makeText(FetchFormDataService.this,
                                        getResources().getText(R.string.unable_fetch_data_for) + " "
                                                + currFileName,
                                        Toast.LENGTH_LONG).show();

                            }
                        } else {
                            Log.d(TAG, "Treating " + currFileName + " like an external data file");
                            boolean dataDumped = saveDataInDb(currFileName, currFileData);
                            String csv = getCSVString(currFileData);
                            if (csv != null) {
                                if (dataDumped) {
                                    saveCSVInFile(currFileName + Form.SUFFIX_CSV + Form.SUFFIX_IMPORTED, csv);
                                    fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName
                                            + Form.SUFFIX_DB;
                                    fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName
                                            + Form.SUFFIX_CSV + Form.SUFFIX_IMPORTED;
                                } else {
                                    saveCSVInFile(currFileName + Form.SUFFIX_CSV, csv);
                                    fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName
                                            + Form.SUFFIX_CSV;
                                }
                            } else {
                                Log.w(TAG, currFileName
                                        + " from the server is null. Unable to save this on the device");
                                Toast.makeText(FetchFormDataService.this,
                                        getResources().getText(R.string.unable_fetch_data_for) + " "
                                                + currFileName,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                    DataHandler.updateFormLastUpdateTime(FetchFormDataService.this, formName);
                    if (fetchedFilesString.length() > 0) {//only show the notification if at least one file updated
                        updateNotification(formName, getString(R.string.fetched_data),
                                getString(R.string.the_following_files_were_added) + fetchedFilesString);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e(TAG,
                        "Data from server null. Something happened while trying to fetch csv for " + formName);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    } else {
        Log.w(TAG, "Form name from intent bundle was null, doing nothing");
    }
}

From source file:org.cfr.restlet.ext.shindig.resource.MakeRequestResourceTest.java

private void assertResponseOk(int expectedStatus, String expectedBody) throws JSONException {
    ContextResource contextResource = resource.getContextResource();

    if (Status.SUCCESS_OK.equals(contextResource.getStatus())) {
        String body = contextResource.getText();
        assertStartsWith(MakeRequestHandler.UNPARSEABLE_CRUFT, body);
        body = body.substring(MakeRequestHandler.UNPARSEABLE_CRUFT.length());
        JSONObject object = new JSONObject(body);
        object = object.getJSONObject(REQUEST_URL.toString());
        assertEquals(expectedStatus, object.getInt("rc"));
        assertEquals(expectedBody, object.getString("body"));
    } else {//from   w ww.  j  a  v  a  2 s . c o  m
        fail("Invalid response for request.");
    }
}

From source file:com.abc.driver.PersonalActivity.java

public void parseJson(JSONObject jsonResult) {
    JSONObject profileJson = null;//from www. j a va2  s .  c o m
    try {
        try {
            profileJson = jsonResult.getJSONObject(CellSiteConstants.PROFILE);
        } catch (Exception e) {
            profileJson = null;
        }
        JSONObject userJson = jsonResult.getJSONObject(CellSiteConstants.USER);
        if (profileJson != null) {
            if (profileJson.get(CellSiteConstants.PROFILE_IMAGE_URL) != JSONObject.NULL) {
                Log.d(TAG, "get the image url");
                app.getUser().setProfileImageUrl(profileJson.getString(CellSiteConstants.PROFILE_IMAGE_URL));

            }
            if (profileJson.get(CellSiteConstants.DRIVER_LICENSE_URL) != JSONObject.NULL) {
                app.getUser()
                        .setDriverLicenseImageUrl(profileJson.getString(CellSiteConstants.DRIVER_LICENSE_URL));
            }
            if (profileJson.get(CellSiteConstants.IDENTITY_CARD_IMAGE_URL) != JSONObject.NULL) {
                app.getUser()
                        .setIdentityImageUrl(profileJson.getString(CellSiteConstants.IDENTITY_CARD_IMAGE_URL));
            }

            if (profileJson.get(CellSiteConstants.NAME) != JSONObject.NULL) {
                app.getUser().setName(profileJson.getString(CellSiteConstants.NAME));
            }

        }
        if (userJson.get(CellSiteConstants.MOBILE) != JSONObject.NULL) {
            app.getUser().setMobileNum(userJson.getString(CellSiteConstants.MOBILE));
        }

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

}

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./*w w  w  . j  a  va  2s.  c  o 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;
    //      }// w w w.java 2 s .co 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:com.goliathonline.android.kegbot.io.RemoteKegsHandler.java

/** {@inheritDoc} */
@Override//from  ww  w.  j  a  va2 s.co 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:com.norman0406.slimgress.API.Item.ItemModMultihack.java

public ItemModMultihack(JSONArray json) throws JSONException {
    super(ItemBase.ItemType.ModMultihack, json);

    JSONObject item = json.getJSONObject(2);
    JSONObject modResource = item.getJSONObject("modResource");
    JSONObject stats = modResource.getJSONObject("stats");
    mBurnoutInsulation = Integer.parseInt(stats.getString("BURNOUT_INSULATION"));
}

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;/*from w w  w  .j  a  v a2s  .c om*/
    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:cn.ttyhuo.activity.InfoOwnerActivity.java

protected void setupViewOfHasLogin(JSONObject jObject) {
    try {//from w  w w. j av a 2 s  .co  m

        ArrayList<String> pics = new ArrayList<String>();
        JSONArray jsonArray = jObject.optJSONArray("imageList");
        if (jsonArray != null) {
            for (int s = 0; s < jsonArray.length(); s++)
                pics.add(jsonArray.getString(s));
        }
        while (pics.size() < 3)
            pics.add("plus");
        mPicData = pics;
        mPicAdapter.updateData(pics);

        if (jObject.getBoolean("isTruckVerified")) {
            tv_edit_tips.setText("?????");
        } else if (jsonArray != null && jsonArray.length() > 2 && jObject.has("truckInfo")) {
            tv_edit_tips.setText(
                    "?????????");
        } else {
            tv_edit_tips.setText("??????");
        }

        if (jObject.has("truckInfo")) {
            JSONObject userJsonObj = jObject.getJSONObject("truckInfo");
            if (!userJsonObj.optString("licensePlate").isEmpty()
                    && userJsonObj.optString("licensePlate") != "null")
                mEditChepai.setText(userJsonObj.getString("licensePlate"));
            Integer truckType = userJsonObj.getInt("truckType");
            if (truckType != null && truckType > 0)
                mEditChexing.setText(ConstHolder.TruckTypeItems[truckType - 1]);
            else
                mEditChexing.setText("");
            if (!userJsonObj.optString("loadLimit").isEmpty() && userJsonObj.optString("loadLimit") != "null")
                mEditZaizhong.setText(userJsonObj.getString("loadLimit"));
            if (!userJsonObj.optString("truckLength").isEmpty()
                    && userJsonObj.optString("truckLength") != "null")
                mEditChechang.setText(userJsonObj.getString("truckLength"));
            if (!userJsonObj.optString("modelNumber").isEmpty()
                    && userJsonObj.optString("modelNumber") != "null")
                mEditXinghao.setText(userJsonObj.getString("modelNumber"));

            if (!userJsonObj.optString("seatingCapacity").isEmpty()
                    && userJsonObj.optString("seatingCapacity") != "null")
                mEditZuowei.setText(userJsonObj.getString("seatingCapacity"));
            if (!userJsonObj.optString("releaseYear").isEmpty()
                    && userJsonObj.optString("releaseYear") != "null")
                mEditDate.setText(userJsonObj.getString("releaseYear") + "");
            if (!userJsonObj.optString("truckWidth").isEmpty() && userJsonObj.optString("truckWidth") != "null")
                mEditKuan.setText(userJsonObj.getString("truckWidth"));
            if (!userJsonObj.optString("truckHeight").isEmpty()
                    && userJsonObj.optString("truckHeight") != "null")
                mEditGao.setText(userJsonObj.getString("truckHeight"));
        }

        if (!jObject.getBoolean("isTruckVerified")) {
            mEditChexing.setOnClickListener(this);
            mEditDate.setOnClickListener(this);
            mEditChepai.setFocusable(true);
            mEditChepai.setEnabled(true);
            mEditZaizhong.setFocusable(true);
            mEditZaizhong.setEnabled(true);
            mEditChechang.setFocusable(true);
            mEditChechang.setEnabled(true);
            mEditZuowei.setFocusable(true);
            mEditZuowei.setEnabled(true);
            mEditKuan.setFocusable(true);
            mEditKuan.setEnabled(true);
            mEditGao.setFocusable(true);
            mEditGao.setEnabled(true);
            mEditXinghao.setFocusable(true);
            mEditXinghao.setEnabled(true);
            canUpdate = true;
        } else {
            mPicGrid.setOnItemLongClickListener(null);

            mEditChepai.setFocusable(false);
            mEditChepai.setEnabled(false);
            mEditZaizhong.setFocusable(false);
            mEditZaizhong.setEnabled(false);
            mEditChechang.setFocusable(false);
            mEditChechang.setEnabled(false);
            mEditZuowei.setFocusable(false);
            mEditZuowei.setEnabled(false);
            mEditKuan.setFocusable(false);
            mEditKuan.setEnabled(false);
            mEditGao.setFocusable(false);
            mEditGao.setEnabled(false);
            mEditXinghao.setFocusable(false);
            mEditXinghao.setEnabled(false);
            canUpdate = false;
        }

        saveParams(true);

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

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

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

    try {//  www  .j a v  a 2s  .  c  o m
        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);
    }
}