1 /* 2 * Copyright (C) 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.settings.testutils; 17 18 import static com.android.settings.core.PreferenceXmlParserUtils.METADATA_KEY; 19 import static com.android.settings.core.PreferenceXmlParserUtils.MetadataFlag 20 .FLAG_INCLUDE_PREF_SCREEN; 21 import static com.android.settings.core.PreferenceXmlParserUtils.MetadataFlag.FLAG_NEED_KEY; 22 23 import android.content.Context; 24 import android.os.Bundle; 25 import android.text.TextUtils; 26 27 import com.android.settings.core.PreferenceXmlParserUtils; 28 29 import org.xmlpull.v1.XmlPullParserException; 30 31 import java.util.ArrayList; 32 import java.util.List; 33 34 /** 35 * Util class for parsing XML 36 */ 37 public class XmlTestUtils { 38 39 /** 40 * Parses a preference screen's xml, collects and returns all keys used by preferences 41 * on the screen. 42 * 43 * @param context of the preference screen. 44 * @param xmlId of the Preference Xml to be parsed. 45 * @return List of all keys in the preference Xml 46 */ getKeysFromPreferenceXml(Context context, int xmlId)47 public static List<String> getKeysFromPreferenceXml(Context context, int xmlId) { 48 final List<String> keys = new ArrayList<>(); 49 try { 50 List<Bundle> metadata = PreferenceXmlParserUtils.extractMetadata(context, xmlId, 51 FLAG_NEED_KEY | FLAG_INCLUDE_PREF_SCREEN); 52 for (Bundle bundle : metadata) { 53 final String key = bundle.getString(METADATA_KEY); 54 if (!TextUtils.isEmpty(key)) { 55 keys.add(key); 56 } 57 } 58 } catch (java.io.IOException | XmlPullParserException e) { 59 return null; 60 } 61 62 return keys; 63 } 64 } 65