我知道什么是空指针异常,但我的问题是我无法弄清楚如何处理它并向用户提供一个toast消息,说明以下代码中的列表为空。我正在为我的应用创建一个图库,我正在指定系统应该将所有文件和文件夹加载到我的Android应用程序中的路径。
当路径中没有文件或文件夹时,应用程序崩溃说:
Attempting to invoke length on a null array.
GalleryFragment.java
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
ImageView icon = (ImageView) getActivity().findViewById(R.id.toolbarIcon);
icon.setImageResource(R.drawable.ic_perm_media_black_24dp);
icon.setColorFilter(getResources().getColor(R.color.Gallery));
TextView title = (TextView) getActivity().findViewById(R.id.toolbarTitle);
title.setText(getString(R.string.galleryLabel));
toolbar.setBackground(getResources().getDrawable(R.drawable.tile_green));
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_green_24dp));
gridView = (GridView) view.findViewById(R.id.gridView);
setGridAdapter(Environment.getExternalStorageDirectory().getPath());
return view;
}
private void setGridAdapter(String path) {
// Create a new grid adapter
gridItems = createGridItems(path);
MyGridAdapter adapter = new MyGridAdapter(getContext(), gridItems);
// Set the grid adapter
gridView.setAdapter(adapter);
// Set the onClickListener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (gridItems.get(position).isDirectory()) {
setGridAdapter(gridItems.get(position).getPath());
}
else {
gridItems.get(position).getImage();
}
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (gridItems.get(position).isDirectory()) {
Dialog dialog = new Dialog(getContext());
dialog.setTitle("Test");
dialog.setContentView(R.layout.activity_recognition);
dialog.show();
return false;
} else {
Dialog dialog = new Dialog(getContext());
dialog.setTitle("Test");
dialog.setContentView(R.layout.activity_reset_password);
dialog.show();
return false;
}
}
});
}
private List<GridViewItem> createGridItems(String directoryPath) {
List<GridViewItem> items = new ArrayList<>();
// List all the items within the folder.
File[] files = new File(directoryPath).listFiles(new ImageFileFilter());
for (File file : files) {
// Add the directories containing images or sub-directories
if (file.isDirectory()
&& file.listFiles(new ImageFileFilter()).length > 0) {
items.add(new GridViewItem(file.getAbsolutePath(), true, null));
}
// Add the images
else {
Bitmap image = BitmapHelper.decodeBitmapFromFile(file.getAbsolutePath(),
50,
50);
items.add(new GridViewItem(file.getAbsolutePath(), false, image));
}
}
return items;
}
/**
* Checks the file to see if it has a compatible extension.
*/
private boolean isImageFile(String filePath) {
if (filePath.endsWith(".jpg") || filePath.endsWith(".png"))
// Add other formats as desired
{
return true;
}
return false;
}
/**
* This can be used to filter files.
*/
private class ImageFileFilter implements FileFilter {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
else if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
GalleryAdapter.java
public class MyGridAdapter extends BaseAdapter {
LayoutInflater inflater;
List < GridViewItem > items;
private Context mContext;
public MyGridAdapter(Context context, List < GridViewItem > items) {
mContext = context;
this.items = items;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_item, null);
}
TextView text = (TextView) convertView.findViewById(R.id.textView);
text.setText(items.get(position).getPath());
ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
Bitmap image = items.get(position).getImage();
if (image != null) {
imageView.setImageBitmap(image);
} else {
// If no image is provided, display a folder icon.
imageView.setImageResource(R.drawable.ic_folder_grey_24dp);
}
return convertView;
}
}
我想只在数组的长度大于零时才列出文件。我不知道在哪里检查。
答案 0 :(得分:0)
如果您尝试迭代for
数组,则增强的null
循环将失败。因此,这里的一个选择就是检查这种可能性,并仅在存在非空数组文件时进行迭代。
private List<GridViewItem> createGridItems(String directoryPath) {
List<GridViewItem> items = new ArrayList<>();
// List all the items within the folder.
File[] files = new File(directoryPath).listFiles(new ImageFileFilter());
if (files != null) { // check here for null
for (File file : files) {
// Add the directories containing images or sub-directories
if (file.isDirectory()
&& file.listFiles(new ImageFileFilter()).length > 0) {
items.add(new GridViewItem(file.getAbsolutePath(), true, null));
}
// Add the images
else {
Bitmap image = BitmapHelper.decodeBitmapFromFile(file.getAbsolutePath(),
50,
50);
items.add(new GridViewItem(file.getAbsolutePath(), false, image));
}
}
}
return items;
}
答案 1 :(得分:0)
第一次更改在下面的循环之前进行空检查
private List<GridViewItem> createGridItems(String directoryPath) {
List<GridViewItem> items = new ArrayList<>();
// List all the items within the folder.
File[] files = new File(directoryPath).listFiles(new ImageFileFilter());
if(files != null && files.length != 0) {
for (File file : files) {
// Add the directories containing images or sub-directories
if (file.isDirectory()
&& file.listFiles(new ImageFileFilter()).length > 0) {
items.add(new GridViewItem(file.getAbsolutePath(), true, null));
}
// Add the images
else {
Bitmap image = BitmapHelper.decodeBitmapFromFile(file.getAbsolutePath(),
50,
50);
items.add(new GridViewItem(file.getAbsolutePath(), false, image));
}
}
}
return items;
}
接下来在myGridAdapter的getItemCount中为空列表编写逻辑,如下所示
@Override
public int getCount() {
if(item.size == 0) {
Log.d("List Size :", "List is empty");
//If you want to toast message accepts context in your constructor
//Then toast message
}
return items.size();
}