我对 android 开发有点陌生,这是我第一次尝试在首选项屏幕中提供已安装应用程序的列表。从此列表中选择的值稍后将用于启动用户选择的应用程序。
我创建了以下类:
public class AppSelectorPreference extends ListPreference {
public AppSelectorPreference(Context context, AttributeSet attrs) {
super(context,attrs);
PackageManager pm = context.getPackageManager();
List<PackageInfo> appListInfo = pm.getInstalledPackages(0);
CharSequence[] entries = new CharSequence[appListInfo.size()];
CharSequence[] entryValues = new CharSequence[appListInfo.size()];
try {
int i = 0;
for (PackageInfo p : appListInfo) {
if (p.applicationInfo.uid > 10000) {
entries[i] = p.applicationInfo.loadLabel(pm).toString();
entryValues[i] = p.applicationInfo.packageName.toString();
Log.d(BT,"Label: " + entries[i]);
Log.d(BT,"PName: " + entryValues[i]);
i++;
}
}
} catch (Exception e) {
Log.e(BT,"ER> Put descriptive error message here");
e.printStackTrace();
}
setEntries(entries);
setEntryValues(entryValues);
}
}
这将使用以下 XML 添加到我的 PreferenceScreen 中:
<PreferenceCategory android:title="Launch Application">
<CheckBoxPreference
android:title="Launch Application"
android:summary="Launch an application"
android:defaultValue="false"
android:key="pref_connect_launch_enable"
android:dependency="pref_connect_enable"/>
<com.nirsoftware.AppSelectorPreference
android:title="Select Application"
android:summary="Select application to launch"
android:key="pref_connect_package_name"
android:dependency="pref_connect_launch_enable"/>
</PreferenceCategory>
看起来一切正常,直到单击 AppSelectorPreference,这会在 android.preference.ListPreference.findIndexOfValue(ListPreference.java:169) 中引发 NPE。有什么建议么?