Example usage for android.util Xml parse

List of usage examples for android.util Xml parse

Introduction

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

Prototype

public static void parse(Reader in, ContentHandler contentHandler) throws IOException, SAXException 

Source Link

Document

Parses xml from the given reader and fires events on the given SAX handler.

Usage

From source file:net.kervala.comicsreader.BrowseRemoteAlbumsTask.java

private boolean parseXml(String xml) {
    try {/*w w w . j  ava  2 s  .c o  m*/
        final AlbumsIndexHandler handler = new AlbumsIndexHandler();

        Xml.parse(xml, handler);

        mItems = handler.getItems();
    } catch (SAXException e) {
        //         error = e.toString();
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.android.providers.downloads.OmaDownload.java

/**
* This method parses an xml file into a provided component.
@param  ddUrl       the URL of the download descriptor file
@param  file        the file containing the XML to be parsed
@param  component   the component to which the parsed xml data should be added
@return             the status code (success or other error code)
*//*w  w w  .j  a v a 2s.  c o  m*/
protected static int parseXml(URL ddUrl, File file, OmaDescription component) {

    BufferedReader sReader = null;

    //Initialize the status code in the component
    component.setStatusCode(OmaStatusHandler.SUCCESS);

    if (file == null || ddUrl == null) {
        component.setStatusCode(OmaStatusHandler.INVALID_DESCRIPTOR);
    } else {
        try {
            sReader = new BufferedReader(new FileReader(file));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            Log.e("@M_" + Constants.LOG_OMA_DL, e.toString());
        }

        try {
            Xml.parse(sReader, OMADL_INSTANCE.new DDHandler(ddUrl, component));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.e("@M_" + Constants.LOG_OMA_DL, e.toString());
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            Log.e("@M_" + Constants.LOG_OMA_DL, e.toString());
            component.setStatusCode(OmaStatusHandler.INVALID_DESCRIPTOR);

            //parse install notify url
            String strLine;
            try {
                sReader = new BufferedReader(new FileReader(file));

                while ((strLine = sReader.readLine()) != null) {
                    strLine = strLine.trim();

                    StringBuffer strBuffer = new StringBuffer(strLine);
                    String startTag = "<installNotifyURI>";
                    String endTag = "</installNotifyURI>";
                    int startTagPos = strBuffer.lastIndexOf(startTag);
                    int endTagPos = strBuffer.lastIndexOf(endTag);

                    if (startTagPos != -1 && endTagPos != -1) {
                        strLine = strLine.substring(startTagPos + startTag.length(), endTagPos);
                        Log.d("@M_" + Constants.LOG_OMA_DL, "install notify URI: " + strLine);
                        URL url = new URL(strLine);
                        component.setInstallNotifyUrl(url);
                        break;
                    }
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                Log.e("@M_" + Constants.LOG_OMA_DL, e1.toString());
            }
        }
    }

    return component.getStatusCode();
}

From source file:org.cdmckay.android.provider.MediaWikiProvider.java

private Cursor parseXmlSearch(String apiUrl, String search) {
    final MatrixCursor cursor = new MatrixCursor(SEARCH_COLUMN_NAMES);

    try {//from  w w w  . ja v  a 2  s . com
        final OpenSearchHandler handler = new OpenSearchHandler();
        Xml.parse(search, handler);

        final List<OpenSearchHandler.Result> results = handler.getResults();
        for (OpenSearchHandler.Result result : results) {
            cursor.addRow(new Object[] { result.id, result.title, result.description, result.url });
        }
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        throw new RuntimeException(e);
    }

    return cursor;
}

From source file:org.cdmckay.android.provider.MediaWikiProvider.java

private Cursor parseXmlPage(String apiUrl, String pageString) {
    final MatrixCursor cursor = new MatrixCursor(PAGE_COLUMN_NAMES);

    try {/*from   w  ww .j a  va 2s. c  o m*/
        final PageHandler handler = new PageHandler();
        Xml.parse(pageString, handler);

        final List<PageHandler.Result> results = handler.getResults();
        for (PageHandler.Result result : results) {
            cursor.addRow(new Object[] { result.pageId, result.namespace, result.title, result.content });
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return cursor;
}

From source file:net.gaast.giggity.Schedule.java

private void loadXml(BufferedReader in, ContentHandler parser) {
    try {// w w  w .ja  v  a  2  s  .c om
        Xml.parse(in, parser);
        in.close();
    } catch (Exception e) {
        Log.e("Schedule.loadXml", "XML parse exception: " + e);
        e.printStackTrace();
        throw new LoadException("XML parsing problem: " + e);
    }
}

From source file:de.nware.app.hsDroid.provider.onlineService2Provider.java

/**
 * Parses the exam info./* w  w w  .j a va2s  .c o  m*/
 * 
 * @param htmlContentString
 *            der/die/das html content string
 * @return der/die/das cursor
 * @throws SAXException
 */
private Cursor parseExamInfo(String htmlContentString) throws SAXException {
    final MatrixCursor cursor = new MatrixCursor(EXAM_INFOS_COLUMNS);
    try {
        ExamInfoParser handler = new ExamInfoParser();
        System.out.println("content exam info: " + htmlContentString);
        Xml.parse(htmlContentString, handler);
        ExamInfo exInfos = handler.getExamInfos();
        cursor.addRow(new Object[] { 0, exInfos.getSehrGutAmount(), exInfos.getGutAmount(),
                exInfos.getBefriedigendAmount(), exInfos.getAusreichendAmount(),
                exInfos.getNichtAusreichendAmount(), exInfos.getAttendees(), exInfos.getAverage() });
    } catch (SAXException e) {
        Log.e("read:SAXException:", e.getMessage());
        e.printStackTrace();
        throw new SAXException(e);
    }
    return cursor;
}

From source file:ca.spencerelliott.mercury.Changesets.java

private synchronized void startThread() {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    //Create the thread that will process the incoming feed
    load_thread = new Thread() {
        @Override/*  www  .j  a  v  a2  s. c  o m*/
        public void run() {
            changesets_list.clear();

            DatabaseHelper db_helper = DatabaseHelper.getInstance(getApplicationContext());
            EncryptionHelper encrypt_helper = EncryptionHelper.getInstance("DEADBEEF".toCharArray(),
                    new byte[] { 'L', 'O', 'L' });

            //Get the repository information from the local database
            Beans.RepositoryBean repo_type = db_helper.getRepository(repo_id, encrypt_helper);
            AtomHandler feed_handler = null;

            //Detect the type of repository and create a parser based on that
            switch (repo_type.getType()) {
            case Mercury.RepositoryTypes.HGSERVE:
                feed_handler = new HGWebAtomHandler();
                break;
            case Mercury.RepositoryTypes.GOOGLECODE:
                feed_handler = new GoogleCodeAtomHandler();
                break;
            case Mercury.RepositoryTypes.BITBUCKET:
                feed_handler = new BitbucketAtomHandler();
                break;
            case Mercury.RepositoryTypes.CODEPLEX:
                feed_handler = new CodePlexAtomHandler();
                break;
            }

            HttpURLConnection conn = null;
            boolean connected = false;

            try {
                // XXX We need to use our own factory to make all ssl certs work
                HttpsURLConnection.setDefaultSSLSocketFactory(NaiveSSLSocketFactory.getSocketFactory());

                String repo_url_string = (repo_type.getUrl().endsWith("/") || repo_type.getUrl().endsWith("\\")
                        ? feed_handler
                                .formatURL(repo_type.getUrl().substring(0, repo_type.getUrl().length() - 1))
                        : feed_handler.formatURL(repo_type.getUrl()));

                switch (repo_type.getType()) {
                case Mercury.RepositoryTypes.BITBUCKET:
                    //Only add the token if the user requested it
                    if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.TOKEN)
                        repo_url_string = repo_url_string + "?token=" + repo_type.getSSHKey();
                    break;
                }

                URL repo_url = new URL(repo_url_string);
                conn = (HttpURLConnection) repo_url.openConnection();

                //Check to see if the user enabled HTTP authentication
                if (repo_type.getAuthentication() == Mercury.AuthenticationTypes.HTTP) {
                    //Get their username and password
                    byte[] decrypted_info = (repo_type.getUsername() + ":" + repo_type.getPassword())
                            .getBytes();

                    //Add the header to the http request
                    conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBytes(decrypted_info));
                }
                conn.connect();
                connected = true;
            } catch (ClientProtocolException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("There was a problem with the HTTP protocol");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (IOException e2) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getBaseContext());
                alert.setMessage("Server did not respond with a valid HTTP response");
                alert.setPositiveButton(android.R.string.ok, null);
                alert.show();

                //Do not allow the app to continue with loading
                connected = false;
            } catch (NullPointerException e3) {

            } catch (Exception e) {

            }

            BufferedReader reader = null;

            //Create a new reader based on the information retrieved
            if (connected) {
                try {
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Make sure both the feed handler and info loaded from the web are not null
            if (reader != null && feed_handler != null) {
                try {
                    Xml.parse(reader, feed_handler);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                }
            } else {
                list_handler.sendEmptyMessage(CANCELLED);
                return;
            }

            //Stored beans in the devices database
            ArrayList<Beans.ChangesetBean> stored_beans = null;

            if (prefs.getBoolean("caching", false)) {
                long last_insert = db_helper.getHighestID(DatabaseHelper.DB_TABLE_CHANGESETS, repo_id);

                if (last_insert >= 0) {
                    //Get all of the stored changesets
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                    String rev_id = "";

                    //Try to find the revision id of the bean that has the id of the last inserted value
                    for (Beans.ChangesetBean b : stored_beans) {
                        if (b.getID() == last_insert) {
                            rev_id = b.getRevisionID();
                            break;
                        }
                    }

                    //Trim the list starting from this revision
                    feed_handler.trimStartingFromRevision(rev_id);
                }
            }

            //Create a new bundle for the progress
            Bundle progress_bundle = new Bundle();

            //Retreive all the beans from the handler
            ArrayList<Beans.ChangesetBean> beans = feed_handler.getAllChangesets();
            int bean_count = beans.size();

            //Store the amount of changesets
            progress_bundle.putInt("max", bean_count);

            //Create a new message and store the bundle and what type of message it is
            Message msg = new Message();
            msg.setData(progress_bundle);
            msg.what = SETUP_COUNT;
            list_handler.sendMessage(msg);

            //Add each of the beans to the list
            for (int i = 0; i < bean_count; i++) {
                String commit_text = beans.get(i).getTitle();
                Date commit_date = new Date(beans.get(i).getUpdated());
                changesets_list.add(createChangeset(
                        (commit_text.length() > 30 ? commit_text.substring(0, 30) + "..." : commit_text),
                        beans.get(i).getRevisionID() + " - " + commit_date.toLocaleString()));

                //Store the current progress of the changeset loading
                progress_bundle.putInt("progress", i);

                //Reuse the old message and send an update progress message
                msg = new Message();
                msg.setData(progress_bundle);
                msg.what = UPDATE_PROGRESS;
                list_handler.sendMessage(msg);
            }

            //Get the current count of changesets and the shared preferences
            long changeset_count = db_helper.getChangesetCount(repo_id);

            if (prefs.getBoolean("caching", false)) {
                //Get all of the stored beans from the device if not already done
                if (stored_beans == null)
                    stored_beans = db_helper.getAllChangesets(repo_id, null);

                //Add all the changesets from the device
                for (Beans.ChangesetBean b : stored_beans) {
                    changesets_list.add(createChangeset(
                            (b.getTitle().length() > 30 ? (b.getTitle().substring(0, 30)) + "..."
                                    : b.getTitle()),
                            b.getRevisionID() + " - " + new Date(b.getUpdated()).toLocaleString()));
                }

                //Reverse the list so the oldest changesets are stored first
                Collections.reverse(beans);

                //Iterate through each bean and add it to the device's database
                for (Beans.ChangesetBean b : beans) {
                    db_helper.insert(b, repo_id);
                }

                //Get the amount of changesets allowed to be stored on the device
                int max_changes = Integer.parseInt(prefs.getString("max_changesets", "-1"));

                //Delete the oldest changesets if too many have been stored
                if (changeset_count > max_changes) {
                    db_helper.deleteNumChangesets(repo_id, (changeset_count - max_changes));
                }
            } else if (changeset_count > 0) {
                //Since the user does not have caching enabled, delete the changesets
                db_helper.deleteAllChangesets(repo_id);
            }

            //Update the tables to the newest revision
            if (!beans.isEmpty())
                db_helper.updateLastRev(repo_id, beans.get(0).getRevisionID());

            //Add all of the data to the changeset list
            changesets_data.addAll(beans);

            if (prefs.getBoolean("caching", false))
                changesets_data.addAll(stored_beans);

            //Clean up the sql connection
            db_helper.cleanup();
            db_helper = null;

            //Notify the handler that the loading of the list was successful
            list_handler.sendEmptyMessage(SUCCESSFUL);
        }
    };

    //Start the thread
    load_thread.start();
}

From source file:de.nware.app.hsDroid.provider.onlineService2Provider.java

/**
 * Notenspiegel Lesen/*  ww  w.  jav a  2s . c o m*/
 * 
 * @param htmlContent
 *            html content
 * @return integer[] mit gesamt anzahl der Prfungsleistungen und anzahl der
 *         Neuen Prfungen
 */
private Integer[] read(String htmlContent) {
    Integer[] counter = { 0, 0 };
    try {

        ExamParser handler = new ExamParser();
        Xml.parse(htmlContent, handler);

        for (Exam iterable_element : handler.getExams()) {
            // Log.d(TAG, "update: lid: " + iterable_element.getInfoID());
            if (!examExists(iterable_element.getExamNr(), iterable_element.getExamDate())) {
                counter[1]++;
                // Log.d(TAG, "exam: insert " +
                // iterable_element.getExamName() + " into DB");
                ContentValues values = new ContentValues();
                values.put(onlineService2Data.ExamsCol.SEMESTER, iterable_element.getSemester());
                // values.put(onlineService2Data.ExamsCol.PASSED,
                // (iterable_element.isPassed() ? 1 : 0));
                values.put(onlineService2Data.ExamsCol.PASSED, iterable_element.isPassed());
                values.put(onlineService2Data.ExamsCol.EXAMNAME, iterable_element.getExamName());
                values.put(onlineService2Data.ExamsCol.EXAMNR, iterable_element.getExamNr());
                values.put(onlineService2Data.ExamsCol.EXAMDATE, iterable_element.getExamDate());
                values.put(onlineService2Data.ExamsCol.ADMITTED, iterable_element.getAdmitted());
                values.put(onlineService2Data.ExamsCol.NOTATION, iterable_element.getNotation());
                values.put(onlineService2Data.ExamsCol.ATTEMPTS, iterable_element.getAttempts());
                values.put(onlineService2Data.ExamsCol.GRADE, iterable_element.getGrade());
                values.put(onlineService2Data.ExamsCol.LINKID, iterable_element.getInfoID());
                values.put(onlineService2Data.ExamsCol.STUDIENGANG, iterable_element.getStudiengang());
                // Log.d(TAG, "insert..");
                insert(onlineService2Data.ExamsCol.CONTENT_URI, values);
            } else {
                // Log.d(TAG, "exam: " + iterable_element.getExamName() +
                // " already in DB");
            }
            counter[0]++;
        }
    } catch (SAXException e) {
        Log.e("read:SAXException:", e.getMessage());
        e.printStackTrace();
    }
    return counter;
}