Example usage for android.util JsonReader JsonReader

List of usage examples for android.util JsonReader JsonReader

Introduction

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

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

private List<RowData> openPage() throws Exception {
    this.errorDescription = null;
    this.errorTitle = null;

    List<RowData> list = new ArrayList<RowData>();
    InputStream inputStream = null;
    try {/*from   w  ww  .  j  a  va 2 s  .  c  om*/
        if (!blnPrivate) {
            URL url = new URL(getCatalogUrl());
            /*HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if ( connection.getResponseCode() >= 400 ) {
               inputStream = connection.getErrorStream();
            }
            else {
               inputStream = connection.getInputStream();
            }*/
            inputStream = org.liberty.android.fantastischmemo.downloader.quizlet.lib.makeApiCall(url,
                    _main.QuizletAccessToken);
        } else {
            inputStream = org.liberty.android.fantastischmemo.downloader.quizlet.lib
                    .getUserPrivateCardsets(_main.QuizletUser, _main.QuizletAccessToken);
        }
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        if (!blnPrivate) {
            reader.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();
                if ("total_pages".equals(name)) {
                    this.totalPages = reader.nextInt();
                    if (page > totalPages) {

                    }
                } else if ("total_results".equals(name)) {
                    this.totalResults = reader.nextInt();
                } else if ("page".equals(name)) {
                    this.page = reader.nextInt();
                } else if ("error_title".equals(name)) {
                    errorTitle = reader.nextString();
                } else if ("error_description".equals(name)) {
                    errorDescription = reader.nextString();
                } else if ("sets".equals(name)) {
                    getSets(reader, list);
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
        } else {
            getSets(reader, list);
        }

    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return list;
}

From source file:watch.oms.omswatch.parser.OMSConfigDBParser.java

/**
 * Parses Service response and stores into respective DB table.
 * //from   w  w w  .j  a va2s  .  c  o m
 * @param pStringReader
 */
private void readJsonStream(Reader pStringReader) {
    double latestModifiedTimeStamp = 0.0f;
    JsonReader reader = null;
    List<ContentValues> rows = null;
    String tableName = null;
    ExecutorService executor = Executors.newFixedThreadPool(10);
    final String VISITED_DATE = "visiteddate";
    OMSServerMapperHelper servermapperhelper = new OMSServerMapperHelper();
    final String DB_PROCESS_DURATION = "dbprocessduration";
    final String SERVER_PROCESS_DURATION = "serverprocessduration";

    try {
        Log.d(TAG, "@@@@@@@@@@ Config DB Tables Start @@@@@@@@@@");
        reader = new JsonReader(pStringReader);
        reader.setLenient(true);
        reader.beginObject();
        // Iterate through each table data
        while (reader.hasNext()) {
            tableName = reader.nextName();
            if (tableName.equals(VISITED_DATE)) {

                latestModifiedTimeStamp = reader.nextDouble();

                /*servermapperhelper.updateModifiedTimeStampForAppsTable(
                       latestModifiedTimeStamp);*/
                /*if (Integer.parseInt(OMSApplication
                      .getInstance().getAppId()) == 10) {
                   servermapperhelper
                .updateModifiedTimeStampForVisitedDateMapper(
                      OMSApplication
                            .getInstance()
                            .getEditTextHiddenVal(),
                      latestModifiedTimeStamp);
                }*/
                continue;
            }
            if (tableName.equals(OMSConstants.NULL_STRING)) {
                continue;
            }
            //Fetch dbprocess duration serverprocess duration
            else if (DB_PROCESS_DURATION.equalsIgnoreCase(tableName)) {
                String dbDuration = reader.nextString();
                OMSApplication.getInstance().setDatabaseProcessDuration(dbDuration);
                Log.i(TAG, "DB Process Duration" + dbDuration);
                continue;
            }
            if (SERVER_PROCESS_DURATION.equalsIgnoreCase(tableName)) {
                String serverProcessDuration = reader.nextString();
                OMSApplication.getInstance().setServerProcessDuration(serverProcessDuration);
                Log.i(TAG, "server process duration " + serverProcessDuration);
                continue;
            }
            rows = readAllRowDataForTable(reader, tableName);

            Runnable worker = new DbWorkerThread(tableName, rows);
            executor.execute(worker);
        }
        reader.endObject();
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        Log.d(TAG, "@@@@@@@@@@ Config DB Tables End @@@@@@@@@@");
        // Update Apps Table
        Log.d(TAG, "@@@@@@@@@@ Updating AppsTable with ConfigLastModifieddate:" + latestModifiedTimeStamp);
        servermapperhelper.updateModifiedTimeStampForAppsTable(latestModifiedTimeStamp);

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

        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            Log.e(TAG, "IOException occurred while loading file from Assets folder." + e.getMessage());
            e.printStackTrace();
        }

    }

}

From source file:br.com.thinkti.android.filechooserfrag.fragFileChooserQuizlet.java

private List<typVok> openSet(String id) throws Exception {
    this.errorDescription = null;
    this.errorTitle = null;
    InputStream inputStream = null;
    List<typVok> list = new ArrayList<typVok>();
    String Kom = "";
    _main.vok.title = "";
    try {/*  w  w w.j a  va2s.c om*/
        URL url = new URL(getDeckUrl(id));
        /*
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        if ( connection.getResponseCode() >= 400 ) {
           inputStream = connection.getErrorStream();
        }
        else {
           inputStream = connection.getInputStream();
        }
        */
        inputStream = org.liberty.android.fantastischmemo.downloader.quizlet.lib.makeApiCall(url,
                _main.QuizletAccessToken);
        JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
        reader.beginArray();
        while (reader.hasNext()) {
            reader.beginObject();
            while (reader.hasNext()) {
                String name = reader.nextName();
                if ("id".equals(name)) {
                    long intId = reader.nextLong();
                    /*if (page > totalPages) {
                            
                    }*/
                } else if ("url".equals(name)) {
                    String strUrl = reader.nextString();
                } else if ("title".equals(name)) {
                    String title = reader.nextString();
                    _main.vok.title = title;
                } else if ("created_by".equals(name)) {
                    String created_by = reader.nextString();
                    Kom = _main.getString(R.string.created_by) + " " + created_by + " "
                            + _main.getString((R.string.at)) + " <link://https://quizlet.com/ Quizlet/>";
                } else if ("term_count".equals(name)) {
                    int term_count = reader.nextInt();
                } else if ("lang_terms".equals(name)) {
                    String lang_terms = reader.nextString();
                    try {
                        _LangWord = new Locale(lang_terms.replace("-", "_"));
                    } catch (Throwable ex) {

                    }
                } else if ("lang_definitions".equals(name)) {
                    String lang_definitions = reader.nextString();
                    try {
                        _LangMeaning = (new Locale(lang_definitions.replace("-", "_")));
                    } catch (Throwable ex) {

                    }
                } else if ("terms".equals(name)) {
                    reader.beginArray();
                    while (reader.hasNext()) {
                        typVok v = parseSetDataJson(reader);
                        String kom = v.Kom;
                        v.Kom = Kom;
                        if (!lib.libString.IsNullOrEmpty(kom)) {
                            v.Kom += " " + kom;
                        }
                        list.add(v);
                    }
                    reader.endArray();
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
        }
        reader.endArray();
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return list;
}

From source file:ngo.music.soundcloudplayer.controller.SongController.java

/**
 * get stack of songs played//w  w  w  . j a  v  a  2s .  c o  m
 * 
 * @return
 */
public ArrayList<Object[]> getSongsPlayed() {
    File file = new File(MusicPlayerService.getInstance().getApplicationContext()
            .getExternalFilesDir(Context.ACCESSIBILITY_SERVICE), filename);
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    ArrayList<Object[]> songs = new ArrayList<Object[]>();

    try {
        FileInputStream fileReader = new FileInputStream(file);
        JsonReader reader = new JsonReader(new InputStreamReader(fileReader));

        String id = null;
        reader.beginArray();

        while (reader.hasNext()) {
            reader.beginObject();

            while (reader.hasNext()) {
                Object[] object = new Object[2];
                id = reader.nextName();
                object[0] = getSong(id);
                object[1] = Integer.valueOf(reader.nextInt());
                if (object[0] != null) {
                    songs.add(object);
                }
            }

            reader.endObject();
        }

        reader.endArray();
        reader.close();
    } catch (Exception e) {
        Log.e("get songPlayed", e.toString());
        return songs;
    }
    return songs;
}

From source file:io.realm.Realm.java

/**
 * Create a Realm object for each object in a JSON array. This must be done within a transaction.
 * JSON properties with a null value will map to the default value for the data type in Realm
 * and unknown properties will be ignored.
 *
 * @param clazz         Type of Realm objects created.
 * @param inputStream   JSON array as a InputStream. All objects in the array must be of the
 *                      specified class.
 *
 * @throws RealmException if mapping from JSON fails.
 * @throws IOException if something was wrong with the input stream.
 *///w w  w  .  j  a v a2s . c  o m
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public <E extends RealmObject> void createAllFromJson(Class<E> clazz, InputStream inputStream)
        throws IOException {
    if (clazz == null || inputStream == null) {
        return;
    }

    JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
    try {
        reader.beginArray();
        while (reader.hasNext()) {
            configuration.getSchemaMediator().createUsingJsonStream(clazz, this, reader);
        }
        reader.endArray();
    } finally {
        reader.close();
    }
}

From source file:watch.oms.omswatch.actioncenter.helpers.WatchTransDBParser.java

/**
 * Parses Service response and stores into respective DB table.
 * //from www .  j  av  a  2  s  . c  o  m
 * @param pStringReader
 */
private void readJsonStream(Reader pStringReader) {

    JsonReader reader = null;
    List<ContentValues> rows = null;
    String tableName = null;
    String colName = null;
    ExecutorService executor = Executors.newFixedThreadPool(10);
    double latestModifiedTimeStamp = 0.0f;
    final String VISITED_DATE = "visiteddate";
    final String MESSAGE = "message";
    final String ADDITION_MESSAGE = "additionMessage";
    final String VISITED_DATE_MAPPER = "visiteddatemapper";
    List<String> tableNames = new ArrayList<String>();
    final String DB_PROCESS_DURATION = "dbprocessduration";
    final String SERVER_PROCESS_DURATION = "serverprocessduration";
    try {
        Log.d(TAG, "@@@@@@@@@@ Trans DB Tables Start @@@@@@@@@@");
        reader = new JsonReader(pStringReader);
        reader.setLenient(true);
        reader.beginObject();

        // Iterate through each table data
        while (reader.hasNext()) {

            colName = reader.nextName();
            if (colName.equals(VISITED_DATE)) {

                latestModifiedTimeStamp = reader.nextDouble();
                // Update Trans Table
                /*servermapperhelper.updateModifiedTimeStampForTransTable(
                      ALL_TABLES, latestModifiedTimeStamp);*/
                if (Integer.parseInt(OMSApplication.getInstance().getAppId()) == 10) {
                    servermapperhelper.updateModifiedTimeStampForVisitedDateMapper(
                            OMSApplication.getInstance().getEditTextHiddenVal(), latestModifiedTimeStamp);
                }
                continue;
            } else if (colName.equals(MESSAGE)) {
                Log.e(TAG, "Trans DB gave error response - message - " + reader.nextString());
                continue;
            } else if (colName.equals(ADDITION_MESSAGE)) {
                Log.e(TAG, "Trans DB gave error response - additionMessage - " + reader.nextString());
                continue;
            } else if (VISITED_DATE_MAPPER.equalsIgnoreCase(colName)) {
                Log.d(TAG, "Skipping internal Table " + VISITED_DATE_MAPPER + " lookup");
                reader.skipValue();
                continue;
            }
            //Fetch dbprocess duration serverprocess duration
            else if (DB_PROCESS_DURATION.equalsIgnoreCase(colName)) {
                String dbDuration = reader.nextString();
                OMSApplication.getInstance().setDatabaseProcessDuration(dbDuration);
                /*Log.i(TAG,
                      "DB Process Duration"
                   + dbDuration);*/
                continue;
            } else if (SERVER_PROCESS_DURATION.equalsIgnoreCase(colName)) {
                String serverProcessDuration = reader.nextString();
                OMSApplication.getInstance().setServerProcessDuration(serverProcessDuration);
                /*Log.i(TAG,
                      "server process duration "
                   + serverProcessDuration);*/
                continue;
            }
            Log.d(TAG, "ColName::::" + colName);
            // Get Table Name
            tableName = servermapperhelper.getClientTableName(colName);

            if (tableName == null) {
                Log.e(TAG, "Table Name was not found in ServerMapperHelper - " + colName);
                // Tables created only on the server sometimes dont find
                // entry in ServerMapper. So, allowing those tables here
                tableNames.add(colName);
            } else {
                tableNames.add(tableName);
            }

            rows = readAllRowDataForTable(reader, tableName);

            // Update DB only if we have valid Table name
            if (tableName != null) {
                Runnable worker = new DbWorkerThread(colName, rows);
                executor.execute(worker);
            }
        }
        reader.endObject();

        Log.d(TAG, "Waiting for DB Worker Threads to Complete");
        // Request for Shutdown. This will wait till the db updates are
        // complete. Wait till the db update is complete and then invoke the
        // time stamp update to avoid db locks.
        executor.shutdown();
        while (!executor.isTerminated()) {
        }

        Log.d(TAG, "DB Worker Threads Completed");
        // Update Modified Time Stamp for All Trans Tables
        executor = Executors.newFixedThreadPool(1);
        Runnable worker = new DbWorkerThreadToUpdateTimeStamp(tableNames, latestModifiedTimeStamp);
        executor.execute(worker);

        // Request for Shutdown. This will wait till the db updates are
        // complete
        Log.d(TAG, "Waiting for DB Timestamp Update Worker Thread to Complete");
        executor.shutdown();
        while (!executor.isTerminated()) {
        }

        Log.d(TAG, "DB Timestamp Update Worker Thread Completed");
        Log.d(TAG, "@@@@@@@@@@ Trans DB Tables End @@@@@@@@@@");

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:io.realm.Realm.java

/**
 * Create a Realm object pre-filled with data from a JSON object. This must be done inside a
 * transaction. JSON properties with a null value will map to the default value for the data
 * type in Realm and unknown properties will be ignored.
 *
 * @param clazz         Type of Realm object to create.
 * @param inputStream   JSON object data as a InputStream.
 * @return Created object or null if json string was empty or null.
 *
 * @throws RealmException if the mapping from JSON failed.
 * @throws IOException if something was wrong with the input stream.
 *//*from  w  ww. java2 s. co  m*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public <E extends RealmObject> E createObjectFromJson(Class<E> clazz, InputStream inputStream)
        throws IOException {
    if (clazz == null || inputStream == null) {
        return null;
    }

    JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
    try {
        return configuration.getSchemaMediator().createUsingJsonStream(clazz, this, reader);
    } finally {
        reader.close();
    }
}

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

private void generateAndSendGeoJsonToolReport() {
    FiskInfoUtility fiskInfoUtility = new FiskInfoUtility();
    JSONObject featureCollection = new JSONObject();

    try {// w  w  w  .j a va  2  s.  c o m
        Set<Map.Entry<String, ArrayList<ToolEntry>>> tools = user.getToolLog().myLog.entrySet();
        JSONArray featureList = new JSONArray();

        for (final Map.Entry<String, ArrayList<ToolEntry>> dateEntry : tools) {
            for (final ToolEntry toolEntry : dateEntry.getValue()) {
                if (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_RECEIVED
                        || toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED) {
                    continue;
                }

                toolEntry.setToolStatus(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                        ? ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                        : ToolEntryStatus.STATUS_SENT_UNCONFIRMED);
                JSONObject gjsonTool = toolEntry.toGeoJson(mGpsLocationTracker);
                featureList.put(gjsonTool);
            }
        }

        if (featureList.length() == 0) {
            Toast.makeText(getActivity(), getString(R.string.no_changes_to_report), Toast.LENGTH_LONG).show();

            return;
        }

        user.writeToSharedPref(getActivity());
        featureCollection.put("features", featureList);
        featureCollection.put("type", "FeatureCollection");
        featureCollection.put("crs", JSONObject.NULL);
        featureCollection.put("bbox", JSONObject.NULL);

        String toolString = featureCollection.toString(4);

        if (fiskInfoUtility.isExternalStorageWritable()) {
            fiskInfoUtility.writeMapLayerToExternalStorage(getActivity(), toolString.getBytes(),
                    getString(R.string.tool_report_file_name), getString(R.string.format_geojson), null, false);
            String directoryPath = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
            String fileName = directoryPath + "/FiskInfo/api_setting.json";
            File apiSettingsFile = new File(fileName);
            String recipient = null;

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

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

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

            recipient = recipient == null ? getString(R.string.tool_report_recipient_email) : recipient;
            String[] recipients = new String[] { recipient };
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("plain/plain");

            String toolIds;
            StringBuilder sb = new StringBuilder();

            sb.append("Redskapskoder:\n");

            for (int i = 0; i < featureList.length(); i++) {
                sb.append(Integer.toString(i + 1));
                sb.append(": ");
                sb.append(featureList.getJSONObject(i).getJSONObject("properties").getString("ToolId"));
                sb.append("\n");
            }

            toolIds = sb.toString();

            intent.putExtra(Intent.EXTRA_EMAIL, recipients);
            intent.putExtra(Intent.EXTRA_TEXT, toolIds);
            intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.tool_report_email_header));
            File file = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()
                            + "/FiskInfo/Redskapsrapport.geojson");
            Uri uri = Uri.fromFile(file);
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            startActivity(Intent.createChooser(intent, getString(R.string.send_tool_report_intent_header)));

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

From source file:com.smc.tw.waltz.MainActivity.java

private void unsubscribeAllGcmChannel() {
    String deviceListText = mPreferences.getString("waltzone_local_data", null);
    if (deviceListText == null)
        return;/*from  w  w w .  j a  va  2s  . c  o m*/
    try {
        StringReader stringReader = new StringReader(deviceListText);
        JsonReader reader = new JsonReader(stringReader);

        reader.beginArray();

        while (reader.hasNext()) {
            String deviceSerial = null;

            reader.beginObject();

            while (reader.hasNext()) {
                String name = reader.nextName();

                if (name.equals("waltzone_serial")) {
                    deviceSerial = reader.nextString();
                } else {
                    reader.skipValue();
                }
            }
            //            Log.e(TAG, "Unsubscribe: WALTZ_" + deviceSerial);
            unsubscribeGcmChannel("WALTZ_" + deviceSerial);
            reader.endObject();
        }

        reader.endArray();
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        //e.printStackTrace();
    }
}