1 package com.android.settings.testutils; 2 3 import android.content.res.Resources; 4 import android.content.res.XmlResourceParser; 5 6 import android.content.Context; 7 import android.text.TextUtils; 8 import android.util.AttributeSet; 9 import android.util.Xml; 10 import com.android.settings.search.XmlParserUtils; 11 import org.xmlpull.v1.XmlPullParser; 12 import org.xmlpull.v1.XmlPullParserException; 13 14 import java.util.ArrayList; 15 import java.util.List; 16 17 /** 18 * Util class for parsing XML 19 */ 20 public class XmlTestUtils { 21 22 /** 23 * Parses a preference screen's xml, collects and returns all keys used by preferences 24 * on the screen. 25 * 26 * @param context of the preference screen. 27 * @param xmlId of the Preference Xml to be parsed. 28 * @return List of all keys in the preference Xml 29 */ getKeysFromPreferenceXml(Context context, int xmlId)30 public static List<String> getKeysFromPreferenceXml(Context context, int xmlId) { 31 final XmlResourceParser parser = context.getResources().getXml(xmlId); 32 final AttributeSet attrs = Xml.asAttributeSet(parser); 33 final List<String> keys = new ArrayList<>(); 34 String key; 35 try { 36 while (parser.next() != XmlPullParser.END_DOCUMENT) { 37 try { 38 key = XmlParserUtils.getDataKey(context, attrs); 39 if (!TextUtils.isEmpty(key)) { 40 keys.add(key); 41 } 42 } catch (NullPointerException e) { 43 continue; 44 } catch (Resources.NotFoundException e) { 45 continue; 46 } 47 } 48 } catch (java.io.IOException e) { 49 return null; 50 } catch (XmlPullParserException e) { 51 return null; 52 } 53 54 return keys; 55 } 56 }