我正在尝试插入应用程序的名称作为首选项的摘要。我编写了这段代码,但是它不起作用,因为在运行此行时,应用程序崩溃并显示NullPointerException
name.setSummary(Pm.getApplicationLabel(nameApp));
该代码是
value2 = getIntent().getStringExtra("ApplicationName");
PackageManager Pm = getPackageManager();
ApplicationInfo nameApp = Pm.getApplicationInfo(value2, 0);
name.setSummary(Pm.getApplicationLabel(nameApp));
Value2是一个变量的名称,该变量采用了上一个Activity产生的包的名称,在正确地传递和恢复包名称的意义上,此步骤效果很好
最佳答案
尝试这个..
PackageManager packageManager=this.getPackageManager();
List<ApplicationInfo applist=packageManager.getInstalledApplications(0);
Iterator<ApplicationInfo> it=applist.iterator();
while(it.hasNext()){
ApplicationInfo pk=(ApplicationInfo)it.next();
String appname = packageManager.getApplicationLabel(pk).toString();
System.out.println("Application name : "+appname);
}
或特定的包装名称
final PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo ai;
try {
ai = pm.getApplicationInfo(PackageName, 0);
} catch (final NameNotFoundException e) {
ai = null;
}
final String applicationName = (String) (ai != null ? pm.getApplicationLabel(ai) : "(unknown)");
System.out.println("Application name : "+applicationName);