我想将图像从SD卡设置为gridview?

时间:2015-11-28 08:43:10

标签: android

以下是我的AppConstant.java

package com.domore.gridviewtutorial.helper;

import java.util.Arrays;
import java.util.List;

/**
 * Created by MY WORLD on 11/28/2015.
 */
public class AppContant {
    // 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 = "MyPhotos";

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

在这个类中我设置了我在我的应用程序中加载的文件扩展名

这是我的utils类

package com.domore.gridviewtutorial.helper;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

/**
 * Created by MY WORLD on 11/28/2015.
 */
public class Utils {
    private Context context;

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

    public ArrayList<String> getFilePaths(){
        ArrayList<String> filePaths=new ArrayList<String>();

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

        if(directory.isDirectory()){
            File[] listFiles=directory.listFiles();

            if(listFiles.length > 0 ){
                for(int i=0;i<listFiles.length;i++){
                    String filePath=listFiles[i].getAbsolutePath();


                    if(IsSupportedFile(filePath)){
                        filePaths.add(filePath);
                    }
                }
            }
            else{
                Toast.makeText(
                        context,
                        AppContant.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(AppContant.PHOTO_ALBUM
                    + " directory path is not valid! Please set the image directory name AppConstant.java class");
            alert.setPositiveButton("OK", null);
            alert.show();
        }
        return filePaths;
    }
    private boolean IsSupportedFile(String filePath) {
        String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
                filePath.length());

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

    }
    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;
    }
}

这是我的grid_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    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>

我有适配器类来加载图像

    package com.domore.gridviewtutorial.adapter;

    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.ImageView;
    import android.widget.GridView;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import android.view.View.OnClickListener;

    /**
     * Created by MY WORLD on 11/28/2015.
     */
    public class GridViewImageAdapter extends BaseAdapter {
        private Activity activity;
        private ArrayList<String> _filePaths=new ArrayList<String>();
        private int imageWidth;

        public GridViewImageAdapter(Activity activity,ArrayList<String> _filePaths,int imageWidth){
            this.activity=activity;
            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(this.activity);
            }
            else{
                imageView=(ImageView)convertView;
            }
            Bitmap image=decodeFile(this._filePaths.get(position),imageWidth,imageWidth);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
                    imageWidth));
            imageView.setImageBitmap(image);

            // image view click listener
            imageView.setOnClickListener(new OnImageClickListener(position));

            return imageView;
        }
        class OnImageClickListener implements OnClickListener {

            int _postion;

            // constructor
            public OnImageClickListener(int position) {
                this._postion = position;
            }

            @Override
            public void onClick(View v) {
                // on selecting grid view image
                // launch full screen activity
    //            Intent i = new Intent(activity, FullScreenViewActivity.class);
    //            i.putExtra("position", _postion);
    //            activity.startActivity(i);
            }

        }
        /*
         * Resizing image size
         */
        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;
        }
    }

这是我的MainActivity.java

package com.domore.gridviewtutorial;

import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.GridLayoutAnimationController;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.domore.gridviewtutorial.adapter.GridViewImageAdapter;
import com.domore.gridviewtutorial.helper.AppContant;
import com.domore.gridviewtutorial.helper.Utils;

import java.util.ArrayList;

public class AndroidGridLayoutActivity extends AppCompatActivity {

    private Utils utils;
    private ArrayList<String> imagePaths = new ArrayList<String>();
    private GridViewImageAdapter adapter;
    private GridView gridView;
    private int columnWidth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid_layout);

        GridView gridView=(GridView)findViewById(R.id.grid_view);
        utils=new Utils(this);
        InitilizeGridLayout();
        imagePaths=utils.getFilePaths();
        adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
        gridView.setAdapter(adapter);
    }
    private void InitilizeGridLayout() {
        Resources r = getResources();
        float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                AppContant.GRID_PADDING, r.getDisplayMetrics());

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

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

我在mainActivity.java中遇到错误 这是我的错误

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setNumColumns(int)' on a null object reference
                                                       at com.domore.gridviewtutorial.AndroidGridLayoutActivity.InitilizeGridLayout(AndroidGridLayoutActivity.java:46)
                                                       at com.domore.gridviewtutorial.AndroidGridLayoutActivity.onCreate(AndroidGridLayoutActivity.java:34)

任何帮助我解决这个错误的人都无法理解。

1 个答案:

答案 0 :(得分:0)

您的gridView变量为null,因为您正在onCreate()方法中重新创建新变量 gridView ,并且您的活动的实例 gridView 变量永远不会被初始化。

public class AndroidGridLayoutActivity extends AppCompatActivity {

    private Utils utils;
    private ArrayList<String> imagePaths = new ArrayList<String>();
    private GridViewImageAdapter adapter;
    private GridView gridView;
    private int columnWidth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grid_layout);

        // initiated the gridView variable
        gridView=(GridView)findViewById(R.id.grid_view);

        utils=new Utils(this);
        InitilizeGridLayout();
        imagePaths=utils.getFilePaths();
        adapter=new GridViewImageAdapter(AndroidGridLayoutActivity.this,imagePaths,columnWidth);
        gridView.setAdapter(adapter);
    }
    private void InitilizeGridLayout() {
        Resources r = getResources();
        float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                AppContant.GRID_PADDING, r.getDisplayMetrics());

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

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