搜索图像的图像文件和文件夹,并在网格视图中显示

时间:2014-11-10 07:14:07

标签: android image gridview photo-gallery

我正在开发一个我必须制作自定义图库的应用。为此,我必须从SD卡中搜索图像的所有图像和文件夹,并在网格视图中显示它。我的代码如下。有人请帮忙。提前谢谢。

package com.example.sdimagetutorial;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
 
public class GridViewAdapter extends BaseAdapter {
 
    // Declare variables
    private Activity activity;
    private String[] filepath;
    private String[] filename;
 
    private static LayoutInflater inflater = null;
 
    public GridViewAdapter(Activity a, String[] fpath, String[] fname) {
        activity = a;
        filepath = fpath;
        filename = fname;
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
    }
 
    public int getCount() {
        return filepath.length;
 
    }
 
    public Object getItem(int position) {
        return position;
    }
 
    public long getItemId(int position) {
        return position;
    }
 
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.gridview_item, null);
        // Locate the TextView in gridview_item.xml
        TextView text = (TextView) vi.findViewById(R.id.text);
        // Locate the ImageView in gridview_item.xml
        ImageView image = (ImageView) vi.findViewById(R.id.image);
 
        // Set file name to the TextView followed by the position
        text.setText(filename[position]);
 
        // Decode the filepath with BitmapFactory followed by the position
        Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);
 
        // Set the decoded bitmap into ImageView
        image.setImageBitmap(bmp);
        return vi;
    }
}
11-10 02:09:50.916: D/dalvikvm(28302): GC_FOR_ALLOC freed 70K, 5% free 3137K/3288K, paused 64ms, total 65ms
11-10 02:09:50.916: I/dalvikvm-heap(28302): Grow heap (frag case) to 4.209MB for 1127536-byte allocation
11-10 02:09:50.996: D/dalvikvm(28302): GC_FOR_ALLOC freed 2K, 4% free 4235K/4392K, paused 72ms, total 72ms
11-10 02:09:51.236: D/AndroidRuntime(28302): Shutting down VM
11-10 02:09:51.236: W/dalvikvm(28302): threadid=1: thread exiting with uncaught exception (group=0xb1a4aba8)
11-10 02:09:51.296: E/AndroidRuntime(28302): FATAL EXCEPTION: main
11-10 02:09:51.296: E/AndroidRuntime(28302): Process: com.example.sdimagetutorial, PID: 28302
11-10 02:09:51.296: E/AndroidRuntime(28302): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sdimagetutorial/com.example.sdimagetutorial.MainActivity}: java.lang.NullPointerException
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.app.ActivityThread.access$800(ActivityThread.java:135)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.os.Handler.dispatchMessage(Handler.java:102)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.os.Looper.loop(Looper.java:136)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.app.ActivityThread.main(ActivityThread.java:5017)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at java.lang.reflect.Method.invokeNative(Native Method)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at java.lang.reflect.Method.invoke(Method.java:515)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at dalvik.system.NativeStart.main(Native Method)
11-10 02:09:51.296: E/AndroidRuntime(28302): Caused by: java.lang.NullPointerException
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at com.example.sdimagetutorial.MainActivity.walkdir(MainActivity.java:113)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at com.example.sdimagetutorial.MainActivity.onCreate(MainActivity.java:48)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.app.Activity.performCreate(Activity.java:5231)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
11-10 02:09:51.296: E/AndroidRuntime(28302): 	... 11 more
package com.example.sdimagetutorial;

import java.io.File;
import java.io.FileFilter;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
 
public class MainActivity extends Activity {
 
    // Declare variables
    private String[] FilePathStrings;
    private String[] FileNameStrings;
    private File[] listFile;
    GridView grid;
    GridViewAdapter adapter;
    File file;
    String filePattent = ".jpge";
    String filePattentCAP = ".JPGE";
    String filePattentPNG = ".PNG";
    String filePattentpng = ".png";
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Check for SD Card
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
                    .show();
        } else {
            // Locate the image folder in your SD Card
            file = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "SDImageTutorial");
            // Create a new folder if no folder named SDImageTutorial exist
            file.mkdirs();
        }
        
        if(file.isDirectory())
        	walkdir(file);
        /*if (file.isDirectory()) {
            listFile = file.listFiles();
            // Create a String array for FilePathStrings
            FilePathStrings = new String[listFile.length];
            // Create a String array for FileNameStrings
            FileNameStrings = new String[listFile.length];
 
            for (int i = 0; i < listFile.length; i++) {
                // Get the path of the image file
                FilePathStrings[i] = listFile[i].getAbsolutePath();
                // Get the name image file
                FileNameStrings[i] = listFile[i].getName();
            }
        }
        */
       
        
       
       

 
        // Locate the GridView in gridview_main.xml
        grid = (GridView) findViewById(R.id.gridview);
        // Pass String arrays to LazyAdapter Class
        adapter = new GridViewAdapter(this, FilePathStrings, FileNameStrings);
        // Set the LazyAdapter to the GridView
        grid.setAdapter(adapter);
 
        // Capture gridview item click
        grid.setOnItemClickListener(new OnItemClickListener() {
 
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
 
                Intent i = new Intent(MainActivity.this, ViewImage.class);
                // Pass String arrays FilePathStrings
                i.putExtra("filepath", FilePathStrings);
                // Pass String arrays FileNameStrings
                i.putExtra("filename", FileNameStrings);
                // Pass click position
                i.putExtra("position", position);
                startActivity(i);
            }
 
        });
    }
    private void walkdir(File dir) 
    {
    String filePattent = ".jpge";
    String filePattentCAP = ".JPGE";
    String filePattentPNG = ".PNG";
    String filePattentpng = ".png";
            File listFile[] = dir.listFiles();
            if (listFile != null) 
            {
                for (int i = 0; i < listFile.length; i++) 
                {
                    if (listFile[i].isDirectory()) 
                    {
                        walkdir(listFile[i]);
                    }
                     else if (listFile[i].getName().endsWith(filePattent) || listFile[i].getName().endsWith(filePattentCAP)||listFile[i].getName().endsWith(filePattentPNG) || listFile[i].getName().endsWith(filePattentpng)) 
                    {
                    	 FilePathStrings[i] = listFile[i].getAbsolutePath();
                         // Get the name image file
                         FileNameStrings[i] = listFile[i].getName();
                    }
                }
            }
        }
    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;
        }
        private boolean isImageFile(String filePath) {
            if (filePath.endsWith(".jpg") || filePath.endsWith(".png"))
            // Add other formats as desired
            {
                return true;
            }
            return false;
        }
    }
    
 
}

2 个答案:

答案 0 :(得分:0)

你的walkdir方法()中有一个nullpointer异常。

正如您在异常中从这一行所看到的那样:

at com.example.sdimagetutorial.MainActivity.walkdir(MainActivity.java:113)

在您的主要活动的第113行导致NPE的东西,如果您已经复制了所有代码,则为:

FilePathStrings[i] = listFile[i].getAbsolutePath();

由于您已经在前面的if条件中对listFile [i]进行了检查,这意味着FilePathStrings为null(从您的代码中看起来很可能)。

作为另一条一般建议,我想提供一些其他建议:

  1. 在执行其余循环之前添加listFile [i] .exists()的检查 (迂腐,但有时候会有所帮助)。另外,我建议使用循环迭代器。

  2. 最重要的是,这不是写一个画廊的好方法。您 永远不应该在getView()方法中解码位图,这是一个 真的很糟糕。看看这个例子 - http://javatechig.com/android/android-gridview-example-building-image-gallery-in-android。 基本上,每次滚动都会调用get view方法,所以如果 你去解码位图(一个非常昂贵的操作) 时间看到一个新项目,我向你保证,你的代码会导致ANR。 您应该拥有位图的持有者,并且只对它们进行一次解码, 然后从列表中获取getView中的位图(两者之一) 位图或包含位图的对象。)

答案 1 :(得分:-1)

我为sd-card图像做了Gridview标题,我在下面的链接中共享了整个项目。我希望它会有所帮助。

android gridview header solution with adapter recycling cells