在Fragment中使用GridView图像

时间:2014-03-24 15:03:05

标签: android image gridview android-fragments

我正在开发一个Android应用程序,它使用GridView在类扩展片段中显示我的图像。但是当我运行我的代码时,我遇到了错误。此错误显示:" NullPointerException"在GridView setadapter中。请帮我。对不起我的英语,这不好。

Fragment class:

public class DetailMore extends Fragment{

GridView gridViewImage;
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.detail_more, null);

    // Create UI components here.
    gridViewImage = (GridView)view.findViewById(R.id.grid_view);
    utils = new Utils(getActivity().getApplicationContext());

    // Initilizing Grid View
    InitilizeGridLayout();

 // loading all image paths from SD card
    imagePaths = utils.getFilePaths();

    // Gridview adapter
    adapter = new GridViewImageAdapter(imagePaths,
            columnWidth);

    // setting grid view adapter
    try {
        gridView.setAdapter(adapter);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //gridViewImage.setAdapter(new GridViewImageAdapter(activity, filePaths, imageWidth));

    return view;
}

private void InitilizeGridLayout() {
    Resources r = getResources();
    float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            AppConstant.GRID_PADDING, r.getDisplayMetrics());

    columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);

    gridViewImage.setNumColumns(AppConstant.NUM_OF_COLUMNS);
    gridViewImage.setColumnWidth(columnWidth);
    gridViewImage.setStretchMode(GridView.NO_STRETCH);
    gridViewImage.setPadding((int) padding, (int) padding, (int) padding,
            (int) padding);
    gridViewImage.setHorizontalSpacing((int) padding);
    gridViewImage.setVerticalSpacing((int) padding);
}
}

GridViewAdapter:

public class GridViewImageAdapter extends BaseAdapter { 
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;

public GridViewImageAdapter(ArrayList<String> filePaths,
        int imageWidth) {      
    this._filePaths = filePaths;
    this.imageWidth = imageWidth;
}

@Override
public int getCount() {
    return this._filePaths.size();
}

@Override
public Object getItem(int position) {
    return this._filePaths.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {
        imageView = new ImageView(_activity);
    } else {
        imageView = (ImageView) convertView;
    }

    // get screen dimensions
    Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
            imageWidth);

    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
            imageWidth));
    imageView.setImageBitmap(image);
    return imageView;
}


public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
    try {

        File f = new File(filePath);

        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);

        final int REQUIRED_WIDTH = WIDTH;
        final int REQUIRED_HIGHT = HIGHT;
        int scale = 1;
        while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
                && o.outHeight / scale / 2 >= REQUIRED_HIGHT)
            scale *= 2;

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

}

AppConstant:

public class AppConstant {

// Number of columns of Grid View
public static final int NUM_OF_COLUMNS = 3;

// Gridview image padding
public static final int GRID_PADDING = 8; // in dp

// SD card image directory
public static final String PHOTO_ALBUM = "Festival";

// supported file formats
public static final List<String> FILE_EXTN = Arrays.asList("jpg", "jpeg",
        "png");

 }

Utils:

public class Utils {

private Context _context;

// constructor
public Utils(Context context) {
    this._context = context;
}

// Reading file paths from SDCard
public ArrayList<String> getFilePaths() {
    ArrayList<String> filePaths = new ArrayList<String>();

    File directory = new File(
            android.os.Environment.getExternalStorageDirectory()
                    + File.separator + AppConstant.PHOTO_ALBUM);

    // check for directory
    if (directory.isDirectory()) {
        // getting list of file paths
        File[] listFiles = directory.listFiles();

        // Check for count
        if (listFiles.length > 0) {

            // loop through all files
            for (int i = 0; i < listFiles.length; i++) {

                // get file path
                String filePath = listFiles[i].getAbsolutePath();

                // check for supported file extension
                if (IsSupportedFile(filePath)) {
                    // Add image path to array list
                    filePaths.add(filePath);
                }
            }
        } else {
            // image directory is empty
            Toast.makeText(
                    _context,
                    AppConstant.PHOTO_ALBUM
                            + " is empty. Please load some images in it !",
                    Toast.LENGTH_LONG).show();
        }

    } else {
        AlertDialog.Builder alert = new AlertDialog.Builder(_context);
        alert.setTitle("Error!");
        alert.setMessage(AppConstant.PHOTO_ALBUM
                + " directory path is not valid! Please set the image directory name AppConstant.java class");
        alert.setPositiveButton("OK", null);
        alert.show();
    }

    return filePaths;
}

// Check supported file extensions
private boolean IsSupportedFile(String filePath) {
    String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
            filePath.length());

    if (AppConstant.FILE_EXTN
            .contains(ext.toLowerCase(Locale.getDefault())))
        return true;
    else
        return false;

}

/*
 * getting screen width
 */
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public int getScreenWidth() {
    int columnWidth;
    WindowManager wm = (WindowManager) _context
            .getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();

    final Point point = new Point();
    try {
        display.getSize(point);
    } catch (java.lang.NoSuchMethodError ignore) { // Older device
        point.x = display.getWidth();
        point.y = display.getHeight();
    }
    columnWidth = point.x;
    return columnWidth;
}

}

detail_more.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<GridView
android:id="@+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:gravity="center"
android:stretchMode="columnWidth"
android:background="#000000"> 
</GridView>

</LinearLayout>

1 个答案:

答案 0 :(得分:1)

您的GridView未初始化,因此在gridView.setAdapter(adapter);处出错。

电话,

 GridView gridView;

仅声明您的GridView,但是为了使用它,您必须将其初始化为

gridView = new GridView(context);

gridView = (GridView) view.findViewById(your id);