[英]Android packagemanager list causing app to crash
I am fairly new to Android programming. 我是Android编程的新手。 I downloaded Android Studio today and started a new project.
我今天下载了Android Studio,并开始了一个新项目。 I added an empty activity to the form with a textview with the following code.
我使用以下代码向具有textview的表单添加了一个空活动。
XML: 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" />
MAIN CODE: 主要代码:
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);
}
}
For some reason, the app crashes as soon as it launches. 由于某种原因,该应用程序一启动就会崩溃。 If I remove the code I wrote and only keep till
如果删除我编写的代码,直到
setContentView(R.layout.activity_main);
it works fine but is empty. 它工作正常,但为空。
EDIT: Stacktrace https://pastebin.com/dHHygFkQ 编辑:Stacktrace https://pastebin.com/dHHygFkQ
As said in the comments, remove the second setContentView. 如评论中所述,删除第二个setContentView。
You are passing null
to tv1.append
. 您正在将
null
传递给tv1.append
。 As appInfo.name
returns null
. 由于
appInfo.name
返回null
。 See PackageManager's applicationInfo.name is always null 请参阅PackageManager的applicationInfo.name始终为null
Use: (String)pm.getApplicationLabel(appInfo)
. 使用:
(String)pm.getApplicationLabel(appInfo)
。
For example: 例如:
applicationsInstalled.add((String)pm.getApplicationLabel(appInfo))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.