我正在编写一个非常基本的Home Launcher,我在AppsGridActivity中创建了一个类AppsInfoModel,一个CustomAdapter和一个GridView。
这是我在Activity
中填充适配器的代码function umbExtendImportController($scope, $routeParams, $http, navigationService) {
$scope.runImport = function () {
navigationService.hideNavigation();
}
};
这是适配器
appsGrid = (GridView) findViewById(R.id.appsGrid);
appsInfo = new AppsInfoModel(this);
appsGrid.setAdapter(new CustomAdapter(this,appsInfo));
}
和Model类
public class CustomAdapter extends BaseAdapter {
Context context;
AppsInfoModel appInfo;
CustomAdapter(Context context,AppsInfoModel appInfo) {
this.context = context;
this.appInfo = appInfo;
}
@Override
public int getCount() {
return appInfo.getSize();
}
@Override
public Object getItem(int position) {
return appInfo.getItem(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.single_grid, parent, false);
ImageView icon = (ImageView) convertView.findViewById(R.id.app_icon);
icon.setImageDrawable(appInfo.getIcon(position));
TextView label = (TextView) convertView.findViewById(R.id.app_label);
label.setText(appInfo.getLabel(position));
return convertView;
}
else
return convertView;
}
这是Logcat错误
public class AppsInfoModel {
String label[];
String name[];
Drawable icon[];
PackageManager pm;
List<ResolveInfo> appsInfo;
AppsInfoModel(Context context){
pm=context.getPackageManager();
appsInfo = pm.queryIntentActivities(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER), 0);
for(int i=0;i<appsInfo.size();i++){
label[i]= (appsInfo.get(i).loadLabel(pm)).toString();//***This is where problem lies according to LogCat***
name[i]= (appsInfo.get(i)).activityInfo.packageName;
icon[i]=(appsInfo.get(i)).activityInfo.loadIcon(pm);
}
}
Drawable getIcon(int i){
return icon[i];
}
String getLabel(int i){
return label[i];
}
String getPackageName(int i){
return name[i];
}
int getSize(){
return appsInfo.size();
}
public ResolveInfo getItem(int i) {
return appsInfo.get(i);
}
}
为什么会发生? 逻辑或语法有什么问题。
答案 0 :(得分:8)
根据您发布的代码,您没有初始化这些数组:
String label[];
String name[];
Drawable icon[];
你应该这样做:
AppsInfoModel(Context context){
pm=context.getPackageManager();
appsInfo = pm.queryIntentActivities(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER), 0);
label = new String[appsInfo.size()];
name = new String[appsInfo.size()];
icon = new Drawable[appsInfo.size()];
for(int i=0;i<appsInfo.size();i++){
label[i]= (appsInfo.get(i).loadLabel(pm)).toString();
name[i]= (appsInfo.get(i)).activityInfo.packageName;
icon[i]=(appsInfo.get(i)).activityInfo.loadIcon(pm);
}
}