[英]Android: Populate ListPreference with installed applications?
我对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。 有什么建议么?
我建议您删除if条件,因为它是导致空指针错误的原因,因为条件将为false,无法执行命令null条目一个值
try {
int i = 0;
for (PackageInfo p : appListInfo) {
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();
}
我已经尝试了您的代码,并且对我来说效果很好,都以编程方式添加了如下代码:
AppSelectorPreference pref2 = new AppSelectorPreference(this, null);
getPreferenceScreen().addPreference(pref2);
并像您写的那样使用xml。 出现错误的行169是哪一个?
另外,您是否浏览了logcat以查看是否有任何应用程序名称或标签给出了null之类的信息? 我唯一能想到的是您的android有与我不同的应用程序。
编辑:对不起,我再次测试,现在我得到了与您相同的错误。 除了选择一个值外,不知道我做了什么不同
但是,我通过重写findIndexOfValue方法来解决此问题。 我只是这样做来测试:
@Override
public int findIndexOfValue(String value) {
return 0;
//return super.findIndexOfValue(value);
}
但是当然您需要实现该值的findind索引。 可能是很大条目数组的android bug吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.