android.content.res.XmlResourceParser

Here are the examples of the java api class android.content.res.XmlResourceParser taken from open source projects.

1. ChangeLogDialog#GetHTMLChangelog()

Project: weiciyuan
File: ChangeLogDialog.java
//Get the changelog in html code, this will be shown in the dialog's webview
private String GetHTMLChangelog(int aResourceId, Resources aResource) {
    String _Result = "<html><head>" + GetStyle() + "</head><body>";
    XmlResourceParser _xml = aResource.getXml(aResourceId);
    try {
        int eventType = _xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if ((eventType == XmlPullParser.START_TAG) && (_xml.getName().equals("release"))) {
                _Result = _Result + ParseReleaseTag(_xml);
            }
            eventType = _xml.next();
        }
    } catch (XmlPullParserException e) {
        Log.e(TAG, e.getMessage(), e);
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
    } finally {
        _xml.close();
    }
    _Result = _Result + "</body></html>";
    return _Result;
}

2. FileUtils#getMimeTypes()

Project: vimtouch
File: FileUtils.java
/**
	 * Load MIME types from XML
	 * 
	 * @param context
	 * @return
	 */
private static MimeTypes getMimeTypes(Context context) {
    MimeTypes mimeTypes = null;
    final MimeTypeParser mtp = new MimeTypeParser();
    final XmlResourceParser in = context.getResources().getXml(R.xml.mimetypes);
    try {
        mimeTypes = mtp.fromXmlResource(in);
    } catch (Exception e) {
        if (DEBUG)
            Log.e(TAG, "getMimeTypes", e);
    }
    return mimeTypes;
}

3. MenuInflater#inflate()

Project: Ushahidi_Android
File: MenuInflater.java
/**
     * Inflate a menu hierarchy from the specified XML resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param menuRes Resource ID for an XML layout resource to load (e.g.,
     *            <code>R.menu.main_activity</code>)
     * @param menu The Menu to inflate into. The items and submenus will be
     *            added to this Menu.
     */
public void inflate(int menuRes, Menu menu) {
    XmlResourceParser parser = null;
    try {
        parser = mContext.getResources().getLayout(menuRes);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        parseMenu(parser, attrs, menu);
    } catch (XmlPullParserException e) {
        throw new InflateException("Error inflating menu XML", e);
    } catch (IOException e) {
        throw new InflateException("Error inflating menu XML", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

4. AnimatorInflater#loadAnimator()

Project: UltimateAndroid
File: AnimatorInflater.java
//private static final int VALUE_TYPE_INT         = 1;
//private static final int VALUE_TYPE_COLOR       = 4;
//private static final int VALUE_TYPE_CUSTOM      = 5;
/**
     * Loads an {@link com.marshalchen.common.uimodule.nineoldandroids.animation.Animator} object from a resource
     *
     * @param context Application context used to access resources
     * @param id The resource id of the animation to load
     * @return The animator object reference by the specified id
     * @throws android.content.res.Resources.NotFoundException when the animation cannot be loaded
     */
public static Animator loadAnimator(Context context, int id) throws NotFoundException {
    XmlResourceParser parser = null;
    try {
        parser = context.getResources().getAnimation(id);
        return createAnimatorFromXml(context, parser);
    } catch (XmlPullParserException ex) {
        NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
        rnf.initCause(ex);
        throw rnf;
    } catch (IOException ex) {
        NotFoundException rnf = new NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
        rnf.initCause(ex);
        throw rnf;
    } finally {
        if (parser != null)
            parser.close();
    }
}

5. TransitionInflater#inflateTransitionManager()

Project: Transitions-Everywhere
File: TransitionInflater.java
/**
     * Loads a {@link TransitionManager} object from a resource
     *
     * @param resource The resource id of the transition manager to load
     * @return The loaded TransitionManager object
     * @throws android.content.res.Resources.NotFoundException when the
     *                                                         transition manager cannot be loaded
     */
public TransitionManager inflateTransitionManager(int resource, ViewGroup sceneRoot) {
    XmlResourceParser parser = mContext.getResources().getXml(resource);
    try {
        return createTransitionManagerFromXml(parser, Xml.asAttributeSet(parser), sceneRoot);
    } catch (XmlPullParserException e) {
        InflateException ex = new InflateException(e.getMessage());
        ex.initCause(e);
        throw ex;
    } catch (IOException e) {
        InflateException ex = new InflateException(parser.getPositionDescription() + ": " + e.getMessage());
        ex.initCause(e);
        throw ex;
    } finally {
        parser.close();
    }
}

6. TransitionInflater#inflateTransition()

Project: Transitions-Everywhere
File: TransitionInflater.java
/**
     * Loads a {@link Transition} object from a resource
     *
     * @param resource The resource id of the transition to load
     * @return The loaded Transition object
     * @throws android.content.res.Resources.NotFoundException when the
     *                                                         transition cannot be loaded
     */
public Transition inflateTransition(int resource) {
    XmlResourceParser parser = mContext.getResources().getXml(resource);
    try {
        return createTransitionFromXml(parser, Xml.asAttributeSet(parser), null);
    } catch (XmlPullParserException e) {
        InflateException ex = new InflateException(e.getMessage());
        ex.initCause(e);
        throw ex;
    } catch (IOException e) {
        InflateException ex = new InflateException(parser.getPositionDescription() + ": " + e.getMessage());
        ex.initCause(e);
        throw ex;
    } finally {
        parser.close();
    }
}

7. MenuInflater#inflate()

Project: todo.txt-android
File: MenuInflater.java
/**
     * Inflate a menu hierarchy from the specified XML resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param menuRes Resource ID for an XML layout resource to load (e.g.,
     *            <code>R.menu.main_activity</code>)
     * @param menu The Menu to inflate into. The items and submenus will be
     *            added to this Menu.
     */
public void inflate(int menuRes, Menu menu) {
    XmlResourceParser parser = null;
    try {
        parser = mContext.getResources().getLayout(menuRes);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        parseMenu(parser, attrs, menu);
    } catch (XmlPullParserException e) {
        throw new InflateException("Error inflating menu XML", e);
    } catch (IOException e) {
        throw new InflateException("Error inflating menu XML", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

8. SublimeMenuInflater#inflate()

Project: SublimeNavigationView
File: SublimeMenuInflater.java
/**
     * Inflate a menu hierarchy from the specified XML resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param menuRes Resource ID for an XML layout resource to load (e.g.,
     *                <code>R.menu.nav_main</code>)
     * @param menu    The Menu to inflate into. The items and groups will be
     *                added to this Menu.
     */
public void inflate(int menuRes, SublimeMenu menu) {
    XmlResourceParser parser = null;
    try {
        parser = mContext.getResources().getLayout(menuRes);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        parseMenu(parser, attrs, menu);
    } catch (XmlPullParserException e) {
        throw new InflateException("Error inflating menu XML", e);
    } catch (IOException e) {
        throw new InflateException("Error inflating menu XML", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

9. AnimatorInflater#loadAnimator()

Project: NineOldAndroids
File: AnimatorInflater.java
//private static final int VALUE_TYPE_INT         = 1;
//private static final int VALUE_TYPE_COLOR       = 4;
//private static final int VALUE_TYPE_CUSTOM      = 5;
/**
     * Loads an {@link Animator} object from a resource
     *
     * @param context Application context used to access resources
     * @param id The resource id of the animation to load
     * @return The animator object reference by the specified id
     * @throws android.content.res.Resources.NotFoundException when the animation cannot be loaded
     */
public static Animator loadAnimator(Context context, int id) throws NotFoundException {
    XmlResourceParser parser = null;
    try {
        parser = context.getResources().getAnimation(id);
        return createAnimatorFromXml(context, parser);
    } catch (XmlPullParserException ex) {
        Resources.NotFoundException rnf = new Resources.NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
        rnf.initCause(ex);
        throw rnf;
    } catch (IOException ex) {
        Resources.NotFoundException rnf = new Resources.NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
        rnf.initCause(ex);
        throw rnf;
    } finally {
        if (parser != null)
            parser.close();
    }
}

10. MenuInflater#inflate()

Project: networklog
File: MenuInflater.java
/**
     * Inflate a menu hierarchy from the specified XML resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param menuRes Resource ID for an XML layout resource to load (e.g.,
     *            <code>R.menu.main_activity</code>)
     * @param menu The Menu to inflate into. The items and submenus will be
     *            added to this Menu.
     */
public void inflate(int menuRes, Menu menu) {
    XmlResourceParser parser = null;
    try {
        parser = mContext.getResources().getLayout(menuRes);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        parseMenu(parser, attrs, menu);
    } catch (XmlPullParserException e) {
        throw new InflateException("Error inflating menu XML", e);
    } catch (IOException e) {
        throw new InflateException("Error inflating menu XML", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

11. MenuInflater#inflate()

Project: Libraries-for-Android-Developers
File: MenuInflater.java
/**
     * Inflate a menu hierarchy from the specified XML resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param menuRes Resource ID for an XML layout resource to load (e.g.,
     *            <code>R.menu.main_activity</code>)
     * @param menu The Menu to inflate into. The items and submenus will be
     *            added to this Menu.
     */
public void inflate(int menuRes, Menu menu) {
    XmlResourceParser parser = null;
    try {
        parser = mContext.getResources().getLayout(menuRes);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        parseMenu(parser, attrs, menu);
    } catch (XmlPullParserException e) {
        throw new InflateException("Error inflating menu XML", e);
    } catch (IOException e) {
        throw new InflateException("Error inflating menu XML", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

12. SettingChangeLogDialog#GetHTMLChangelog()

Project: iBeebo
File: SettingChangeLogDialog.java
// Get the changelog in html code, this will be shown in the dialog's
// webview
private String GetHTMLChangelog(int aResourceId, Resources aResource) {
    String _Result = "<html><head>" + GetStyle() + "</head><body>";
    XmlResourceParser _xml = aResource.getXml(aResourceId);
    try {
        int eventType = _xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if ((eventType == XmlPullParser.START_TAG) && (_xml.getName().equals("release"))) {
                _Result = _Result + ParseReleaseTag(_xml);
            }
            eventType = _xml.next();
        }
    } catch (XmlPullParserException e) {
        Log.e(TAG, e.getMessage(), e);
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
    } finally {
        _xml.close();
    }
    _Result = _Result + "</body></html>";
    return _Result;
}

13. ChangeLogDialog#GetHTMLChangelog()

Project: iBeebo
File: ChangeLogDialog.java
// Get the changelog in html code, this will be shown in the dialog's
// webview
private String GetHTMLChangelog(int aResourceId, Resources aResource) {
    String _Result = "<html><head>" + GetStyle() + "</head><body>";
    XmlResourceParser _xml = aResource.getXml(aResourceId);
    try {
        int eventType = _xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if ((eventType == XmlPullParser.START_TAG) && (_xml.getName().equals("release"))) {
                _Result = _Result + ParseReleaseTag(_xml);
            }
            eventType = _xml.next();
        }
    } catch (XmlPullParserException e) {
        Log.e(TAG, e.getMessage(), e);
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
    } finally {
        _xml.close();
    }
    _Result = _Result + "</body></html>";
    return _Result;
}

14. SupportMenuInflater#inflate()

Project: HoloEverywhere
File: SupportMenuInflater.java
/**
     * Inflate a menu hierarchy from the specified XML resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param menuRes Resource ID for an XML layout resource to load (e.g.,
     *                <code>R.menu.main_activity</code>)
     * @param menu    The Menu to inflate into. The items and submenus will be
     *                added to this Menu.
     */
@Override
public void inflate(int menuRes, Menu menu) {
    // If we're not dealing with a SupportMenu instance, let super handle
    if (!(menu instanceof SupportMenu)) {
        super.inflate(menuRes, menu);
        return;
    }
    XmlResourceParser parser = null;
    try {
        parser = mContext.getResources().getLayout(menuRes);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        parseMenu(parser, attrs, menu);
    } catch (XmlPullParserException e) {
        throw new InflateException("Error inflating menu XML", e);
    } catch (IOException e) {
        throw new InflateException("Error inflating menu XML", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

15. MimeTypes#initInstance()

Project: filemanager
File: MimeTypes.java
/**
	 * Use this instead of the default constructor to get a prefilled object.
	 */
public static void initInstance(Context c) {
    MimeTypeParser mtp = null;
    try {
        mtp = new MimeTypeParser(c, c.getPackageName());
    } catch (NameNotFoundException e) {
    }
    XmlResourceParser in = c.getResources().getXml(R.xml.mimetypes);
    try {
        mimeTypes = mtp.fromXmlResource(in);
    } catch (XmlPullParserExceptionIOException |  e) {
        e.printStackTrace();
    }
}

16. PathAnimatorInflater#loadAnimator()

Project: ElasticProgressBar
File: PathAnimatorInflater.java
public static Animator loadAnimator(Context c, Resources resources, Resources.Theme theme, int id, float pathErrorScale) throws Resources.NotFoundException {
    XmlResourceParser parser = null;
    try {
        parser = resources.getAnimation(id);
        return createAnimatorFromXml(c, resources, theme, parser, pathErrorScale);
    } catch (XmlPullParserException ex) {
        Resources.NotFoundException rnf = new Resources.NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
        rnf.initCause(ex);
        throw rnf;
    } catch (IOException ex) {
        Resources.NotFoundException rnf = new Resources.NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
        rnf.initCause(ex);
        throw rnf;
    } finally {
        if (parser != null) {
            parser.close();
        }
    }
}

17. AnimatorInflater#loadAnimator()

Project: cgeo
File: AnimatorInflater.java
//private static final int VALUE_TYPE_INT         = 1;
//private static final int VALUE_TYPE_COLOR       = 4;
//private static final int VALUE_TYPE_CUSTOM      = 5;
/**
     * Loads an {@link Animator} object from a resource
     *
     * @param context Application context used to access resources
     * @param id The resource id of the animation to load
     * @return The animator object reference by the specified id
     * @throws android.content.res.Resources.NotFoundException when the animation cannot be loaded
     */
public static Animator loadAnimator(Context context, int id) throws NotFoundException {
    XmlResourceParser parser = null;
    try {
        parser = context.getResources().getAnimation(id);
        return createAnimatorFromXml(context, parser);
    } catch (XmlPullParserException ex) {
        Resources.NotFoundException rnf = new Resources.NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
        rnf.initCause(ex);
        throw rnf;
    } catch (IOException ex) {
        Resources.NotFoundException rnf = new Resources.NotFoundException("Can't load animation resource ID #0x" + Integer.toHexString(id));
        rnf.initCause(ex);
        throw rnf;
    } finally {
        if (parser != null)
            parser.close();
    }
}

18. MenuInflater#inflate()

Project: astrid
File: MenuInflater.java
/**
     * Inflate a menu hierarchy from the specified XML resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param menuRes Resource ID for an XML layout resource to load (e.g.,
     *            <code>R.menu.main_activity</code>)
     * @param menu The Menu to inflate into. The items and submenus will be
     *            added to this Menu.
     */
public void inflate(int menuRes, Menu menu) {
    XmlResourceParser parser = null;
    try {
        parser = mContext.getResources().getLayout(menuRes);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        parseMenu(parser, attrs, menu);
    } catch (XmlPullParserException e) {
        throw new InflateException("Error inflating menu XML", e);
    } catch (IOException e) {
        throw new InflateException("Error inflating menu XML", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

19. MenuInflater#inflate()

Project: ActionBarSherlock
File: MenuInflater.java
/**
     * Inflate a menu hierarchy from the specified XML resource. Throws
     * {@link InflateException} if there is an error.
     *
     * @param menuRes Resource ID for an XML layout resource to load (e.g.,
     *            <code>R.menu.main_activity</code>)
     * @param menu The Menu to inflate into. The items and submenus will be
     *            added to this Menu.
     */
public void inflate(int menuRes, Menu menu) {
    XmlResourceParser parser = null;
    try {
        parser = mContext.getResources().getLayout(menuRes);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        parseMenu(parser, attrs, menu);
    } catch (XmlPullParserException e) {
        throw new InflateException("Error inflating menu XML", e);
    } catch (IOException e) {
        throw new InflateException("Error inflating menu XML", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

20. FontIconDrawable#inflate()

Project: fonticon
File: FontIconDrawable.java
public static FontIconDrawable inflate(Context context, int xmlId) {
    XmlResourceParser parser = context.getResources().getXml(xmlId);
    if (parser == null) {
        throw new InflateException();
    }
    try {
        int type;
        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) {
            final String name = parser.getName();
            if (type != XmlPullParser.START_TAG) {
                continue;
            }
            if ("font-icon".equals(name)) {
                FontIconDrawable result = new FontIconDrawable();
                result.inflate(context, Xml.asAttributeSet(parser));
                return result;
            } else {
                throw new InflateException(name);
            }
        }
    } catch (XmlPullParserException ex) {
        throw new InflateException(ex);
    } catch (IOException ex) {
        throw new InflateException(ex);
    }
    throw new InflateException();
}

21. PluginManager#loadPlugins()

Project: cordova-android-chromeview
File: PluginManager.java
/**
     * Load plugins from res/xml/config.xml
     */
public void loadPlugins() {
    int id = this.ctx.getActivity().getResources().getIdentifier("config", "xml", this.ctx.getActivity().getPackageName());
    if (id == 0) {
        id = this.ctx.getActivity().getResources().getIdentifier("plugins", "xml", this.ctx.getActivity().getPackageName());
        LOG.i(TAG, "Using plugins.xml instead of config.xml.  plugins.xml will eventually be deprecated");
    }
    if (id == 0) {
        this.pluginConfigurationMissing();
        //We have the error, we need to exit without crashing!
        return;
    }
    XmlResourceParser xml = this.ctx.getActivity().getResources().getXml(id);
    int eventType = -1;
    String service = "", pluginClass = "", paramType = "";
    boolean onload = false;
    boolean insideFeature = false;
    while (eventType != XmlResourceParser.END_DOCUMENT) {
        if (eventType == XmlResourceParser.START_TAG) {
            String strNode = xml.getName();
            //This is for the old scheme
            if (strNode.equals("plugin")) {
                service = xml.getAttributeValue(null, "name");
                pluginClass = xml.getAttributeValue(null, "value");
                Log.d(TAG, "<plugin> tags are deprecated, please use <features> instead. <plugin> will no longer work as of Cordova 3.0");
                onload = "true".equals(xml.getAttributeValue(null, "onload"));
            } else //What is this?
            if (strNode.equals("url-filter")) {
                this.urlMap.put(xml.getAttributeValue(null, "value"), service);
            } else if (strNode.equals("feature")) {
                //Check for supported feature sets  aka. plugins (Accelerometer, Geolocation, etc)
                //Set the bit for reading params
                insideFeature = true;
                service = xml.getAttributeValue(null, "name");
            } else if (insideFeature && strNode.equals("param")) {
                paramType = xml.getAttributeValue(null, "name");
                if (// check if it is using the older service param
                paramType.equals("service"))
                    service = xml.getAttributeValue(null, "value");
                else if (paramType.equals("package") || paramType.equals("android-package"))
                    pluginClass = xml.getAttributeValue(null, "value");
                else if (paramType.equals("onload"))
                    onload = "true".equals(xml.getAttributeValue(null, "value"));
            }
        } else if (eventType == XmlResourceParser.END_TAG) {
            String strNode = xml.getName();
            if (strNode.equals("feature") || strNode.equals("plugin")) {
                PluginEntry entry = new PluginEntry(service, pluginClass, onload);
                this.addService(entry);
                //Empty the strings to prevent plugin loading bugs
                service = "";
                pluginClass = "";
                insideFeature = false;
            }
        }
        try {
            eventType = xml.next();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

22. FileProvider#parsePathStrategy()

Project: CodenameOne
File: FileProvider.java
/**
     * Parse and return {@link PathStrategy} for given authority as defined in
     * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
     *
     * @see #getPathStrategy(Context, String)
     */
private static PathStrategy parsePathStrategy(Context context, String authority) throws IOException, XmlPullParserException {
    final SimplePathStrategy strat = new SimplePathStrategy(authority);
    final ProviderInfo info = context.getPackageManager().resolveContentProvider(authority, PackageManager.GET_META_DATA);
    final XmlResourceParser in = info.loadXmlMetaData(context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
    if (in == null) {
        throw new IllegalArgumentException("Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
    }
    int type;
    while ((type = in.next()) != END_DOCUMENT) {
        if (type == START_TAG) {
            final String tag = in.getName();
            final String name = in.getAttributeValue(null, ATTR_NAME);
            String path = in.getAttributeValue(null, ATTR_PATH);
            File target = null;
            if (TAG_ROOT_PATH.equals(tag)) {
                target = buildPath(DEVICE_ROOT, path);
            } else if (TAG_FILES_PATH.equals(tag)) {
                target = buildPath(context.getFilesDir(), path);
            } else if (TAG_CACHE_PATH.equals(tag)) {
                target = buildPath(context.getCacheDir(), path);
            } else if (TAG_EXTERNAL.equals(tag)) {
                target = buildPath(Environment.getExternalStorageDirectory(), path);
            }
            if (target != null) {
                strat.addRoot(name, target);
            }
        }
    }
    return strat;
}

23. ChangeLog#readChangeLogFromResource()

Project: ckChangeLog
File: ChangeLog.java
/**
     * Read change log from XML resource file.
     *
     * @param resId
     *         Resource ID of the XML file to read the change log from.
     * @param full
     *         If this is {@code true} the full change log is returned. Otherwise only changes for
     *         versions newer than the last version are returned.
     *
     * @return A {@code SparseArray} containing {@link ReleaseItem}s representing the (partial)
     *         change log.
     */
protected final SparseArray<ReleaseItem> readChangeLogFromResource(int resId, boolean full) {
    XmlResourceParser xml = mContext.getResources().getXml(resId);
    try {
        return readChangeLog(xml, full);
    } finally {
        xml.close();
    }
}

24. ChangeLogDialog#GetHTMLChangelog()

Project: browser-android
File: ChangeLogDialog.java
//Get the changelog in html code, this will be shown in the dialog's webview
private String GetHTMLChangelog(int aResourceId, Resources aResource) {
    String _Result = "<html><head>" + GetStyle() + "</head><body>";
    XmlResourceParser _xml = aResource.getXml(aResourceId);
    try {
        int eventType = _xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if ((eventType == XmlPullParser.START_TAG) && (_xml.getName().equals("release"))) {
                _Result = _Result + ParseReleaseTag(_xml);
            }
            eventType = _xml.next();
        }
    } catch (XmlPullParserException e) {
        Log.e(TAG, e.getMessage(), e);
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
    } finally {
        _xml.close();
    }
    _Result = _Result + "</body></html>";
    return _Result;
}

25. TableList#parseResource()

Project: brailleback
File: TableList.java
private void parseResource(Resources res) {
    XmlResourceParser p = res.getXml(R.xml.tablelist);
    try {
        int elementType;
        while ((elementType = p.next()) != XmlPullParser.END_DOCUMENT) {
            if (elementType != XmlPullParser.START_TAG) {
                continue;
            }
            if (p.getDepth() == 1) {
                p.require(XmlPullParser.START_TAG, null, TAG_TABLE_LIST);
                continue;
            } else if (p.getDepth() == 2) {
                p.require(XmlPullParser.START_TAG, null, TAG_TABLE);
                parseTable(p);
            } else {
                throw new RuntimeException(p.getPositionDescription() + ": Unexpected start tag");
            }
        }
    } catch (XmlPullParserException ex) {
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        p.close();
    }
}

26. WidgetOneApplication#initPlugin()

Project: appcan-android
File: WidgetOneApplication.java
private final void initPlugin() {
    int id = EUExUtil.getResXmlID("plugin");
    if (id == 0) {
        throw new RuntimeException(EUExUtil.getString("plugin_config_no_exist"));
    }
    XmlResourceParser plugins = getResources().getXml(id);
    if (null == mThirdPluginMgr) {
        mThirdPluginMgr = new ThirdPluginMgr(plugins, mListenerQueue, this);
    }
}

27. LaunchViewModel#parseDemos()

Project: AndroidBinding
File: LaunchViewModel.java
private void parseDemos() {
    DemoCategory current = null;
    DemoEntry entry = null;
    XmlResourceParser parser = mContext.getResources().getXml(R.xml.demos);
    try {
        int eventType = parser.getEventType();
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            switch(eventType) {
                case XmlResourceParser.START_TAG:
                    if (parser.getName().equals("category") && current == null) {
                        current = new DemoCategory(mContext, parser.getAttributeValue(null, "name"));
                    }
                    if (parser.getName().equals("entry")) {
                        if (current == null)
                            throw new Exception();
                        entry = new DemoEntry(parser.getAttributeValue(null, "name"), resolveVM(parser.getAttributeValue(null, "vm")), resolveLayout(parser.getAttributeValue(null, "layout")));
                        current.Entries.add(entry);
                    } else if (parser.getName().equals("raw")) {
                        if (entry != null) {
                            entry.Raws.add(new RawEntry(parser.getAttributeValue(null, "title"), resolveRaw(parser.getAttributeValue(null, "name")), parser.getAttributeValue(null, "type")));
                        }
                    }
                    break;
                case XmlResourceParser.END_TAG:
                    if (parser.getName().equals("category")) {
                        if (current == null)
                            throw new Exception();
                        Categories.add(current);
                        current = null;
                    }
                    break;
            }
            eventType = parser.next();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

28. PopupMenuBinderV30#createAndBindPopupMenu()

Project: AndroidBinding
File: PopupMenuBinderV30.java
public void createAndBindPopupMenu(View v, PopupMenu popup, int menuResId, Object viewModel) {
    // First inflate the menu - default action
    Activity activity = (Activity) v.getContext();
    if (menuResId > 0)
        popup.getMenuInflater().inflate(menuResId, popup.getMenu());
    // Now, parse the menu
    XmlResourceParser parser = activity.getResources().getXml(menuResId);
    try {
        int eventType = parser.getEventType();
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            if (eventType == XmlResourceParser.START_TAG) {
                int id = parser.getAttributeResourceValue(Binder.ANDROID_NAMESPACE, "id", -1);
                MenuItem mi = popup.getMenu().findItem(id);
                if (mi != null) {
                    mi.setOnMenuItemClickListener(this);
                    String nodeName = parser.getName();
                    if (id > 0) {
                        AttributeSet attrs = Xml.asAttributeSet(parser);
                        AbsMenuBridge item = null;
                        if ("item".equals(nodeName)) {
                            item = new MenuItemBridge(id, attrs, activity, viewModel);
                        } else if ("group".equals(nodeName)) {
                            item = new MenuGroupBridge(id, attrs, activity, viewModel);
                        }
                        if (item != null) {
                            items.put(id, item);
                        }
                    }
                }
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    for (AbsMenuBridge item : items.values()) {
        item.onCreateOptionItem(popup.getMenu());
        item.onPrepareOptionItem(popup.getMenu());
    }
}

29. ActionModeBinder#onCreateActionMode()

Project: AndroidBinding
File: ActionModeBinder.java
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
    mActionMode = mode;
    // First inflate the menu - default action
    mode.getMenuInflater().inflate(mMenuResId, menu);
    // Now, parse the menu
    XmlResourceParser parser = mContext.getResources().getXml(mMenuResId);
    try {
        int eventType = parser.getEventType();
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            if (eventType == XmlResourceParser.START_TAG) {
                int id = parser.getAttributeResourceValue(Binder.ANDROID_NAMESPACE, "id", -1);
                MenuItem mi = menu.findItem(id);
                if (mi != null) {
                    String nodeName = parser.getName();
                    if (id > 0) {
                        AttributeSet attrs = Xml.asAttributeSet(parser);
                        AbsMenuBridge item = null;
                        if ("item".equals(nodeName)) {
                            item = new MenuItemBridge(id, attrs, mContext, mModel, this);
                        } else if ("group".equals(nodeName)) {
                            item = new MenuGroupBridge(id, attrs, mContext, mModel, this);
                        }
                        if (item != null) {
                            items.put(id, item);
                        }
                    }
                }
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    for (AbsMenuBridge item : items.values()) {
        item.onCreateOptionItem(menu);
        item.onPrepareOptionItem(menu);
    }
    return true;
}

30. BindingActivityV30#inflate()

Project: AndroidBinding
File: BindingActivityV30.java
/*	private void rebindOptionsMenu(){
		if (optionsMenu_source==null || optionsMenu_id==null)
			return;
		if (!(optionsMenu_id.get() instanceof Integer)) return;
		if (optionsMenu_source instanceof IObservable){
			this.setAndBindOptionsMenu((Integer)optionsMenu_id.get(), ((IObservable<?>)optionsMenu_source).get());
		}
		else
			this.setAndBindOptionsMenu((Integer)optionsMenu_id.get(), optionsMenu_source);
	}
*/
protected boolean inflate(int xmlId) {
    XmlResourceParser parser = getResources().getXml(xmlId);
    try {
        int eventType = parser.getEventType();
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            if (eventType == XmlResourceParser.START_TAG) {
                String tagName = parser.getName().toLowerCase();
                if (tagName.equals("optionsmenu")) {
                    mBindableOptionsMenuRef = createBindableOptionsMenu();
                    if (mBindableOptionsMenuRef != null)
                        Binder.putBindingMapToView((View) mBindableOptionsMenuRef, Utility.createBindingMap(Xml.asAttributeSet(parser)));
                } else if (tagName.equals("rootview")) {
                    mBindableRootViewRef = createBindableRootView();
                    Binder.putBindingMapToView((View) mBindableRootViewRef, Utility.createBindingMap(Xml.asAttributeSet(parser)));
                } else if (tagName.equals("actionbar")) {
                    View bar = createBindableActionBar();
                    if (bar != null) {
                        mBindableActionBarRef = bar;
                        Binder.putBindingMapToView(bar, Utility.createBindingMap(Xml.asAttributeSet(parser)));
                    }
                }
            }
            eventType = parser.next();
        }
    } catch (Exception e) {
        BindingLog.exception("BindingActivityV30", new Exception("Problem with the Activity XML file", e));
        return false;
    }
    return true;
}

31. ContextMenuBinder#onCreateContextMenu()

Project: AndroidBinding
File: ContextMenuBinder.java
@SuppressWarnings("rawtypes")
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    // Activity should be the context, or else, nothing can do
    if (!(v.getContext() instanceof Activity))
        return;
    // TODO: modulize this dirty hack
    if (v instanceof ExpandableListView) {
        long ppos = ((ExpandableListView.ExpandableListContextMenuInfo) menuInfo).packedPosition;
        int child = ExpandableListView.getPackedPositionChild(ppos);
        int group = ExpandableListView.getPackedPositionGroup(ppos);
        try {
            ViewAttribute<?, ?> attr = Binder.getAttributeForView(v, "clickedItem");
            attr._setObject(((ExpandableListView) v).getExpandableListAdapter().getChild(group, child), new ArrayList<Object>());
            attr.notifyChanged(attr);
        } catch (AttributeNotDefinedException e) {
            e.printStackTrace();
        }
    } else if (v instanceof AdapterView) {
        int pos = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;
        try {
            ViewAttribute<?, ?> attr = Binder.getAttributeForView(v, "clickedItem");
            attr._setObject(((AdapterView) v).getItemAtPosition(pos), new ArrayList<Object>());
            attr.notifyChanged(attr);
        } catch (AttributeNotDefinedException e) {
            e.printStackTrace();
        }
    }
    // First inflate the menu - default action
    Activity activity = (Activity) v.getContext();
    activity.getMenuInflater().inflate(mMenuResId, menu);
    // Now, parse the menu
    XmlResourceParser parser = activity.getResources().getXml(mMenuResId);
    try {
        int eventType = parser.getEventType();
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            if (eventType == XmlResourceParser.START_TAG) {
                int id = parser.getAttributeResourceValue(Binder.ANDROID_NAMESPACE, "id", -1);
                MenuItem mi = menu.findItem(id);
                if (mi != null) {
                    mi.setOnMenuItemClickListener(this);
                    String nodeName = parser.getName();
                    if (id > 0) {
                        AttributeSet attrs = Xml.asAttributeSet(parser);
                        AbsMenuBridge item = null;
                        if ("item".equals(nodeName)) {
                            item = new MenuItemBridge(id, attrs, activity, mViewModel);
                        } else if ("group".equals(nodeName)) {
                            item = new MenuGroupBridge(id, attrs, activity, mViewModel);
                        }
                        if (item != null) {
                            items.put(id, item);
                        }
                    }
                }
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    for (AbsMenuBridge item : items.values()) {
        item.onCreateOptionItem(menu);
        item.onPrepareOptionItem(menu);
    }
}

32. ChangeLogDialog#getHTMLChangelog()

Project: android-proxy
File: ChangeLogDialog.java
//Get the changelog in html code, this will be shown in the dialog's webview
private String getHTMLChangelog(final int resourceId, final Resources resources, final int version) {
    boolean releaseFound = false;
    final StringBuilder changelogBuilder = new StringBuilder();
    changelogBuilder.append("<html>").append(getHead()).append("<body>");
    final XmlResourceParser xml = resources.getXml(resourceId);
    try {
        int eventType = xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if ((eventType == XmlPullParser.START_TAG) && (xml.getName().equals("release"))) {
                //Check if the version matches the release tag.
                //When version is 0 every release tag is parsed.
                final int versioncode = Integer.parseInt(xml.getAttributeValue(null, "versioncode"));
                if ((version == 0) || (versioncode == version)) {
                    parseReleaseTag(changelogBuilder, xml);
                    //At lease one release tag has been parsed.
                    releaseFound = true;
                }
            }
            eventType = xml.next();
        }
    } catch (XmlPullParserException e) {
        Log.e(TAG, e.getMessage(), e);
        return "";
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
        return "";
    } finally {
        xml.close();
    }
    changelogBuilder.append("</body></html>");
    //Check if there was a release tag parsed, if not return an empty string.
    if (releaseFound) {
        return changelogBuilder.toString();
    } else {
        return "";
    }
}

33. MdCompat#getColorStateList()

Project: android-md-core
File: MdCompat.java
/**
   * A temporary fix for android.content.res.ColorStateList.inflate
   */
public static ColorStateList getColorStateList(Context context, int resId) throws IOException, XmlPullParserException {
    XmlResourceParser parser = context.getResources().getXml(resId);
    AttributeSet attrs = Xml.asAttributeSet(parser);
    Resources r = context.getResources();
    final int innerDepth = parser.getDepth() + 2;
    int depth;
    int type;
    List<int[]> customStateList = new ArrayList<>();
    List<Integer> customColorList = new ArrayList<>();
    while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) {
        if (type != XmlPullParser.START_TAG || depth > innerDepth || !parser.getName().equals("item")) {
            continue;
        }
        // Parse all unrecognized attributes as state specifiers.
        int j = 0;
        final int numAttrs = attrs.getAttributeCount();
        int color = 0;
        float alpha = 1.0f;
        int[] stateSpec = new int[numAttrs];
        for (int i = 0; i < numAttrs; i++) {
            final int stateResId = attrs.getAttributeNameResource(i);
            switch(stateResId) {
                case android.R.attr.color:
                    int colorAttrId = attrs.getAttributeResourceValue(i, 0);
                    if (colorAttrId == 0) {
                        String colorAttrValue = attrs.getAttributeValue(i);
                        colorAttrId = Integer.valueOf(colorAttrValue.replace("?", ""));
                        color = getColorFromAttribute(context, colorAttrId);
                    } else {
                        color = ContextCompat.getColor(context, colorAttrId);
                    }
                    break;
                case android.R.attr.alpha:
                    try {
                        alpha = attrs.getAttributeFloatValue(i, 1.0f);
                    } catch (Exception e) {
                        String alphaAttrValue = attrs.getAttributeValue(i);
                        alpha = getFloatFromAttribute(context, Integer.valueOf(alphaAttrValue.replace("?", "")));
                    }
                    break;
                default:
                    stateSpec[j++] = attrs.getAttributeBooleanValue(i, false) ? stateResId : -stateResId;
            }
        }
        stateSpec = StateSet.trimStateSet(stateSpec, j);
        color = modulateColorAlpha(color, alpha);
        customColorList.add(color);
        customStateList.add(stateSpec);
    }
    int[] colors = new int[customColorList.size()];
    int[][] states = new int[customStateList.size()][];
    int i = 0;
    for (int n = states.length; i < n; i++) {
        colors[i] = customColorList.get(i);
        states[i] = customStateList.get(i);
    }
    return new ColorStateList(states, colors);
}

34. ReceiverReader#parsePackage()

Project: android-autostarts
File: ReceiverReader.java
private void parsePackage(android.content.pm.PackageInfo p) {
    // Open the manifest file
    XmlResourceParser xml = null;
    Resources resources = null;
    try {
        Context scannedAppContext = mContext.createPackageContext(p.packageName, 0);
        AssetManager assets = scannedAppContext.getAssets();
        xml = openManifest(scannedAppContext, assets);
        resources = new Resources(assets, mContext.getResources().getDisplayMetrics(), null);
    } catch (IOException e) {
        Log.e(TAG, "Unable to open manifest or resources for " + p.packageName, e);
    } catch (NameNotFoundException e) {
        Log.e(TAG, "Unable to open manifest or resources for " + p.packageName, e);
    } catch (NullPointerException e) {
        Log.e(TAG, "Error processing " + p.packageName + " - most likely," + " the createPackageContext() call failed; if so, your" + " application directory is somehow screwed up. Android" + " is probably to blame, since it shouldn't be happening. Skipping.", e);
    }
    if (xml == null)
        return;
    mAndroidPackage = p;
    mCurrentPackage = null;
    mCurrentXML = xml;
    mCurrentResources = resources;
    try {
        String tagName = null;
        mCurrentState = ParserState.Unknown;
        int eventType = xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch(eventType) {
                case XmlPullParser.START_TAG:
                    tagName = xml.getName();
                    if (tagName.equals("manifest"))
                        startManifest();
                    else if (tagName.equals("application"))
                        startApplication();
                    else if (tagName.equals("receiver"))
                        startReceiver();
                    else if (tagName.equals("intent-filter"))
                        startIntentFilter();
                    else if (tagName.equals("action"))
                        startAction();
                    break;
                case XmlPullParser.END_TAG:
                    tagName = xml.getName();
                    if (tagName.equals("manifest"))
                        endManifest();
                    else if (tagName.equals("application"))
                        endApplication();
                    else if (tagName.equals("receiver"))
                        endReceiver();
                    else if (tagName.equals("intent-filter"))
                        endIntentFilter();
                    else if (tagName.equals("action"))
                        endAction();
                    break;
            }
            eventType = xml.nextToken();
        }
    } catch (XmlPullParserException e) {
        Log.e(TAG, "Unable to process manifest for " + p.packageName, e);
    } catch (IOException e) {
        Log.e(TAG, "Unable to process manifest for " + p.packageName, e);
    } finally {
        mCurrentXML = null;
        mCurrentResources = null;
    }
}

35. SettingsActivity#loadDashboardFromResource()

Project: AcDisplay
File: SettingsActivity.java
/**
     * Parse the given XML file as a categories description, adding each
     * parsed categories and tiles into the target list.
     *
     * @param resourceId The XML resource to load and parse.
     * @param target     The list in which the parsed categories and tiles should be placed.
     */
protected final void loadDashboardFromResource(@XmlRes int resourceId, @NonNull List<DashboardCategory> target) {
    XmlResourceParser parser = null;
    try {
        parser = getResources().getXml(resourceId);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        int type;
        for (type = parser.next(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
            if (type == XmlPullParser.START_TAG)
                break;
        }
        String nodeName = parser.getName();
        if (!RESOURCE_TAG_DASHBOARD.equals(nodeName))
            throw new RuntimeException(String.format("XML document must start with <%s> tag; found %s at %s", RESOURCE_TAG_DASHBOARD, nodeName, parser.getPositionDescription()));
        for (type = parser.next(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
            if (type == XmlPullParser.END_TAG && parser.getDepth() <= 1)
                /* root tag */
                break;
            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                continue;
            }
            switch(parser.getName()) {
                case RESOURCE_TAG_DASHBOARD_CATEGORY:
                    DashboardCategory category = new DashboardCategory(this, attrs);
                    final int categoryDepth = parser.getDepth();
                    for (type = parser.next(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
                        if (type == XmlPullParser.END_TAG && parser.getDepth() <= categoryDepth)
                            break;
                        if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                            continue;
                        }
                        switch(parser.getName()) {
                            case RESOURCE_TAG_DASHBOARD_TILE:
                                DashboardTile tile = new DashboardTile(this, attrs);
                                Bundle bundle = null;
                                final int tileDepth = parser.getDepth();
                                for (type = parser.next(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
                                    if (type == XmlPullParser.END_TAG && parser.getDepth() <= tileDepth)
                                        break;
                                    if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                                        continue;
                                    }
                                    switch(parser.getName()) {
                                        case RESOURCE_TAG_DASHBOARD_TILE_EXTRA:
                                            if (bundle == null) {
                                                bundle = new Bundle();
                                            }
                                            getResources().parseBundleExtra(RESOURCE_TAG_DASHBOARD_TILE_EXTRA, attrs, bundle);
                                            XmlUtils.skipCurrentTag(parser);
                                            break;
                                        case RESOURCE_TAG_DASHBOARD_TILE_INTENT:
                                            tile.intent = Intent.parseIntent(getResources(), parser, attrs);
                                            break;
                                        default:
                                            XmlUtils.skipCurrentTag(parser);
                                    }
                                }
                                tile.fragmentArguments = bundle;
                                category.add(tile);
                                break;
                            default:
                                XmlUtils.skipCurrentTag(parser);
                        }
                    }
                    target.add(category);
                    break;
                default:
                    XmlUtils.skipCurrentTag(parser);
            }
        }
    } catch (XmlPullParserExceptionIOException |  e) {
        throw new RuntimeException("Error parsing categories", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

36. PackageLite#parse()

Project: ACDD
File: PackageLite.java
public static PackageLite parse(File file) {
    XmlResourceParser openXmlResourceParser = null;
    try {
        AssetManager assetManager = AssetManager.class.newInstance();
        Method addAssetPath = AssetManager.class.getMethod("addAssetPath", String.class);
        int intValue = (Integer) addAssetPath.invoke(assetManager, file.getAbsolutePath());
        if (intValue != 0) {
            openXmlResourceParser = assetManager.openXmlResourceParser(intValue, "AndroidManifest.xml");
        } else {
            openXmlResourceParser = assetManager.openXmlResourceParser(intValue, "AndroidManifest.xml");
        }
        if (openXmlResourceParser != null) {
            try {
                PackageLite parse = parse(openXmlResourceParser);
                if (parse == null) {
                    parse = new PackageLite();
                }
                openXmlResourceParser.close();
                return parse;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    } catch (Exception e) {
    } finally {
        if (openXmlResourceParser != null) {
            openXmlResourceParser.close();
        }
    }
    return null;
}

37. ChangeLogHelper#getHTMLChangelog()

Project: YourAppIdea
File: ChangeLogHelper.java
private String getHTMLChangelog(int resourceId, Resources resources, int fromVersion, Context context) {
    boolean releaseFound = false;
    StringBuilder changeLogBuilder = new StringBuilder("<html><head>");
    changeLogBuilder.append(getStyle()).append("</head><body>");
    XmlResourceParser xmlParser = resources.getXml(resourceId);
    try {
        int eventType = xmlParser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if ((eventType == XmlPullParser.START_TAG) && (xmlParser.getName().equals("release"))) {
                //Check if the version matches the release tag.
                //When version is 0 every release tag is parsed.
                int versionCode = Integer.parseInt(xmlParser.getAttributeValue(null, "versioncode"));
                if (versionCode > fromVersion) {
                    parseReleaseTag(changeLogBuilder, xmlParser, context);
                    //At lease one release tag has been parsed.
                    releaseFound = true;
                }
            }
            eventType = xmlParser.next();
        }
    } catch (XmlPullParserExceptionIOException |  e) {
        throw new RuntimeException(e);
    } finally {
        xmlParser.close();
    }
    changeLogBuilder.append("</body></html>");
    String changeLog = null;
    if (releaseFound) {
        changeLog = changeLogBuilder.toString();
    } else {
        changeLog = "";
    }
    return changeLog;
}

38. CreateUserAndBlog#getDeviceLanguage()

Project: WordPress-Android
File: CreateUserAndBlog.java
public static String getDeviceLanguage(Context context) {
    Resources resources = context.getResources();
    XmlResourceParser parser = resources.getXml(R.xml.wpcom_languages);
    Hashtable<String, String> entries = new Hashtable<String, String>();
    String matchedDeviceLanguage = "en - English";
    try {
        int eventType = parser.getEventType();
        String deviceLanguageCode = LanguageUtils.getPatchedCurrentDeviceLanguage(context);
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                String name = parser.getName();
                if (name.equals("language")) {
                    String currentID = null;
                    boolean currentLangIsDeviceLanguage = false;
                    int i = 0;
                    while (i < parser.getAttributeCount()) {
                        if (parser.getAttributeName(i).equals("id")) {
                            currentID = parser.getAttributeValue(i);
                        }
                        if (parser.getAttributeName(i).equals("code") && parser.getAttributeValue(i).equalsIgnoreCase(deviceLanguageCode)) {
                            currentLangIsDeviceLanguage = true;
                        }
                        i++;
                    }
                    while (eventType != XmlPullParser.END_TAG) {
                        if (eventType == XmlPullParser.TEXT) {
                            entries.put(parser.getText(), currentID);
                            if (currentLangIsDeviceLanguage) {
                                matchedDeviceLanguage = parser.getText();
                            }
                        }
                        eventType = parser.next();
                    }
                }
            }
            eventType = parser.next();
        }
    } catch (Exception e) {
    }
    return matchedDeviceLanguage;
}

39. UnifiedPreferenceHelper#loadLegacyHeadersFromResource()

Project: UnifiedPreference
File: UnifiedPreferenceHelper.java
/**
	 * Parse the given XML file as a header description, adding each parsed
	 * LegacyHeader into the target list.
	 * 
	 * @param resid The XML resource to load and parse.
	 * @param target The list in which the parsed headers should be placed.
	 */
public void loadLegacyHeadersFromResource(int resid, List<LegacyHeader> target) {
    XmlResourceParser parser = null;
    try {
        parser = mActivity.getResources().getXml(resid);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        int type;
        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
        // Parse next until start tag is found
        }
        String nodeName = parser.getName();
        if (!"preference-headers".equals(nodeName)) {
            throw new RuntimeException("XML document must start with <preference-headers> tag; found" + nodeName + " at " + parser.getPositionDescription());
        }
        final int outerDepth = parser.getDepth();
        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                continue;
            }
            nodeName = parser.getName();
            if ("header".equals(nodeName)) {
                LegacyHeader header = new LegacyHeader();
                TypedArray sa = mActivity.getResources().obtainAttributes(attrs, R.styleable.PreferenceHeader);
                TypedValue tv = sa.peekValue(R.styleable.PreferenceHeader_title);
                if (tv != null && tv.type == TypedValue.TYPE_STRING) {
                    if (tv.resourceId != 0) {
                        header.titleRes = tv.resourceId;
                    } else {
                        header.title = tv.string;
                    }
                }
                header.preferenceRes = sa.getResourceId(R.styleable.PreferenceHeader_preferenceRes, 0);
                sa.recycle();
                target.add(header);
            } else {
                XmlUtils.skipCurrentTag(parser);
            }
        }
    } catch (XmlPullParserException e) {
        throw new RuntimeException("Error parsing headers", e);
    } catch (IOException e) {
        throw new RuntimeException("Error parsing headers", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

40. UnifiedPreferenceHelper#loadHeadersFromResource()

Project: UnifiedPreference
File: UnifiedPreferenceHelper.java
/**
	 * Parse the given XML file as a header description, adding each parsed
	 * Header into the target list.
	 * 
	 * @param resid The XML resource to load and parse.
	 * @param target The list in which the parsed headers should be placed.
	 */
public void loadHeadersFromResource(int resid, List<Header> target) {
    XmlResourceParser parser = null;
    try {
        parser = mActivity.getResources().getXml(resid);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        int type;
        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
        // Parse next until start tag is found
        }
        String nodeName = parser.getName();
        if (!"preference-headers".equals(nodeName)) {
            throw new RuntimeException("XML document must start with <preference-headers> tag; found" + nodeName + " at " + parser.getPositionDescription());
        }
        Bundle curBundle = null;
        final int outerDepth = parser.getDepth();
        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                continue;
            }
            nodeName = parser.getName();
            if ("header".equals(nodeName)) {
                Header header = new Header();
                TypedArray sa = mActivity.getResources().obtainAttributes(attrs, R.styleable.PreferenceHeader);
                header.id = sa.getResourceId(R.styleable.PreferenceHeader_id, (int) HEADER_ID_UNDEFINED);
                TypedValue tv = sa.peekValue(R.styleable.PreferenceHeader_title);
                if (tv != null && tv.type == TypedValue.TYPE_STRING) {
                    if (tv.resourceId != 0) {
                        header.titleRes = tv.resourceId;
                    } else {
                        header.title = tv.string;
                    }
                }
                tv = sa.peekValue(R.styleable.PreferenceHeader_summary);
                if (tv != null && tv.type == TypedValue.TYPE_STRING) {
                    if (tv.resourceId != 0) {
                        header.summaryRes = tv.resourceId;
                    } else {
                        header.summary = tv.string;
                    }
                }
                tv = sa.peekValue(R.styleable.PreferenceHeader_breadCrumbTitle);
                if (tv != null && tv.type == TypedValue.TYPE_STRING) {
                    if (tv.resourceId != 0) {
                        header.breadCrumbTitleRes = tv.resourceId;
                    } else {
                        header.breadCrumbTitle = tv.string;
                    }
                }
                tv = sa.peekValue(R.styleable.PreferenceHeader_breadCrumbShortTitle);
                if (tv != null && tv.type == TypedValue.TYPE_STRING) {
                    if (tv.resourceId != 0) {
                        header.breadCrumbShortTitleRes = tv.resourceId;
                    } else {
                        header.breadCrumbShortTitle = tv.string;
                    }
                }
                header.iconRes = sa.getResourceId(R.styleable.PreferenceHeader_icon, 0);
                header.fragment = sa.getString(R.styleable.PreferenceHeader_fragment);
                if (curBundle == null) {
                    curBundle = new Bundle();
                }
                // Add preference resource to fragmentArgs
                int preference = sa.getResourceId(R.styleable.PreferenceHeader_preferenceRes, 0);
                if (preference > 0) {
                    curBundle.putInt(UnifiedPreferenceFragment.ARG_PREFERENCE_RES, preference);
                }
                sa.recycle();
                final int innerDepth = parser.getDepth();
                while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > innerDepth)) {
                    if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                        continue;
                    }
                    String innerNodeName = parser.getName();
                    if (innerNodeName.equals("extra")) {
                        mActivity.getResources().parseBundleExtra("extra", attrs, curBundle);
                        XmlUtils.skipCurrentTag(parser);
                    } else if (innerNodeName.equals("intent")) {
                        header.intent = Intent.parseIntent(mActivity.getResources(), parser, attrs);
                    } else {
                        XmlUtils.skipCurrentTag(parser);
                    }
                }
                if (curBundle.size() > 0) {
                    header.fragmentArguments = curBundle;
                    curBundle = null;
                }
                target.add(header);
            } else {
                XmlUtils.skipCurrentTag(parser);
            }
        }
    } catch (XmlPullParserException e) {
        throw new RuntimeException("Error parsing headers", e);
    } catch (IOException e) {
        throw new RuntimeException("Error parsing headers", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}

41. ListXmlParser#getListItemsFromResource()

Project: Tower
File: ListXmlParser.java
public void getListItemsFromResource(Context context, int resourceId) {
    XmlResourceParser is = context.getResources().getXml(resourceId);
    parse(is);
}

42. DataService#loadLevels()

Project: tilt-game-android
File: DataService.java
private void loadLevels(Intent intent) {
    XmlResourceParser parser = getResources().getXml(R.xml.levels);
    String levelPackage = "";
    String controllerPackage = "";
    List<LevelVO> newLevels = new ArrayList<>();
    try {
        parser.next();
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                switch(parser.getName()) {
                    case "levels":
                        levelPackage = parser.getAttributeValue(null, "levelpackage");
                        controllerPackage = parser.getAttributeValue(null, "controllerpackage");
                        break;
                    case "level":
                        newLevels.add(LevelVO.createFromXML(parser, levelPackage, controllerPackage));
                        break;
                }
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserExceptionIOException |  e) {
        e.printStackTrace();
    }
    List<LevelVO> allLevels = new ArrayList<>(newLevels);
    if (newLevels.size() > 0) {
        // retrieve current set of stored levels
        List<LevelVO> oldLevels = cupboard().withContext(this).query(LevelVO.URI, LevelVO.class).list();
        for (LevelVO oldLevelVO : oldLevels) {
            LevelVO newLevelVO = getLevelById(newLevels, oldLevelVO.id);
            if (newLevelVO != null) {
                newLevelVO.unlocked = oldLevelVO.unlocked;
            }
        }
        cupboard().withContext(this).put(LevelVO.URI, LevelVO.class, newLevels);
        // determine if there are new levels
        boolean hasNewLevels = (oldLevels.size() == 0) || newLevels.removeAll(oldLevels);
        // insert empty LevelResultVO instances into database for new levels
        if (hasNewLevels) {
            List<LevelResultVO> newResults = new ArrayList<>();
            for (LevelVO levelVO : newLevels) {
                newResults.add(new LevelResultVO(levelVO.id));
            }
            cupboard().withContext(this).put(LevelResultVO.URI, LevelResultVO.class, newResults);
        }
    }
    List<LevelResultVO> results = cupboard().withContext(this).query(LevelResultVO.URI, LevelResultVO.class).list();
    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(ACTION_LOAD_LEVELS).putParcelableArrayListExtra(KEY_LEVELS, (ArrayList<? extends Parcelable>) allLevels).putParcelableArrayListExtra(KEY_LEVEL_RESULTS, (ArrayList<? extends Parcelable>) results));
}

43. FileProvider#parsePathStrategy()

Project: telescope
File: FileProvider.java
/**
   * Parse and return {@link PathStrategy} for given authority as defined in
   * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code <meta-data>}.
   *
   * @see #getPathStrategy(Context, String)
   */
private static PathStrategy parsePathStrategy(Context context, String authority) throws IOException, XmlPullParserException {
    final SimplePathStrategy strat = new SimplePathStrategy(authority);
    final ProviderInfo info = context.getPackageManager().resolveContentProvider(authority, PackageManager.GET_META_DATA);
    final XmlResourceParser in = info.loadXmlMetaData(context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
    if (in == null) {
        throw new IllegalArgumentException("Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
    }
    int type;
    while ((type = in.next()) != END_DOCUMENT) {
        if (type == START_TAG) {
            final String tag = in.getName();
            final String name = in.getAttributeValue(null, ATTR_NAME);
            String path = in.getAttributeValue(null, ATTR_PATH);
            File target = null;
            if (TAG_ROOT_PATH.equals(tag)) {
                target = buildPath(DEVICE_ROOT, path);
            } else if (TAG_FILES_PATH.equals(tag)) {
                target = buildPath(context.getFilesDir(), path);
            } else if (TAG_CACHE_PATH.equals(tag)) {
                target = buildPath(context.getCacheDir(), path);
            } else if (TAG_EXTERNAL.equals(tag)) {
                target = buildPath(Environment.getExternalStorageDirectory(), path);
            } else if (TAG_EXTERNAL_APP.equals(tag)) {
                target = buildPath(context.getExternalFilesDir(null), path);
            }
            if (target != null) {
                strat.addRoot(name, target);
            }
        }
    }
    return strat;
}

44. ApnUtils#query()

Project: qksms
File: ApnUtils.java
/**
     * Query for apns using mcc and mnc codes found on the sim card or in the network settings.
     *
     * @param mcc mobile country code
     * @param mnc mobile network code
     * @param context context
     */
@SuppressWarnings("TryFinallyCanBeTryWithResources")
public static List<Apn> query(Context context, String mcc, String mnc) {
    ArrayList<Apn> result = new ArrayList<>();
    if (TextUtils.isEmpty(mcc) || TextUtils.isEmpty(mnc)) {
        Log.e(TAG, "Invalid mcc or mnc. {mcc:\"" + mcc + "\", mnc=\"" + mnc + "\"}");
        return result;
    }
    // Scan the apns master list to identify compatible APNs.
    XmlResourceParser parser = context.getResources().getXml(R.xml.apns);
    try {
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (isAPNStartTag(parser) && matches(parser, mcc, mnc)) {
                Apn apn = apnFromParser(parser);
                // Don't return duplicates!
                if (!result.contains(apn)) {
                    result.add(apn);
                }
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserExceptionIOException |  e) {
        Log.e(TAG, "Exception thrown while getting APNs", e);
    } finally {
        parser.close();
    }
    return result;
}

45. DrawableXmlParser#parse()

Project: polar-dashboard
File: DrawableXmlParser.java
public static List<Category> parse(@NonNull Context context, @XmlRes int xmlRes) {
    mCategories = new ArrayList<>();
    XmlResourceParser parser = null;
    try {
        parser = context.getResources().getXml(xmlRes);
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch(eventType) {
                case XmlPullParser.START_TAG:
                    final String tagName = parser.getName();
                    if (tagName.equalsIgnoreCase("category")) {
                        mCurrentCategory = new Category(parser.getAttributeValue(null, "title"));
                        mCategories.add(mCurrentCategory);
                    } else if (tagName.equalsIgnoreCase("item")) {
                        if (mCurrentCategory == null) {
                            mCurrentCategory = new Category(context.getString(R.string.default_category));
                            mCategories.add(mCurrentCategory);
                        }
                        mCurrentCategory.addItem(new Icon(parser.getAttributeValue(null, "drawable"), mCurrentCategory));
                    }
                    break;
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserExceptionIOException |  e) {
        e.printStackTrace();
    } finally {
        if (parser != null)
            parser.close();
    }
    mCurrentCategory = null;
    return mCategories;
}

46. GenericInflater#inflate()

Project: HoloEverywhere
File: GenericInflater.java
public T inflate(int resource, P root, boolean attachToRoot) {
    XmlResourceParser parser = getContext().getResources().getXml(resource);
    try {
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

47. PreferenceActivity#loadHeadersFromResource()

Project: HoloEverywhere
File: PreferenceActivity.java
public void loadHeadersFromResource(int resid, List<Header> target) {
    XmlResourceParser parser = null;
    try {
        parser = getResources().getXml(resid);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        int type;
        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && type != XmlPullParser.START_TAG) {
            ;
        }
        String nodeName = parser.getName();
        if (!"preference-headers".equals(nodeName)) {
            throw new RuntimeException("XML document must start with <preference-headers> tag; found" + nodeName + " at " + parser.getPositionDescription());
        }
        Bundle curBundle = null;
        final int outerDepth = parser.getDepth();
        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                continue;
            }
            nodeName = parser.getName();
            if ("header".equals(nodeName)) {
                Header header = new Header();
                TypedArray sa = getResources().obtainAttributes(attrs, R.styleable.PreferenceHeader);
                header.id = sa.getResourceId(R.styleable.PreferenceHeader_android_id, (int) PreferenceActivity.HEADER_ID_UNDEFINED);
                TypedValue tv = sa.peekValue(R.styleable.PreferenceHeader_android_title);
                if (tv != null && tv.type == TypedValue.TYPE_STRING) {
                    if (tv.resourceId != 0) {
                        header.titleRes = tv.resourceId;
                    } else {
                        header.title = tv.string;
                    }
                }
                tv = sa.peekValue(R.styleable.PreferenceHeader_android_summary);
                if (tv != null && tv.type == TypedValue.TYPE_STRING) {
                    if (tv.resourceId != 0) {
                        header.summaryRes = tv.resourceId;
                    } else {
                        header.summary = tv.string;
                    }
                }
                tv = sa.peekValue(R.styleable.PreferenceHeader_android_breadCrumbTitle);
                if (tv != null && tv.type == TypedValue.TYPE_STRING) {
                    if (tv.resourceId != 0) {
                        header.breadCrumbTitleRes = tv.resourceId;
                    } else {
                        header.breadCrumbTitle = tv.string;
                    }
                }
                tv = sa.peekValue(R.styleable.PreferenceHeader_android_breadCrumbShortTitle);
                if (tv != null && tv.type == TypedValue.TYPE_STRING) {
                    if (tv.resourceId != 0) {
                        header.breadCrumbShortTitleRes = tv.resourceId;
                    } else {
                        header.breadCrumbShortTitle = tv.string;
                    }
                }
                header.iconRes = sa.getResourceId(R.styleable.PreferenceHeader_android_icon, 0);
                header.fragment = sa.getString(R.styleable.PreferenceHeader_android_fragment);
                sa.recycle();
                if (curBundle == null) {
                    curBundle = new Bundle();
                }
                final int innerDepth = parser.getDepth();
                while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > innerDepth)) {
                    if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                        continue;
                    }
                    String innerNodeName = parser.getName();
                    if (innerNodeName.equals("extra")) {
                        getResources().parseBundleExtra("extra", attrs, curBundle);
                        XmlUtils.skipCurrentTag(parser);
                    } else if (innerNodeName.equals("intent")) {
                        header.intent = Intent.parseIntent(getResources(), parser, attrs);
                    } else {
                        XmlUtils.skipCurrentTag(parser);
                    }
                }
                if (curBundle.size() > 0) {
                    header.fragmentArguments = curBundle;
                    curBundle = null;
                }
                target.add(header);
            } else {
                XmlUtils.skipCurrentTag(parser);
            }
        }
    } catch (XmlPullParserException e) {
        throw new RuntimeException("Error parsing headers", e);
    } catch (IOException e) {
        throw new RuntimeException("Error parsing headers", e);
    } finally {
        if (parser != null) {
            parser.close();
        }
    }
}

48. SettingsActivity#loadDashboardFromResource()

Project: HeadsUp
File: SettingsActivity.java
/**
     * Parse the given XML file as a categories description, adding each
     * parsed categories and tiles into the target list.
     *
     * @param resourceId The XML resource to load and parse.
     * @param target     The list in which the parsed categories and tiles should be placed.
     */
protected final void loadDashboardFromResource(@XmlRes int resourceId, @NonNull List<DashboardCategory> target) {
    XmlResourceParser parser = null;
    try {
        parser = getResources().getXml(resourceId);
        AttributeSet attrs = Xml.asAttributeSet(parser);
        int type;
        for (type = parser.next(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
            if (type == XmlPullParser.START_TAG)
                break;
        }
        String nodeName = parser.getName();
        if (!RESOURCE_TAG_DASHBOARD.equals(nodeName))
            throw new RuntimeException(String.format("XML document must start with <%s> tag; found %s at %s", RESOURCE_TAG_DASHBOARD, nodeName, parser.getPositionDescription()));
        for (type = parser.next(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
            if (type == XmlPullParser.END_TAG && parser.getDepth() <= 1)
                /* root tag */
                break;
            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                continue;
            }
            switch(parser.getName()) {
                case RESOURCE_TAG_DASHBOARD_CATEGORY:
                    DashboardCategory category = new DashboardCategory(this, attrs);
                    final int categoryDepth = parser.getDepth();
                    for (type = parser.next(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
                        if (type == XmlPullParser.END_TAG && parser.getDepth() <= categoryDepth)
                            break;
                        if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                            continue;
                        }
                        switch(parser.getName()) {
                            case RESOURCE_TAG_DASHBOARD_TILE:
                                DashboardTile tile = new DashboardTile(this, attrs);
                                Bundle bundle = null;
                                final int tileDepth = parser.getDepth();
                                for (type = parser.next(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
                                    if (type == XmlPullParser.END_TAG && parser.getDepth() <= tileDepth)
                                        break;
                                    if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
                                        continue;
                                    }
                                    switch(parser.getName()) {
                                        case RESOURCE_TAG_DASHBOARD_TILE_EXTRA:
                                            if (bundle == null) {
                                                bundle = new Bundle();
                                            }
                                            getResources().parseBundleExtra(RESOURCE_TAG_DASHBOARD_TILE_EXTRA, attrs, bundle);
                                            XmlUtils.skipCurrentTag(parser);
                                            break;
                                        case RESOURCE_TAG_DASHBOARD_TILE_INTENT:
                                            tile.intent = Intent.parseIntent(getResources(), parser, attrs);
                                            break;
                                        default:
                                            XmlUtils.skipCurrentTag(parser);
                                    }
                                }
                                tile.fragmentArguments = bundle;
                                category.add(tile);
                                break;
                            default:
                                XmlUtils.skipCurrentTag(parser);
                        }
                    }
                    target.add(category);
                    break;
                default:
                    XmlUtils.skipCurrentTag(parser);
            }
        }
    } catch (XmlPullParserExceptionIOException |  e) {
        throw new RuntimeException("Error parsing categories", e);
    } finally {
        if (parser != null)
            parser.close();
    }
}