Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

In this page you can find the example usage for org.json JSONArray length.

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java

private List<DownloadItem> retrieveDatabaseList(DownloadItem category) throws Exception {
    List<DownloadItem> diList = new LinkedList<DownloadItem>();
    String url = SS_API_GET_CATEGORY_CONTENT + category.getExtras("id");
    String page = category.getExtras("page");
    if (page != null) {
        url += "&page=" + page;
    } else {/*w  w  w. j  a va  2s.  co m*/
        page = "1";
    }

    JSONArray jsonArray = new JSONArray(downloadJSONString(url));
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonItem = jsonArray.getJSONObject(i);
        DownloadItem di = new DownloadItem();
        di.setType(DownloadItem.TYPE_DATABASE);
        di.setTitle(jsonItem.getString("stackName"));
        di.setDescription(jsonItem.getString("description"));
        di.setExtras("id", jsonItem.getString("id"));
        di.setAddress(SS_API_GET_DECK + jsonItem.getString("id"));
        di.setExtras("page", page);
        if (di.getTitle() != null) {
            diList.add(di);
        }
    }
    return diList;
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java

private void downloadDatabase(DownloadItem di) throws Exception {
    String url = di.getAddress();
    String jsonString = downloadJSONString(url);
    JSONObject jsonObject = new JSONObject(jsonString);
    JSONArray jsonDataArray = jsonObject.getJSONArray("data");
    List<Item> itemList = new LinkedList<Item>();
    for (int i = 0; i < jsonDataArray.length(); i++) {
        JSONArray jsonItemArray = jsonDataArray.getJSONArray(i);
        String question = jsonItemArray.getString(0);
        String answer = jsonItemArray.getString(1);
        if (question != null && !question.equals("")) {
            Item item = new Item();
            item.setQuestion(question);// ww  w. jav a2  s  . c om
            item.setAnswer(answer);
            item.setId(i + 1);
            itemList.add(item);
        }

    }
    String dbname = di.getTitle() + ".db";
    String dbpath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + getString(R.string.default_dir);
    DatabaseHelper.createEmptyDatabase(dbpath, dbname);
    DatabaseHelper dbHelper = new DatabaseHelper(this, dbpath, dbname);
    dbHelper.insertListItems(itemList);
    dbHelper.close();

}

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

/**
 * Creates a CSV string corresponding to the provided JSONArray. Indexes in JSONArray expected
 * to correspond to rows in the CSV string. Each JSONArray element should be a JSONObject with
 * children being column values (with keys being column names). Make sure all JSONObjects in the
 * JSONArray have the same number of key-value pairs.
 *
 * @param jsonArray JSONArray with the data
 * @return  The CSV string or NULL if the JSONArray is empty or if an error occurs
 *///from  ww  w .  j  a  v  a 2 s  .com
private String getCSVString(JSONArray jsonArray) {
    String csv = null;
    if (jsonArray.length() > 0) {
        try {
            csv = "";
            List<String> keys = new ArrayList<String>();
            Iterator<String> iterator = jsonArray.getJSONObject(0).keys();
            while (iterator.hasNext()) {
                String currKey = iterator.next();
                keys.add(currKey);
                if (csv.length() == 0) {
                    csv = currKey;
                } else {
                    csv = csv + "," + currKey;
                }
            }
            csv = csv + "\n";
            for (int rowIndex = 0; rowIndex < jsonArray.length(); rowIndex++) {
                JSONObject currRow = jsonArray.getJSONObject(rowIndex);
                for (int keyIndex = 0; keyIndex < keys.size(); keyIndex++) {
                    String currValue = currRow.getString(keys.get(keyIndex));
                    if (currValue != null) {
                        csv = csv + currValue;
                    }
                    if (keyIndex < keys.size() - 1) {//not the last item in row
                        csv = csv + ",";
                    }
                }
                csv = csv + "\n";//will potentially lead to having an empty last line in the csv
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        Log.w(TAG, "Provided jsonArray to be converted to CSV is empty returning null as csv");
    }
    return csv;
}

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

/**
 * Dumps data provided the rows variable into the specified database. The location of the database
 * is in the form's media folder in ODK's SDCard's folder.
 *
 * Indexes in {@param rows} are expected to correspond to rows in {@param org.cgiar.ilri.odk.pull.backend.carriers.Form.DB_DATA_TABLE} for {@param fileName}.
 * Each JSONArray element should be a JSONObject with children being column values (with keys being column names).
 * Make sure all JSONObjects in the JSONArray have the same number of key-value pairs.
 *
 * @param fileName  Then name to be given to the Database (without the .db suffix)
 * @param rows      The {@link org.json.JSONArray} object containing the data
 * @return  TRUE if database created successfully
 *///from   w  w  w. j  a  va2s  .c om
private boolean saveDataInDb(String fileName, JSONArray rows) {
    boolean result = false;
    //TODO: only do this if ODK Collect is not using this file
    String pathToFile = Form.BASE_ODK_LOCATION + formName + Form.EXTERNAL_ITEM_SET_SUFFIX;
    /*File existingDb = new File(pathToFile+File.separator+fileName+Form.SUFFIX_DB);
    existingDb.delete();*/
    final DatabaseHelper databaseHelper = new DatabaseHelper(this, fileName, 1, pathToFile);
    SQLiteDatabase db = null;
    try {
        db = databaseHelper.getWritableDatabase();
    } catch (SQLiteException e) {//probably because the existing .db file is corrupt
        e.printStackTrace();
        Log.w(TAG, "Unable to open database in " + pathToFile + File.separator + fileName + Form.SUFFIX_DB
                + " most likely because the database is corrupt. Trying to recreate db file");
        File existingDbFile = new File(pathToFile + File.separator + fileName + Form.SUFFIX_DB);
        existingDbFile.delete();
        File existingDbJournalFile = new File(
                pathToFile + File.separator + fileName + Form.SUFFIX_DB + Form.SUFFIX_JOURNAL);
        existingDbJournalFile.delete();
        try {
            db = databaseHelper.getWritableDatabase();
        } catch (SQLiteException e1) {
            Log.e(TAG,
                    "Unable to recreate " + pathToFile + File.separator + fileName + Form.SUFFIX_DB + "  file");
            e1.printStackTrace();
        }
    }
    if (rows.length() > 0 && db != null) {
        try {
            List<String> columns = new ArrayList<String>();
            List<String> indexes = new ArrayList<String>();
            Iterator<String> iterator = rows.getJSONObject(0).keys();
            //recreate the tables
            db.execSQL("drop table if exists " + Form.DB_METADATA_TABLE);
            String createMetaTableString = "create table " + Form.DB_METADATA_TABLE + " ("
                    + Form.DB_META_LOCALE_FIELD + " " + Form.DB_META_LOCALE_FIELD_TYPE + ")";
            db.execSQL(createMetaTableString);
            databaseHelper.runInsertQuery(Form.DB_METADATA_TABLE, new String[] { Form.DB_META_LOCALE_FIELD },
                    new String[] { Form.DB_DEFAULT_LOCALE }, -1, db);
            db.execSQL("drop table if exists " + Form.DB_DATA_TABLE);
            String createTableString = "create table " + Form.DB_DATA_TABLE + " (";
            while (iterator.hasNext()) {
                String currKey = iterator.next();
                if (columns.size() > 0) {//this is the first column
                    createTableString = createTableString + ", ";
                }
                createTableString = createTableString + Form.DB_DATA_COLUMN_PREFIX + currKey + " "
                        + Form.DB_DATA_COLUMN_TYPE;
                columns.add(currKey);
                if (currKey.endsWith(Form.SUFFIX_INDEX_FIELD)) {
                    Log.d(TAG, fileName + " has an index column " + currKey);
                    indexes.add(currKey);
                }
            }
            //only continue if we have at least one column
            if (columns.size() > 0) {
                createTableString = createTableString + ", " + Form.DB_DATA_SORT_FIELD + " "
                        + Form.DB_DATA_SORT_COLUMN_TYPE + ")";
                db.execSQL(createTableString);
                for (int index = 0; index < indexes.size(); index++) {
                    db.execSQL("create index " + indexes.get(index) + Form.SUFFIX_INDEX + " on "
                            + Form.DB_DATA_TABLE + "(" + Form.DB_DATA_COLUMN_PREFIX + indexes.get(index) + ")");
                }
                for (int rowIndex = 0; rowIndex < rows.length(); rowIndex++) {
                    JSONObject currRow = rows.getJSONObject(rowIndex);
                    String[] currColumns = new String[columns.size() + 1];
                    String[] currValues = new String[columns.size() + 1];
                    for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) {
                        currColumns[columnIndex] = Form.DB_DATA_COLUMN_PREFIX + columns.get(columnIndex);
                        currValues[columnIndex] = currRow.getString(columns.get(columnIndex));
                    }
                    currColumns[columns.size()] = Form.DB_DATA_SORT_FIELD;
                    currValues[columns.size()] = String.valueOf((double) rowIndex);//TODO: not sure if should be float or double
                    databaseHelper.runInsertQuery(Form.DB_DATA_TABLE, currColumns, currValues, -1, db);//do not add unique key field index in argument list. Will end up being an extra query
                }
                result = true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        Log.w(TAG, "Provided jsonArray to be dumped into a db is empty");
    }
    db.close();
    //copy db to the ADB push directory
    File adbFormDir = new File(
            Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_") + Form.EXTERNAL_ITEM_SET_SUFFIX);
    if (!adbFormDir.exists() || !adbFormDir.isDirectory()) {
        adbFormDir.setWritable(true);
        adbFormDir.setReadable(true);
        Log.i(TAG, "Trying to create dir " + adbFormDir.getPath());
    }
    File sourceDbFile = new File(pathToFile + File.separator + fileName + Form.SUFFIX_DB);
    File destDbFile = new File(Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_")
            + Form.EXTERNAL_ITEM_SET_SUFFIX + File.separator + fileName + Form.SUFFIX_DB);
    InputStream in = null;
    OutputStream out = null;
    try {
        in = new FileInputStream(sourceDbFile);
        out = new FileOutputStream(destDbFile);
        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.WebClientPlaylistsSchema.java

@Override
public ArrayList<WebClientSongsSchema> fromJsonArray(JSONArray jsonArray) {

    ArrayList<WebClientSongsSchema> songList = new ArrayList<WebClientSongsSchema>();
    if (jsonArray != null && jsonArray.length() > 0) {
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                WebClientSongsSchema song = new WebClientSongsSchema()
                        .fromJsonObject(jsonArray.getJSONObject(i));
                songList.add(song);//w  w  w  .  java  2 s.  c  om

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

        }

    }
    return songList;
}

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"));
    }/*from w ww .  ja va 2s . c om*/
    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:org.runnerup.export.format.RunKeeper.java

private static SortedMap<Long, HashMap<String, String>> createPointsMap(JSONArray distance, JSONArray path,
        JSONArray hr) throws JSONException {
    SortedMap<Long, HashMap<String, String>> result = new TreeMap<Long, HashMap<String, String>>();

    if (distance != null && distance.length() > 0) {
        for (int i = 0; i < distance.length(); i++) {
            JSONObject o = distance.getJSONObject(i);
            Long key = TimeUnit.SECONDS.toMillis((long) Float.parseFloat(o.getString("timestamp")));
            HashMap<String, String> value = new HashMap<String, String>();
            String valueMapKey = "distance";
            String valueMapValue = o.getString(valueMapKey);
            value.put(valueMapKey, valueMapValue);
            result.put(key, value);//from ww  w.j  a  va 2s.co m
        }
    }

    if (path != null && path.length() > 0) {
        for (int i = 0; i < path.length(); i++) {
            JSONObject o = path.getJSONObject(i);
            Long key = TimeUnit.SECONDS.toMillis((long) Float.parseFloat(o.getString("timestamp")));
            HashMap<String, String> value = result.get(key);
            if (value == null) {
                value = new HashMap<String, String>();
            }
            String[] attrs = new String[] { "latitude", "longitude", "altitude", "type" };
            for (String valueMapKey : attrs) {
                String valueMapValue = o.getString(valueMapKey);
                value.put(valueMapKey, valueMapValue);
            }
            result.put(key, value);
        }
    }

    if (hr != null && hr.length() > 0) {
        for (int i = 0; i < hr.length(); i++) {
            JSONObject o = hr.getJSONObject(i);
            Long key = TimeUnit.SECONDS.toMillis((long) Float.parseFloat(o.getString("timestamp")));
            HashMap<String, String> value = result.get(key);
            if (value == null) {
                value = new HashMap<String, String>();
            }
            String valueMapKey = "heart_rate";
            String valueMapValue = o.getString(valueMapKey);
            value.put(valueMapKey, valueMapValue);
            result.put(key, value);
        }
    }
    return result;
}

From source file:com.aokp.romcontrol.github.tasks.GetJSONChangelogTask.java

protected Void doInBackground(Void... unused) {
    HttpClient httpClient = null;//from  w w w .  ja  va  2s .  c  om
    try {
        httpClient = new DefaultHttpClient();
        String url = String.valueOf(STATIC_DEBUG ? "https://raw.github.com/JBirdVegas/tests/master/example.json"
                : mConfig.CHANGELOG_JSON);
        HttpGet requestWebsite = new HttpGet(url);
        Log.d(TAG, "attempting to connect to: " + url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        JSONArray projectCommitsArray = new JSONArray(httpClient.execute(requestWebsite, responseHandler));

        // debugging
        if (DEBUG)
            Log.d(TAG, "projectCommitsArray.length() is: " + projectCommitsArray.length());
        if (Config.StaticVars.JSON_SPEW)
            Log.d(TAG, "projectCommitsArray.toString() is: " + projectCommitsArray.toString());

        final ChangelogObject commitObject = new ChangelogObject(new JSONObject());
        for (int i = 0; i < projectCommitsArray.length(); i++) {
            JSONObject projectsObject = (JSONObject) projectCommitsArray.get(i);
            PreferenceScreen newCommitPreference = mCategory.getPreferenceManager()
                    .createPreferenceScreen(mContext);
            commitObject.reParse(projectsObject);
            newCommitPreference.setTitle(commitObject.getSubject());
            newCommitPreference.setSummary(commitObject.getBody());
            newCommitPreference.setKey(commitObject.getCommitHash());
            newCommitPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    mAlertDialog.setCommitAndShow(commitObject);
                    return false;
                }
            });
            mCategory.addPreference(newCommitPreference);
        }
    } catch (HttpResponseException httpError) {
        Log.e(TAG, "bad HTTP response:", httpError);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "client protocal exception:", e);
    } catch (JSONException e) {
        Log.d(TAG, "bad json interaction:", e);
    } catch (IOException e) {
        Log.d(TAG, "io exception:", e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return null;
}

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./*from w w  w.  ja  v a 2  s.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:run.ace.IncomingMessages.java

public static Object create(JSONArray message, Activity activity) throws JSONException {
    String fullTypeName = message.getString(2);
    Class c = null;/*www. j  a  v a 2 s. c om*/
    Object instance = null;
    try {
        c = Class.forName(fullTypeName);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Unable to find a class named '" + fullTypeName + "'");
    }

    if (message.length() == 4) {
        // Parameterized constructor
        JSONArray constructorArgs = message.getJSONArray(3);
        Object[] args = Utils.convertJSONArrayToArray(constructorArgs);
        instance = Utils.invokeConstructorWithBestParameterMatch(c, args);
    } else {
        // Default constructor
        try {
            // Expect the Context constructor
            try {
                instance = c.getConstructor(new Class[] { Context.class }).newInstance(activity);
            } catch (NoSuchMethodException ex) {
                // Try the default constructor instead
                instance = c.getConstructor().newInstance();
            }
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(fullTypeName
                    + " does not have a public default constructor, or a public constructor with a single Context parameter");
        } catch (InvocationTargetException ex) {
            throw new RuntimeException(
                    "Error in " + fullTypeName + " constructor: " + ex.getTargetException().toString());
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(fullTypeName + ", or its relevant constructor, isn't public");
        } catch (InstantiationException ex) {
            throw new RuntimeException("Error instantiating " + fullTypeName + ": " + ex.toString());
        }
    }

    return instance;
}