List of usage examples for android.content.res Resources getXml
@NonNull public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException
From source file:com.androzic.Preferences.java
/** * Parse the given XML file as a header description, adding each * parsed Header into the target list.//from w w w .ja v a 2 s.c om * * @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) { Androzic application = Androzic.getApplication(); XmlResourceParser parser = null; try { Resources resources = getResources(); parser = resources.getXml(resid); AttributeSet attrs = Xml.asAttributeSet(parser); int type; //noinspection StatementWithEmptyBody 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 = resources.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); header.help = sa.getResourceId(R.styleable.PreferenceHeader_help, 0); 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")) { resources.parseBundleExtra(innerNodeName, attrs, curBundle); XmlUtils.skipCurrentTag(parser); } else if (innerNodeName.equals("intent")) { header.intent = Intent.parseIntent(resources, parser, attrs); } else { XmlUtils.skipCurrentTag(parser); } } if (curBundle.size() > 0) { header.fragmentArguments = curBundle; curBundle = null; } if (header.id == R.id.pref_plugins && application.getPluginsPreferences().size() == 0) continue; target.add(header); } else { XmlUtils.skipCurrentTag(parser); } } } catch (XmlPullParserException | IOException e) { throw new RuntimeException("Error parsing headers", e); } finally { if (parser != null) parser.close(); } }
From source file:android.support.graphics.drawable.VectorDrawableCompat.java
/** * Create a VectorDrawableCompat object. * * @param res the resources.//from ww w . ja v a2s.c o m * @param resId the resource ID for VectorDrawableCompat object. * @param theme the theme of this vector drawable, it can be null. * @return a new VectorDrawableCompat or null if parsing error is found. */ @Nullable public static VectorDrawableCompat create(@NonNull Resources res, @DrawableRes int resId, @Nullable Theme theme) { if (Build.VERSION.SDK_INT >= 23) { final VectorDrawableCompat drawable = new VectorDrawableCompat(); drawable.mDelegateDrawable = ResourcesCompat.getDrawable(res, resId, theme); drawable.mCachedConstantStateDelegate = new VectorDrawableDelegateState( drawable.mDelegateDrawable.getConstantState()); return drawable; } try { final XmlPullParser parser = res.getXml(resId); final AttributeSet attrs = Xml.asAttributeSet(parser); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty loop } if (type != XmlPullParser.START_TAG) { throw new XmlPullParserException("No start tag found"); } return createFromXmlInner(res, parser, attrs, theme); } catch (XmlPullParserException e) { Log.e(LOGTAG, "parser error", e); } catch (IOException e) { Log.e(LOGTAG, "parser error", e); } return null; }
From source file:android.support.v7.widget.AppCompatDrawableManager.java
private Drawable loadDrawableFromDelegates(@NonNull Context context, @DrawableRes int resId) { if (mDelegates != null && !mDelegates.isEmpty()) { if (mKnownDrawableIdTags != null) { final String cachedTagName = mKnownDrawableIdTags.get(resId); if (SKIP_DRAWABLE_TAG.equals(cachedTagName) || (cachedTagName != null && mDelegates.get(cachedTagName) == null)) { // If we don't have a delegate for the drawable tag, or we've been set to // skip it, fail fast and return null if (DEBUG) { Log.d(TAG, "[loadDrawableFromDelegates] Skipping drawable: " + context.getResources().getResourceName(resId)); }//from ww w . java 2 s. c om return null; } } else { // Create an id cache as we'll need one later mKnownDrawableIdTags = new SparseArray<>(); } if (mTypedValue == null) { mTypedValue = new TypedValue(); } final TypedValue tv = mTypedValue; final Resources res = context.getResources(); res.getValue(resId, tv, true); final long key = createCacheKey(tv); Drawable dr = getCachedDrawable(context, key); if (dr != null) { if (DEBUG) { Log.i(TAG, "[loadDrawableFromDelegates] Returning cached drawable: " + context.getResources().getResourceName(resId)); } // We have a cached drawable, return it! return dr; } if (tv.string != null && tv.string.toString().endsWith(".xml")) { // If the resource is an XML file, let's try and parse it try { final XmlPullParser parser = res.getXml(resId); final AttributeSet attrs = Xml.asAttributeSet(parser); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty loop } if (type != XmlPullParser.START_TAG) { throw new XmlPullParserException("No start tag found"); } final String tagName = parser.getName(); // Add the tag name to the cache mKnownDrawableIdTags.append(resId, tagName); // Now try and find a delegate for the tag name and inflate if found final InflateDelegate delegate = mDelegates.get(tagName); if (delegate != null) { dr = delegate.createFromXmlInner(context, parser, attrs, context.getTheme()); } if (dr != null) { // Add it to the drawable cache dr.setChangingConfigurations(tv.changingConfigurations); if (addDrawableToCache(context, key, dr) && DEBUG) { Log.i(TAG, "[loadDrawableFromDelegates] Saved drawable to cache: " + context.getResources().getResourceName(resId)); } } } catch (Exception e) { Log.e(TAG, "Exception while inflating drawable", e); } } if (dr == null) { // If we reach here then the delegate inflation of the resource failed. Mark it as // bad so we skip the id next time mKnownDrawableIdTags.append(resId, SKIP_DRAWABLE_TAG); } return dr; } return null; }
From source file:br.liveo.ndrawer.ui.activity.MainActivity.java
License:asdf
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private void startDevice() { mProgressDialog = new ProgressDialog(this); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIndeterminate(true); mProgressDialog.setTitle("? ? ..."); mProgressDialog.setMessage(""); mProgressDialog.setMax(100);/*from w w w . j a v a 2 s .com*/ mProgressDialog.setProgress(0); mProgressDialog.show(); /* mlblMessage.setText("?? ."); mBtnStart.setEnabled(false); mBtnStart.setVisibility(View.INVISIBLE); */ // GATT database Resources res = getResources(); XmlResourceParser xpp = res.getXml(R.xml.gatt_uuid); new GattInfo(xpp); if (!mReceiving) { registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter()); mReceiving = true; } if (mGatt != null) { if (mGatt.getServices().size() == 0) discoverServices(); else { } } }
From source file:android.support.v7ox.widget.AppCompatDrawableManager.java
private Drawable loadDrawableFromDelegates(@NonNull Context context, @DrawableRes int resId) { if (mDelegates != null && !mDelegates.isEmpty()) { if (mKnownDrawableIdTags != null) { final String cachedTagName = mKnownDrawableIdTags.get(resId); if (SKIP_DRAWABLE_TAG.equals(cachedTagName) || (cachedTagName != null && mDelegates.get(cachedTagName) == null)) { // If we don't have a delegate for the drawable tag, or we've been set to // skip it, fail fast and return null if (DEBUG) { Log.d(TAG, "[loadDrawableFromDelegates] Skipping drawable: " + context.getResources().getResourceName(resId)); }/*from w ww . j ava 2s .com*/ return null; } } else { // Create an id cache as we'll need one later mKnownDrawableIdTags = new SparseArray<>(); } if (mTypedValue == null) { mTypedValue = new TypedValue(); } final TypedValue tv = mTypedValue; final Resources res = context.getResources(); res.getValue(resId, tv, true); final long key = (((long) tv.assetCookie) << 32) | tv.data; Drawable dr = getCachedDelegateDrawable(context, key); if (dr != null) { if (DEBUG) { Log.i(TAG, "[loadDrawableFromDelegates] Returning cached drawable: " + context.getResources().getResourceName(resId)); } // We have a cached drawable, return it! return dr; } if (tv.string != null && tv.string.toString().endsWith(".xml")) { // If the resource is an XML file, let's try and parse it try { final XmlPullParser parser = res.getXml(resId); final AttributeSet attrs = Xml.asAttributeSet(parser); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty loop } if (type != XmlPullParser.START_TAG) { throw new XmlPullParserException("No start tag found"); } final String tagName = parser.getName(); // Add the tag name to the cache mKnownDrawableIdTags.append(resId, tagName); // Now try and find a delegate for the tag name and inflate if found final InflateDelegate delegate = mDelegates.get(tagName); if (delegate != null) { dr = delegate.createFromXmlInner(context, parser, attrs, context.getTheme()); } if (dr != null) { // Add it to the drawable cache dr.setChangingConfigurations(tv.changingConfigurations); if (addCachedDelegateDrawable(context, key, dr) && DEBUG) { Log.i(TAG, "[loadDrawableFromDelegates] Saved drawable to cache: " + context.getResources().getResourceName(resId)); } } } catch (Exception e) { Log.e(TAG, "Exception while inflating drawable", e); } } if (dr == null) { // If we reach here then the delegate inflation of the resource failed. Mark it as // bad so we skip the id next time mKnownDrawableIdTags.append(resId, SKIP_DRAWABLE_TAG); } return dr; } return null; }
From source file:com.androidclub.source.XmlDocumentProvider.java
/** * Creates an XmlPullParser for the provided local resource. Can be overloaded to provide your * own parser.//from w w w .j a v a 2 s. c om * @param resourceUri A fully qualified resource name referencing a local XML resource. * @return An XmlPullParser on this resource. */ protected XmlPullParser getResourceXmlPullParser(Uri resourceUri) { //OpenResourceIdResult resourceId; try { String authority = resourceUri.getAuthority(); Resources r; if (TextUtils.isEmpty(authority)) { throw new FileNotFoundException("No authority: " + resourceUri); } else { try { r = getContext().getPackageManager().getResourcesForApplication(authority); } catch (NameNotFoundException ex) { throw new FileNotFoundException("No package found for authority: " + resourceUri); } } List<String> path = resourceUri.getPathSegments(); if (path == null) { throw new FileNotFoundException("No path: " + resourceUri); } int len = path.size(); int id; if (len == 1) { try { id = Integer.parseInt(path.get(0)); } catch (NumberFormatException e) { throw new FileNotFoundException("Single path segment is not a resource ID: " + resourceUri); } } else if (len == 2) { id = r.getIdentifier(path.get(1), path.get(0), authority); } else { throw new FileNotFoundException("More than two path segments: " + resourceUri); } if (id == 0) { throw new FileNotFoundException("No resource found for: " + resourceUri); } return r.getXml(id); } catch (FileNotFoundException e) { Log.w(LOG_TAG, "XML resource not found: " + resourceUri.toString(), e); return null; } }
From source file:org.distantshoresmedia.keyboard.LatinIME.java
/** * Loads a dictionary or multiple separated dictionary * * @return returns array of dictionary resource ids *//*ww w . j a v a 2 s .c om*/ /* package */static int[] getDictionary(Resources res) { String packageName = LatinIME.class.getPackage().getName(); XmlResourceParser xrp = res.getXml(R.xml.dictionary); ArrayList<Integer> dictionaries = new ArrayList<Integer>(); try { int current = xrp.getEventType(); while (current != XmlResourceParser.END_DOCUMENT) { if (current == XmlResourceParser.START_TAG) { String tag = xrp.getName(); if (tag != null) { if (tag.equals("part")) { String dictFileName = xrp.getAttributeValue(null, "name"); dictionaries.add(res.getIdentifier(dictFileName, "raw", packageName)); } } } xrp.next(); current = xrp.getEventType(); } } catch (XmlPullParserException e) { Log.e(TAG, "Dictionary XML parsing failure"); } catch (IOException e) { Log.e(TAG, "Dictionary XML IOException"); } int count = dictionaries.size(); int[] dict = new int[count]; for (int i = 0; i < count; i++) { dict[i] = dictionaries.get(i); } return dict; }
From source file:com.android.server.MountService.java
private void readStorageListLocked() { mVolumes.clear();/*from w ww. j av a 2s .c o m*/ mVolumeStates.clear(); Resources resources = mContext.getResources(); int id = com.android.internal.R.xml.storage_list; XmlResourceParser parser = resources.getXml(id); AttributeSet attrs = Xml.asAttributeSet(parser); try { XmlUtils.beginDocument(parser, TAG_STORAGE_LIST); while (true) { XmlUtils.nextElement(parser); String element = parser.getName(); if (element == null) break; if (TAG_STORAGE.equals(element)) { TypedArray a = resources.obtainAttributes(attrs, com.android.internal.R.styleable.Storage); String path = a.getString(com.android.internal.R.styleable.Storage_mountPoint); int descriptionId = a.getResourceId(com.android.internal.R.styleable.Storage_storageDescription, -1); CharSequence description = a .getText(com.android.internal.R.styleable.Storage_storageDescription); boolean primary = a.getBoolean(com.android.internal.R.styleable.Storage_primary, false); boolean removable = a.getBoolean(com.android.internal.R.styleable.Storage_removable, false); boolean emulated = a.getBoolean(com.android.internal.R.styleable.Storage_emulated, false); int mtpReserve = a.getInt(com.android.internal.R.styleable.Storage_mtpReserve, 0); boolean allowMassStorage = a .getBoolean(com.android.internal.R.styleable.Storage_allowMassStorage, false); boolean allowMtp = a.getBoolean(com.android.internal.R.styleable.Storage_allowMtp, true); // resource parser does not support longs, so XML value is in megabytes long maxFileSize = a.getInt(com.android.internal.R.styleable.Storage_maxFileSize, 0) * 1024L * 1024L; Slog.d(TAG, "got storage path: " + path + " description: " + description + " primary: " + primary + " removable: " + removable + " emulated: " + emulated + " mtpReserve: " + mtpReserve + " allowMassStorage: " + allowMassStorage + " maxFileSize: " + maxFileSize + " allowMtp: " + allowMtp); if (emulated) { // For devices with emulated storage, we create separate // volumes for each known user. mEmulatedTemplate = new StorageVolume(null, descriptionId, true, false, true, mtpReserve, false, maxFileSize, null, allowMtp); final UserManagerService userManager = UserManagerService.getInstance(); for (UserInfo user : userManager.getUsers(false)) { createEmulatedVolumeForUserLocked(user.getUserHandle()); } } else { if (path == null || description == null) { Slog.e(TAG, "Missing storage path or description in readStorageList"); } else { final StorageVolume volume = new StorageVolume(new File(path), descriptionId, primary, removable, emulated, mtpReserve, allowMassStorage, maxFileSize, null, allowMtp); addVolumeLocked(volume); // Until we hear otherwise, treat as unmounted mVolumeStates.put(volume.getPath(), Environment.MEDIA_UNMOUNTED); volume.setState(Environment.MEDIA_UNMOUNTED); } } a.recycle(); } } } catch (XmlPullParserException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { // Compute storage ID for each physical volume; emulated storage is // always 0 when defined. int index = isExternalStorageEmulated() ? 1 : 0; for (StorageVolume volume : mVolumes) { if (!volume.isEmulated()) { volume.setStorageId(index++); } } parser.close(); } }