String[] m_cPackageName;
int m_size;
int j=0;
List<ApplicationInfo> installedList = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
m_size = installedList.size();
m_cPackageName=new String[m_size];
for (PackageInfo pi : pkginfoList) {
try {
m_appinfo = packageManager.getApplicationInfo(pi.packageName, 0);
if ((m_appinfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
// equal to zoo means system apps, not equal is third party installed apps
m_cPackageName[j]=pi.packageName;
j++;
}
} catch (NameNotFoundException e) {
Log.d(getClass().getSimpleName(), "Name not found", e);
}
这里我得到的instalList的总大小是56 ..在数组中填充值后,它显示为空值。我怎样才能消除空值..对我来说任何一个帮助..
输出:
m_cPackageName=String[56];
m_cPackageName[0]="Myvalue"
m_cPackageName[1]="null"
m_cPackageName[2]="null"
.
.
.
m_cPackageName[55]="null"
答案 0 :(得分:0)
在将元素插入数组之前添加空检查。
if ((m_appinfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
if(pi.packageName!=null){
m_cPackageName[j]=pi.packageName;
j++;
}
}
答案 1 :(得分:0)
if (((m_appinfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)&& (pi.packageName != null &&!pi.packageName.equals("")) {
// equal to zoo means system apps, not equal is third party installed apps
m_cPackageName[j]=pi.packageName;
j++;
}
答案 2 :(得分:0)
您正在根据installedList
的大小分配数组,但是您正在迭代pkginfoList
。更好的方法是创建List<String> packageNames = new ArrayList<String>();
,然后在循环中添加到该列表。
这样,您不必担心计数或尺寸。
答案 3 :(得分:0)
if ((m_appinfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
// equal to zoo means system apps, not equal is third party installed apps
if(pi.packageName!=null){
m_cPackageName[j]=pi.packageName;
j++;
}
}
答案 4 :(得分:0)
小于m_size
个元素被添加到数组(大小为m_size
),最终导致未分配的null
个元素。
这是因为 j
有时只会增加 - 在条件((m_appinfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
)内,并且只有在没有抛出并捕获异常时才会增加。
一个简单的解决方案是使用ArrayList,然后只添加“已批准”元素。因为List / ArrayList按需增长,所以在固定大小的数组中没有可以找到的尾随空(未分配)元素。
// List, not array
List<String> m_cPackageName = new ArrayList<String>();
// ..
if ((m_appinfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
// Only added to list sometimes, but m_cPackageName.size() is
// always the count of elements that HAVE been added.
m_cPackageName.add(pi.packageName);
}
// Then, if you really need an array, which will now be the proper size
// and not contain null elements because the size is computed based on the
// accepted elements in m_cPackageName which is m_cPackageName.size() ..
String[] arrayOfPackageNames = m_cPackageName.toArray(new String[0]);
答案 5 :(得分:0)
如果您不需要消除空字符串和空字符串的歧义,请考虑将空值存储为空;像这样的东西:
m_cPackageName[j]=pi.packageName == null ? "" : pi.packageName;
这可能会降低因NullPointerException-s进一步下降而导致事件爆发的风险。