Java Code Examples for android.content.res.XmlResourceParser#next()

The following examples show how to use android.content.res.XmlResourceParser#next() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WhatsNewDialog.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
private void readRelease(XmlResourceParser parser) throws XmlPullParserException, IOException {
    parser.require(XmlPullParser.START_TAG, null, TAG_RELEASE);
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        if (name.equals(TAG_CHANGE)) {
            parser.require(XmlPullParser.START_TAG, null, TAG_CHANGE);
            String variant = parser.getAttributeValue(null, ATTRIBUTE_VARIANT);
            ChangeListItem changeItem = new ChangeListItem();
            changeItem.change = readText(parser);
            if (BuildConfig.FULL_VERSION || !"full".equals(variant))
                mChangelog.add(changeItem);
            parser.require(XmlPullParser.END_TAG, null, TAG_CHANGE);
        } else {
            skip(parser);
        }
    }
    parser.require(XmlPullParser.END_TAG, null, TAG_RELEASE);
}
 
Example 2
Source File: XmlConfigSource.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private Domain parseDomain(XmlResourceParser parser, Set<String> seenDomains)
        throws IOException, XmlPullParserException, ParserException {
    boolean includeSubdomains =
            parser.getAttributeBooleanValue(null, "includeSubdomains", false);
    if (parser.next() != XmlPullParser.TEXT) {
        throw new ParserException(parser, "Domain name missing");
    }
    String domain = parser.getText().trim().toLowerCase(Locale.US);
    if (parser.next() != XmlPullParser.END_TAG) {
        throw new ParserException(parser, "domain contains additional elements");
    }
    // Domains are matched using a most specific match, so don't allow duplicates.
    // includeSubdomains isn't relevant here, both android.com + subdomains and android.com
    // match for android.com equally. Do not allow any duplicates period.
    if (!seenDomains.add(domain)) {
        throw new ParserException(parser, domain + " has already been specified");
    }
    return new Domain(domain, includeSubdomains);
}
 
Example 3
Source File: XmlHelper.java    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
@NonNull
public static Map<String, String> getFilterMap(XmlResourceParser parser)
        throws XmlPullParserException, IOException {
    Map<String, String> map = new HashMap<>();

    for (int type = parser.getEventType(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
        if (type == XmlPullParser.START_TAG && Constants.FILTER_TAG_ITEM.equals(parser.getName())) {
            map.put(
                    parser.getAttributeValue(null, Constants.FILTER_TAG_NAME),
                    parser.getAttributeValue(null, Constants.FILTER_TAG_VALUE)
            );
        }
    }

    return map;
}
 
Example 4
Source File: SpriteSheetAnimation.java    From tilt-game-android with MIT License 6 votes vote down vote up
private ArrayList<FrameVO> parseXML(XmlResourceParser parser) {
	ArrayList<FrameVO> frames = new ArrayList<>();

	try {
		parser.next();
		int eventType = parser.getEventType();

		while (eventType != XmlPullParser.END_DOCUMENT) {
			if (eventType == XmlPullParser.START_TAG) {
				if (parser.getName().equals("TextureAtlas")) {
				} else if (parser.getName().equals("SubTexture")) {
					frames.add(new FrameVO(parser));
				}
			}
			eventType = parser.next();
		}
	} catch (XmlPullParserException | IOException e) {
		e.printStackTrace();
	}

	return frames;
}
 
Example 5
Source File: BundleParser.java    From Small with Apache License 2.0 5 votes vote down vote up
private static void skipCurrentTag(XmlResourceParser parser)
        throws XmlPullParserException, IOException {
    int outerDepth = parser.getDepth();
    int type;
    while ((type=parser.next()) != XmlResourceParser.END_DOCUMENT
            && (type != XmlResourceParser.END_TAG
            || parser.getDepth() > outerDepth)) {
    }
}
 
Example 6
Source File: LiteIconActivity.java    From NanoIconPackLite with Apache License 2.0 5 votes vote down vote up
private List<Cate> getIcons() {
    List<Cate> dataList = new ArrayList<>();
    Cate defCate = new Cate(null);
    XmlResourceParser parser = getResources().getXml(R.xml.drawable);
    try {
        int event = parser.getEventType();
        while (event != XmlPullParser.END_DOCUMENT) {
            if (event == XmlPullParser.START_TAG) {
                switch (parser.getName()) {
                    case "category":
                        dataList.add(new Cate(parser.getAttributeValue(null, "title")));
                        break;
                    case "item":
                        String iconName = parser.getAttributeValue(null, "drawable");
                        if (dataList.isEmpty()) {
                            defCate.pushIcon(iconName);
                        } else {
                            dataList.get(dataList.size() - 1).pushIcon(iconName);
                        }
                        break;
                }
            }
            event = parser.next();
        }
        if (!defCate.isEmpty()) {
            dataList.add(defCate);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return dataList;
}
 
Example 7
Source File: ManifestParser.java    From Neptune with Apache License 2.0 5 votes vote down vote up
/**
 * 解析Manifest节点
 */
private void parseManifest(XmlResourceParser parser) throws IOException, XmlPullParserException {
    int type;
    while ((type = parser.next()) != XmlPullParser.START_TAG
            && type != XmlPullParser.END_DOCUMENT) {
        // go on to find START_TAG
    }

    if (type != XmlPullParser.START_TAG) {
        throw new XmlPullParserException("No start tag found");
    }
    if (!parser.getName().equals("manifest")) {
        throw new XmlPullParserException("No <manifest> tag");
    }

    pkg = parser.getAttributeValue(null, "package");
    Log.i(TAG, "parsed packageName=" + pkg);

    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;
        }

        String tagName = parser.getName();
        if (tagName.equals("application")) {
            // found Application Tag
            parseApplication(parser);
        }
    }
}
 
Example 8
Source File: XmlConfigSource.java    From cwac-netsecurity with Apache License 2.0 5 votes vote down vote up
private Pin parsePin(XmlResourceParser parser)
        throws IOException, XmlPullParserException, ParserException {
    String digestAlgorithm = parser.getAttributeValue(null, "digest");
    if (!Pin.isSupportedDigestAlgorithm(digestAlgorithm)) {
        throw new ParserException(parser, "Unsupported pin digest algorithm: "
                + digestAlgorithm);
    }
    if (parser.next() != XmlPullParser.TEXT) {
        throw new ParserException(parser, "Missing pin digest");
    }
    String digest = parser.getText().trim();
    byte[] decodedDigest = null;
    try {
        decodedDigest = Base64.decode(digest, 0);
    } catch (IllegalArgumentException e) {
        throw new ParserException(parser, "Invalid pin digest", e);
    }
    int expectedLength = Pin.getDigestLength(digestAlgorithm);
    if (decodedDigest.length != expectedLength) {
        throw new ParserException(parser, "digest length " + decodedDigest.length
                + " does not match expected length for " + digestAlgorithm + " of "
                + expectedLength);
    }
    if (parser.next() != XmlPullParser.END_TAG) {
        throw new ParserException(parser, "pin contains additional elements");
    }
    return new Pin(digestAlgorithm, decodedDigest);
}
 
Example 9
Source File: XmlPreferenceParser.java    From WearPreferenceActivity with Apache License 2.0 5 votes vote down vote up
private void parsePreferences(@NonNull final Context context, @NonNull final XmlResourceParser parser, @NonNull final WearPreferenceScreen screen)
        throws XmlPullParserException, IOException {

    if(parser.getEventType() == XmlResourceParser.START_TAG) {
        parser.next();
        while(parser.getEventType() != XmlResourceParser.END_TAG) {
            parseItem(context, parser, screen);
            parser.next();
        }
    }
}
 
Example 10
Source File: PluginManifestParser.java    From Android-Plugin-Framework with MIT License 5 votes vote down vote up
private static String addIntentFilter(HashMap<String, ArrayList<PluginIntentFilter>> map, String packageName, String namespace,
                                         XmlResourceParser parser, String endTagName) throws XmlPullParserException, IOException {
	int eventType = parser.getEventType();
	String activityName = parser.getAttributeValue(namespace, "name");
	activityName = getName(activityName, packageName);

	ArrayList<PluginIntentFilter> filters = map.get(activityName);
	if (filters == null) {
		filters = new ArrayList<PluginIntentFilter>();
           map.put(activityName, filters);
	}
	
	PluginIntentFilter intentFilter = new PluginIntentFilter();
	do {
		switch (eventType) {
			case XmlPullParser.START_TAG: {
				String tag = parser.getName();
				if ("intent-filter".equals(tag)) {
					intentFilter = new PluginIntentFilter();
					filters.add(intentFilter);
				} else {
					intentFilter.readFromXml(tag, namespace, parser);
				}
			}
		}
		eventType = parser.next();
	} while (!endTagName.equals(parser.getName()));//再次到达,表示一个标签结束了

       return activityName;
}
 
Example 11
Source File: ZenModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private ZenModeConfig readDefaultConfig(Resources resources) {
    XmlResourceParser parser = null;
    try {
        parser = resources.getXml(R.xml.default_zen_mode_config);
        while (parser.next() != XmlPullParser.END_DOCUMENT) {
            final ZenModeConfig config = ZenModeConfig.readXml(parser);
            if (config != null) return config;
        }
    } catch (Exception e) {
        Log.w(TAG, "Error reading default zen mode config from resource", e);
    } finally {
        IoUtils.closeQuietly(parser);
    }
    return new ZenModeConfig();
}
 
Example 12
Source File: IconsHelper.java    From candybar with Apache License 2.0 4 votes vote down vote up
@NonNull
public static List<Icon> getIconsList(@NonNull Context context) throws Exception {
    XmlResourceParser parser = context.getResources().getXml(R.xml.drawable);
    int eventType = parser.getEventType();
    String sectionTitle = "";
    List<Icon> icons = new ArrayList<>();
    List<Icon> sections = new ArrayList<>();

    int count = 0;
    while (eventType != XmlPullParser.END_DOCUMENT) {
        if (eventType == XmlPullParser.START_TAG) {
            if (parser.getName().equals("category")) {
                String title = parser.getAttributeValue(null, "title");
                if (!sectionTitle.equals(title)) {
                    if (sectionTitle.length() > 0) {
                        count += icons.size();
                        sections.add(new Icon(sectionTitle, icons));
                    }
                }
                sectionTitle = title;
                icons = new ArrayList<>();
            } else if (parser.getName().equals("item")) {
                String name = parser.getAttributeValue(null, "drawable");
                String customName = parser.getAttributeValue(null, "name");
                int id = getResourceId(context, name);
                if (id > 0) {
                    icons.add(new Icon(name, customName, id));
                }
            }
        }

        eventType = parser.next();
    }
    count += icons.size();
    CandyBarMainActivity.sIconsCount = count;
    if (!CandyBarApplication.getConfiguration().isAutomaticIconsCountEnabled() &&
            CandyBarApplication.getConfiguration().getCustomIconsCount() == 0) {
        CandyBarApplication.getConfiguration().setCustomIconsCount(count);
    }
    sections.add(new Icon(sectionTitle, icons));
    parser.close();
    return sections;
}
 
Example 13
Source File: WallpaperInfo.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor.
 * 
 * @param context The Context in which we are parsing the wallpaper.
 * @param service The ResolveInfo returned from the package manager about
 * this wallpaper's component.
 */
public WallpaperInfo(Context context, ResolveInfo service)
        throws XmlPullParserException, IOException {
    mService = service;
    ServiceInfo si = service.serviceInfo;
    
    final PackageManager pm = context.getPackageManager();
    XmlResourceParser parser = null;
    try {
        parser = si.loadXmlMetaData(pm, WallpaperService.SERVICE_META_DATA);
        if (parser == null) {
            throw new XmlPullParserException("No "
                    + WallpaperService.SERVICE_META_DATA + " meta-data");
        }
    
        Resources res = pm.getResourcesForApplication(si.applicationInfo);
        
        AttributeSet attrs = Xml.asAttributeSet(parser);
        
        int type;
        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
                && type != XmlPullParser.START_TAG) {
        }
        
        String nodeName = parser.getName();
        if (!"wallpaper".equals(nodeName)) {
            throw new XmlPullParserException(
                    "Meta-data does not start with wallpaper tag");
        }
        
        TypedArray sa = res.obtainAttributes(attrs,
                com.android.internal.R.styleable.Wallpaper);
        mSettingsActivityName = sa.getString(
                com.android.internal.R.styleable.Wallpaper_settingsActivity);

        mThumbnailResource = sa.getResourceId(
                com.android.internal.R.styleable.Wallpaper_thumbnail,
                -1);
        mAuthorResource = sa.getResourceId(
                com.android.internal.R.styleable.Wallpaper_author,
                -1);
        mDescriptionResource = sa.getResourceId(
                com.android.internal.R.styleable.Wallpaper_description,
                -1);
        mContextUriResource = sa.getResourceId(
                com.android.internal.R.styleable.Wallpaper_contextUri,
                -1);
        mContextDescriptionResource = sa.getResourceId(
                com.android.internal.R.styleable.Wallpaper_contextDescription,
                -1);
        mShowMetadataInPreview = sa.getBoolean(
                com.android.internal.R.styleable.Wallpaper_showMetadataInPreview,
                false);
        mSupportsAmbientMode = sa.getBoolean(
                com.android.internal.R.styleable.Wallpaper_supportsAmbientMode,
                false);

        sa.recycle();
    } catch (NameNotFoundException e) {
        throw new XmlPullParserException(
                "Unable to create context for: " + si.packageName);
    } finally {
        if (parser != null) parser.close();
    }
}
 
Example 14
Source File: FileProvider.java    From V.FlyoutTest with MIT License 4 votes vote down vote up
/**
 * Parse and return {@link PathStrategy} for given authority as defined in
 * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;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;
}
 
Example 15
Source File: ApduParser.java    From smartcard-reader with GNU General Public License v3.0 4 votes vote down vote up
static void init(Context context) {
    if (CMDS != null && SWS != null)
        return;

    final XmlResourceParser xml = context.getResources().getXml(
            R.xml.apdu7816);

    try {
        // START__DOCUMENT
        xml.next();

        if (xml.next() == START_TAG
                && "apdu".equalsIgnoreCase(xml.getName())) {

            while (xml.next() != END_DOCUMENT) {

                Apdu7816 cmds = readTag(Apdu7816.CMDS.class, xml);
                if (cmds != null) {
                    CMDS = cmds;
                    continue;
                }

                Apdu7816 sws = readTag(Apdu7816.SWS.class, xml);
                if (sws != null) {
                    SWS = sws;
                    continue;
                }

                break;

            }
        }
    } catch (Exception e) {
    } finally {
        if (xml != null)
            xml.close();
    }

    if (CMDS == null)
        CMDS = new Apdu7816.CMDS();

    if (SWS == null)
        SWS = new Apdu7816.SWS();
}
 
Example 16
Source File: StreamProvider.java    From cwac-provider with Apache License 2.0 4 votes vote down vote up
private CompositeStreamStrategy parseStreamStrategy(final CompositeStreamStrategy result,
                                                    Context context,
                                                    String authority)
  throws IOException, XmlPullParserException {
  final ProviderInfo info=
    context.getPackageManager()
      .resolveContentProvider(authority,
        PackageManager.GET_META_DATA);

  useLegacyCursorWrapper=info.metaData.getBoolean(META_DATA_USE_LEGACY_CURSOR_WRAPPER, true);
  useUriForDataColumn=info.metaData.getBoolean(META_DATA_USE_URI_FOR_DATA_COLUMN, false);

  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()) != org.xmlpull.v1.XmlPullParser.END_DOCUMENT) {
    if (type == org.xmlpull.v1.XmlPullParser.START_TAG) {
      final String tag=in.getName();

      if (!"paths".equals(tag)) {
        final String name=in.getAttributeValue(null, ATTR_NAME);

        if (TextUtils.isEmpty(name)) {
          throw new IllegalArgumentException("Name must not be empty");
        }

        String path=in.getAttributeValue(null, ATTR_PATH);
        boolean readOnly=allReadOnly ||
          Boolean.parseBoolean(in.getAttributeValue(null, ATTR_READ_ONLY));
        HashMap<String, String> attrs=new HashMap<String, String>();

        for (int i=0;i<in.getAttributeCount();i++) {
          attrs.put(in.getAttributeName(i), in.getAttributeValue(i));
        }

        StreamStrategy strategy=
          buildStrategy(context, tag, name, path, readOnly, attrs);

        if (strategy != null) {
          result.add(name, strategy);
        }
        else {
          throw new IllegalArgumentException("Could not build strategy for "
            + tag);
        }
      }
    }
  }

  return(result);
}
 
Example 17
Source File: Keyboard.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void loadKeyboard(Context context, XmlResourceParser parser) {
    boolean inKey = false;
    boolean inRow = false;
    boolean leftMostKey = false;
    int row = 0;
    int x = 0;
    int y = 0;
    Key key = null;
    Row currentRow = null;
    Resources res = context.getResources();
    boolean skipRow = false;

    try {
        int event;
        while ((event = parser.next()) != XmlResourceParser.END_DOCUMENT) {
            if (event == XmlResourceParser.START_TAG) {
                String tag = parser.getName();
                if (TAG_ROW.equals(tag)) {
                    inRow = true;
                    x = 0;
                    currentRow = createRowFromXml(res, parser);
                    rows.add(currentRow);
                    skipRow = currentRow.mode != 0 && currentRow.mode != mKeyboardMode;
                    if (skipRow) {
                        skipToEndOfRow(parser);
                        inRow = false;
                    }
               } else if (TAG_KEY.equals(tag)) {
                    inKey = true;
                    key = createKeyFromXml(res, currentRow, x, y, parser);
                    mKeys.add(key);
                    if (key.codes[0] == KEYCODE_SHIFT) {
                        // Find available shift key slot and put this shift key in it
                        for (int i = 0; i < mShiftKeys.length; i++) {
                            if (mShiftKeys[i] == null) {
                                mShiftKeys[i] = key;
                                mShiftKeyIndices[i] = mKeys.size()-1;
                                break;
                            }
                        }
                        mModifierKeys.add(key);
                    } else if (key.codes[0] == KEYCODE_ALT) {
                        mModifierKeys.add(key);
                    }
                    currentRow.mKeys.add(key);
                } else if (TAG_KEYBOARD.equals(tag)) {
                    parseKeyboardAttributes(res, parser);
                }
            } else if (event == XmlResourceParser.END_TAG) {
                if (inKey) {
                    inKey = false;
                    x += key.gap + key.width;
                    if (x > mTotalWidth) {
                        mTotalWidth = x;
                    }
                } else if (inRow) {
                    inRow = false;
                    y += currentRow.verticalGap;
                    y += currentRow.defaultHeight;
                    row++;
                } else {
                    // TODO: error or extend?
                }
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Parse error:" + e);
        e.printStackTrace();
    }
    mTotalHeight = y - mDefaultVerticalGap;
}
 
Example 18
Source File: AutoInstallsLayout.java    From LB-Launcher with Apache License 2.0 4 votes vote down vote up
@Override
public long parseAndAdd(XmlResourceParser parser)
        throws XmlPullParserException, IOException {
    final String title;
    final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
    if (titleResId != 0) {
        title = mSourceRes.getString(titleResId);
    } else {
        title = mContext.getResources().getString(R.string.folder_name);
    }

    mValues.put(Favorites.TITLE, title);
    mValues.put(Favorites.ITEM_TYPE, Favorites.ITEM_TYPE_FOLDER);
    mValues.put(Favorites.SPANX, 1);
    mValues.put(Favorites.SPANY, 1);
    mValues.put(Favorites._ID, mCallback.generateNewItemId());
    long folderId = mCallback.insertAndCheck(mDb, mValues);
    if (folderId < 0) {
        if (LOGD) Log.e(TAG, "Unable to add folder");
        return -1;
    }

    final ContentValues myValues = new ContentValues(mValues);
    ArrayList<Long> folderItems = new ArrayList<Long>();

    int type;
    int folderDepth = parser.getDepth();
    while ((type = parser.next()) != XmlPullParser.END_TAG ||
            parser.getDepth() > folderDepth) {
        if (type != XmlPullParser.START_TAG) {
            continue;
        }
        mValues.clear();
        mValues.put(Favorites.CONTAINER, folderId);

        TagParser tagParser = mFolderElements.get(parser.getName());
        if (tagParser != null) {
            final long id = tagParser.parseAndAdd(parser);
            if (id >= 0) {
                folderItems.add(id);
            }
        } else {
            throw new RuntimeException("Invalid folder item " + parser.getName());
        }
    }

    long addedId = folderId;

    // We can only have folders with >= 2 items, so we need to remove the
    // folder and clean up if less than 2 items were included, or some
    // failed to add, and less than 2 were actually added
    if (folderItems.size() < 2) {
        // Delete the folder
        Uri uri = Favorites.getContentUri(folderId, false);
        SqlArguments args = new SqlArguments(uri, null, null);
        mDb.delete(args.table, args.where, args.args);
        addedId = -1;

        // If we have a single item, promote it to where the folder
        // would have been.
        if (folderItems.size() == 1) {
            final ContentValues childValues = new ContentValues();
            copyInteger(myValues, childValues, Favorites.CONTAINER);
            copyInteger(myValues, childValues, Favorites.SCREEN);
            copyInteger(myValues, childValues, Favorites.CELLX);
            copyInteger(myValues, childValues, Favorites.CELLY);

            addedId = folderItems.get(0);
            mDb.update(LauncherProvider.TABLE_FAVORITES, childValues,
                    Favorites._ID + "=" + addedId, null);
        }
    }
    return addedId;
}
 
Example 19
Source File: FileProvider.java    From android-recipes-app with Apache License 2.0 4 votes vote down vote up
/**
 * Parse and return {@link PathStrategy} for given authority as defined in
 * {@link #META_DATA_FILE_PROVIDER_PATHS} {@code &lt;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;
}
 
Example 20
Source File: Keyboard.java    From WirelessHid with Apache License 2.0 4 votes vote down vote up
private LinearLayout parseKeyLayout(Context context, XmlResourceParser xmlParser)
        throws XmlPullParserException, IOException {
    LinearLayout linearLayout = new LinearLayout(context);
    linearLayout.setLayoutParams(new LayoutParams(
            xmlParser.getAttributeIntValue(null, "width", LayoutParams.MATCH_PARENT),
            xmlParser.getAttributeIntValue(null, "height", 0),
            xmlParser.getAttributeFloatValue(null, "weight", 1.0f)));
    linearLayout.setOrientation(xmlParser.getAttributeIntValue(null, "orientation",
            LinearLayout.HORIZONTAL));

    String tag;
    do {
        xmlParser.next();
        tag = xmlParser.getName();

        if (xmlParser.getEventType() == XmlResourceParser.START_TAG) {
            if (tag.equals(XML_TAG_LAYOUT)) {
                linearLayout.addView(parseKeyLayout(context, xmlParser));
            } else if (tag.equals(XML_TAG_KEY)) {
                Key.KeyAttributes attrs = new Key.KeyAttributes();
                attrs.keyFunction = getStringAttributeValue(xmlParser, "keyFunc", "");
                attrs.mainLabel = getStringAttributeValue(xmlParser, "keyLabel", "");
                attrs.shiftLabel = getStringAttributeValue(xmlParser, "shiftLabel", "");
                attrs.keyCode = xmlParser.getAttributeIntValue(null, "keyCode", 0);

                Key key = new Key(context, attrs);
                key.setLayoutParams(new LayoutParams(
                        xmlParser.getAttributeIntValue(null, "width", 0),
                        xmlParser.getAttributeIntValue(null, "height",
                                LayoutParams.MATCH_PARENT),
                        xmlParser.getAttributeFloatValue(null, "weight", 1)));
                key.setVisibility(xmlParser.getAttributeBooleanValue(null, "visible", true) ?
                    VISIBLE : INVISIBLE);
                key.setKeyListener(this);

                if (attrs.shiftLabel != null & attrs.shiftLabel.length() > 0) {
                    mKeysWithShiftLabel.add(key);
                }

                linearLayout.addView(key);
            }
        }
    } while (xmlParser.getEventType() != XmlResourceParser.END_TAG
            || !tag.equals(XML_TAG_LAYOUT));

    return linearLayout;
}