Example usage for android.util JsonReader hasNext

List of usage examples for android.util JsonReader hasNext

Introduction

In this page you can find the example usage for android.util JsonReader hasNext.

Prototype

public boolean hasNext() throws IOException 

Source Link

Document

Returns true if the current array or object has another element.

Usage

From source file:com.example.propertylist.handler.JsonPropertyHandler.java

/**
 * Populates property data with the JSON data.
 *
 * @param reader// w  w  w  .j av  a 2s .c om
 *             the {@link android.util.JsonReader} used to read in the data
 * @return
 *          the propertyResults
 * @throws org.json.JSONException
 * @throws java.io.IOException
 */
public List<Property> populatePropertySales(JsonReader reader) throws JSONException, IOException {
    //   Property property = new Property();
    List<Property> propertyResults = new ArrayList<Property>();

    reader.beginObject();
    while (reader.hasNext()) {
        final String name = reader.nextName();
        final boolean isNull = reader.peek() == JsonToken.NULL;
        if (name.equals("result") && !isNull) {
            propertyResults = populateResultsSales(reader);
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
    return propertyResults;
}

From source file:pedromendes.tempodeespera.HospitalDetailActivity.java

public List<Emergency> readResult(JsonReader reader) throws IOException {
    List<Emergency> result = new ArrayList<Emergency>();
    String name = reader.nextName();
    if (name.equals("Result")) {
        reader.beginArray();//  w ww . j  a va  2  s .co  m
        while (reader.hasNext()) {
            reader.beginObject();
            Emergency hospitalEmergencyDetail = new Emergency();
            readEmergency(reader, hospitalEmergencyDetail);
            reader.endObject();
            result.add(hospitalEmergencyDetail);
        }
        reader.endArray();
    }
    return result;
}

From source file:at.ac.tuwien.caa.docscan.logic.DataLog.java

private ArrayList<ShotLog> readList(JsonReader reader) throws ParseException {

    ArrayList<ShotLog> shotLogs = new ArrayList<>();

    try {/*from   w w w  . j a va 2 s .com*/
        reader.beginArray();
        while (reader.hasNext()) {
            shotLogs.add(readShotLog(reader));
        }
        reader.endArray();

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

    return shotLogs;

}

From source file:fiskinfoo.no.sintef.fiskinfoo.Http.BarentswatchApiRetrofit.BarentswatchApi.java

public BarentswatchApi() {
    String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString();//from ww w . j ava 2 s . c  om
    String fileName = directoryPath + "/FiskInfo/api_setting.json";
    File file = new File(fileName);
    String environment = null;

    if (file.exists()) {
        InputStream inputStream;
        InputStreamReader streamReader;
        JsonReader jsonReader;

        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            streamReader = new InputStreamReader(inputStream, "UTF-8");
            jsonReader = new JsonReader(streamReader);

            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                if (name.equals("environment")) {
                    environment = jsonReader.nextString();
                } else {
                    jsonReader.skipValue();
                }
            }
            jsonReader.endObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    targetProd = !"pilot".equals(environment);
    currentPath = targetProd ? barentsWatchProdAddress : barentsWatchPilotAddress;
    BARENTSWATCH_API_ENDPOINT = currentPath + "/api/v1/geodata";

    Executor httpExecutor = Executors.newSingleThreadExecutor();
    MainThreadExecutor callbackExecutor = new MainThreadExecutor();
    barentswatchApi = initializeBarentswatchAPI(httpExecutor, callbackExecutor);
}

From source file:at.ac.tuwien.caa.docscan.logic.DataLog.java

private GPS readGPS(JsonReader reader) throws IOException {

    String longitude = null;// w w  w .j av a2 s.  c om
    String latitude = null;

    reader.beginObject();
    //        reader.beginArray();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals(GPS_LONGITUDE_NAME))
            longitude = reader.nextString();
        else if (name.equals(GPS_LATITUDE_NAME))
            latitude = reader.nextString();
        else
            reader.skipValue();
    }
    //        reader.endArray();
    reader.endObject();

    GPS gps = null;
    if (longitude != null && latitude != null)
        gps = new GPS(longitude, latitude);

    return gps;

}

From source file:com.morlunk.leeroy.LeeroyUpdateService.java

private void handleCheckUpdates(Intent intent, boolean notify, ResultReceiver receiver) {
    List<LeeroyApp> appList = LeeroyApp.getApps(getPackageManager());

    if (appList.size() == 0) {
        return;/* w w  w .j  a  v  a  2s . c o  m*/
    }

    List<LeeroyAppUpdate> updates = new LinkedList<>();
    List<LeeroyApp> notUpdatedApps = new LinkedList<>();
    List<LeeroyException> exceptions = new LinkedList<>();
    for (LeeroyApp app : appList) {
        try {
            String paramUrl = app.getJenkinsUrl() + "/api/json?tree=lastSuccessfulBuild[number,url]";
            URL url = new URL(paramUrl);
            URLConnection conn = url.openConnection();
            Reader reader = new InputStreamReader(conn.getInputStream());

            JsonReader jsonReader = new JsonReader(reader);
            jsonReader.beginObject();
            jsonReader.nextName();
            jsonReader.beginObject();

            int latestSuccessfulBuild = 0;
            String buildUrl = null;
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                if ("number".equals(name)) {
                    latestSuccessfulBuild = jsonReader.nextInt();
                } else if ("url".equals(name)) {
                    buildUrl = jsonReader.nextString();
                } else {
                    throw new RuntimeException("Unknown key " + name);
                }
            }
            jsonReader.endObject();
            jsonReader.endObject();
            jsonReader.close();

            if (latestSuccessfulBuild > app.getJenkinsBuild()) {
                LeeroyAppUpdate update = new LeeroyAppUpdate();
                update.app = app;
                update.newBuild = latestSuccessfulBuild;
                update.newBuildUrl = buildUrl;
                updates.add(update);
            } else {
                notUpdatedApps.add(app);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            CharSequence appName = app.getApplicationInfo().loadLabel(getPackageManager());
            exceptions.add(new LeeroyException(app, getString(R.string.invalid_url, appName), e));
        } catch (IOException e) {
            e.printStackTrace();
            exceptions.add(new LeeroyException(app, e));
        }
    }

    if (notify) {
        NotificationManagerCompat nm = NotificationManagerCompat.from(this);
        if (updates.size() > 0) {
            NotificationCompat.Builder ncb = new NotificationCompat.Builder(this);
            ncb.setSmallIcon(R.drawable.ic_stat_update);
            ncb.setTicker(getString(R.string.updates_available));
            ncb.setContentTitle(getString(R.string.updates_available));
            ncb.setContentText(getString(R.string.num_updates, updates.size()));
            ncb.setPriority(NotificationCompat.PRIORITY_LOW);
            ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            Intent appIntent = new Intent(this, AppListActivity.class);
            appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            ncb.setContentIntent(
                    PendingIntent.getActivity(this, 0, appIntent, PendingIntent.FLAG_CANCEL_CURRENT));
            ncb.setAutoCancel(true);
            NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
            for (LeeroyAppUpdate update : updates) {
                CharSequence appName = update.app.getApplicationInfo().loadLabel(getPackageManager());
                style.addLine(getString(R.string.notify_app_update, appName, update.app.getJenkinsBuild(),
                        update.newBuild));
            }
            style.setSummaryText(getString(R.string.app_name));
            ncb.setStyle(style);
            ncb.setNumber(updates.size());
            nm.notify(NOTIFICATION_UPDATE, ncb.build());
        }

        if (exceptions.size() > 0) {
            NotificationCompat.Builder ncb = new NotificationCompat.Builder(this);
            ncb.setSmallIcon(R.drawable.ic_stat_error);
            ncb.setTicker(getString(R.string.error_checking_updates));
            ncb.setContentTitle(getString(R.string.error_checking_updates));
            ncb.setContentText(getString(R.string.click_to_retry));
            ncb.setPriority(NotificationCompat.PRIORITY_LOW);
            ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            ncb.setContentIntent(PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
            ncb.setAutoCancel(true);
            ncb.setNumber(exceptions.size());
            nm.notify(NOTIFICATION_ERROR, ncb.build());
        }
    }

    if (receiver != null) {
        Bundle results = new Bundle();
        results.putParcelableArrayList(EXTRA_UPDATE_LIST, new ArrayList<>(updates));
        results.putParcelableArrayList(EXTRA_NO_UPDATE_LIST, new ArrayList<>(notUpdatedApps));
        results.putParcelableArrayList(EXTRA_EXCEPTION_LIST, new ArrayList<>(exceptions));
        receiver.send(0, results);
    }
}

From source file:com.workday.autoparse.json.parser.JsonParserUtils.java

/**
 * Parse an array that has only non-array children into a {@link Collection}.
 *
 * @param reader The reader to use, whose next token should either be {@link JsonToken#NULL} or
 * {@link JsonToken#BEGIN_ARRAY}./*w  w  w .  j a v a 2 s .  c om*/
 * @param collection The Collection to populate. The parametrization should match {@code
 * typeClass}.
 * @param itemParser The parser to use for items of the array. May be null.
 * @param typeClass The type of items to expect in the array. May not be null, but may be
 * Object.class.
 * @param key The key corresponding to the current value. This is used to make more useful error
 * messages.
 */
private static <T> void parseFlatJsonArray(JsonReader reader, Collection<T> collection,
        JsonObjectParser<T> itemParser, Class<T> typeClass, String key) throws IOException {
    if (handleNull(reader)) {
        return;
    }

    Converter<T> converter = null;
    if (Converters.isConvertibleFromString(typeClass)) {
        converter = Converters.getConverter(typeClass);
    }

    final String discriminationName = ContextHolder.getContext().getSettings().getDiscriminationName();

    reader.beginArray();
    while (reader.hasNext()) {
        Object nextValue;
        final JsonToken nextToken = reader.peek();
        if (itemParser != null && nextToken == JsonToken.BEGIN_OBJECT) {
            reader.beginObject();
            nextValue = itemParser.parseJsonObject(null, reader, discriminationName, null);
            reader.endObject();
        } else if (converter != null && (nextToken == JsonToken.NUMBER || nextToken == JsonToken.STRING)) {
            nextValue = converter.convert(reader.nextString());
        } else {
            nextValue = parseNextValue(reader);
        }

        if (typeClass.isInstance(nextValue)) {
            // This is safe since we are calling class.isInstance()
            @SuppressWarnings("unchecked")
            T toAdd = (T) nextValue;
            collection.add(toAdd);
        } else {
            throw new IllegalStateException(
                    String.format(Locale.US, "Could not convert value in array at \"%s\" to %s from %s.", key,
                            typeClass.getCanonicalName(), getClassName(nextValue)));
        }
    }
    reader.endArray();
}

From source file:at.ac.tuwien.caa.docscan.logic.DataLog.java

private ShotLog readShotLog(JsonReader reader) throws IOException, ParseException {

    GPS gps = null;//from w w w .  j  a va 2s .com
    String dateString, fileName = null;
    Date date = null;
    boolean seriesMode = false;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals(FILE_NAME)) {
            fileName = reader.nextString();
        } else if (name.equals(DATE_NAME)) {
            dateString = reader.nextString();
            if (dateString != null)
                date = string2Date(dateString);
        } else if (name.equals(GPS_NAME)) {
            gps = readGPS(reader);
        } else if (name.equals(SERIES_MODE_NAME)) {
            seriesMode = reader.nextBoolean();
        }

    }
    reader.endObject();

    ShotLog shotLog = new ShotLog(fileName, gps, date, seriesMode);
    return shotLog;

}

From source file:com.tcity.android.ui.info.BuildInfoTask.java

private void handleResponse(@NotNull HttpResponse response) throws IOException, ParseException {
    JsonReader reader = new JsonReader(new InputStreamReader(response.getEntity().getContent()));

    //noinspection TryFinallyCanBeTryWithResources
    try {/*ww w .  java 2s .  com*/
        reader.beginObject();

        BuildInfoData data = new BuildInfoData();
        SimpleDateFormat dateFormat = new SimpleDateFormat(Common.TEAMCITY_DATE_FORMAT);

        while (reader.hasNext()) {
            switch (reader.nextName()) {
            case "status":
                if (data.status == null) {
                    data.status = com.tcity.android.Status.valueOf(reader.nextString());
                }
                break;
            case "running":
                if (reader.nextBoolean()) {
                    data.status = com.tcity.android.Status.RUNNING;
                }
                break;
            case "branchName":
                data.branch = reader.nextString();
                break;
            case "defaultBranch":
                data.isBranchDefault = reader.nextBoolean();
                break;
            case "statusText":
                data.result = reader.nextString();
                break;
            case "waitReason":
                data.waitReason = reader.nextString();
                break;
            case "queuedDate":
                data.queued = dateFormat.parse(reader.nextString());
                break;
            case "startDate":
                data.started = dateFormat.parse(reader.nextString());
                break;
            case "finishDate":
                data.finished = dateFormat.parse(reader.nextString());
                break;
            case "agent":
                data.agent = getAgentName(reader);
                break;
            default:
                reader.skipValue();
            }
        }

        myResult = data;

        reader.endObject();
    } finally {
        reader.close();
    }
}

From source file:com.dalaran.async.task.http.AbstractHTTPService.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected List<ContentValues> parseJson(JsonReader reader) throws IOException {

    List<ContentValues> contentValueses = new ArrayList<ContentValues>();
    ContentValues values = new ContentValues();
    Long threadId = 0L;/*from  w w  w . ja va2s.c  om*/
    boolean notEnd = true;
    String name = "";
    if (reader.hasNext()) { //todo android.util.MalformedJsonException: Use JsonReader.setLenient(true)
        do {
            switch (reader.peek()) {
            case BEGIN_OBJECT:
                values = new ContentValues();
                if (threadId != 0) {
                    values.put("threadId", threadId);
                }
                reader.beginObject();
                break;
            case BEGIN_ARRAY:
                if (values != null && values.getAsLong("threadId") != null) {
                    threadId = values.getAsLong("threadId");
                }
                reader.beginArray();
                break;
            case BOOLEAN:
                values.put(name, reader.nextBoolean());
                break;
            case END_ARRAY:
                reader.endArray();
                break;
            case END_DOCUMENT:
                notEnd = false;
                break;
            case END_OBJECT:
                contentValueses.add(values);
                reader.endObject();
                break;
            case NAME:
                name = reader.nextName();
                break;
            case NULL:
                reader.nextNull();
                break;
            case NUMBER:
                values.put(name, reader.nextDouble());
                break;
            case STRING:
                values.put(name, reader.nextString());
                break;
            default:
                reader.skipValue();
            }
        } while (notEnd);
    }
    return contentValueses;
}