Android packagemanager列表导致应用程序崩溃

时间:2016-12-04 15:48:31

标签: java android android-studio

我对Android编程很新。我今天下载了Android Studio并开始了一个新项目。我在表单中添加了一个空活动,其中包含带有以下代码的textview。

XML:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:id="@+id/textView1"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

主要代码:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    int flags = PackageManager.GET_META_DATA |
            PackageManager.GET_SHARED_LIBRARY_FILES |
            PackageManager.GET_UNINSTALLED_PACKAGES;

    PackageManager pm = getPackageManager();
    List<ApplicationInfo> applications = pm.getInstalledApplications(flags);
    List<String> applicationsInstalled = new ArrayList<String>();
    for (ApplicationInfo appInfo : applications) {
        if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
            // System application
        } else {
            // Installed by user
            applicationsInstalled.add(appInfo.name);
        }
    }
    TextView tv1 = (TextView)findViewById(R.id.textView1);
    for (String app : applicationsInstalled)
    {
        tv1.append(app);
    }
    setContentView(R.layout.activity_main);
}
}

出于某种原因,应用程序一启动就会崩溃。如果我删除了我写的代码并且只保留到

setContentView(R.layout.activity_main);

它工作正常但是空的。

编辑:Stacktrace https://pastebin.com/dHHygFkQ

1 个答案:

答案 0 :(得分:0)

如评论中所述,删除第二个setContentView。

您正在将null传递给tv1.append。当appInfo.name返回null时。见PackageManager's applicationInfo.name is always null

使用: (String)pm.getApplicationLabel(appInfo)

例如:

applicationsInstalled.add((String)pm.getApplicationLabel(appInfo))