首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >搜索图像文件和图像文件夹,并在网格视图中显示

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

Stack Overflow用户
提问于 2014-11-10 15:14:07
回答 2查看 921关注 0票数 1

我在一个应用程序上工作,我必须使一个自定义画廊。为此,我必须从SD卡中搜索所有图像和图像文件夹,并在网格视图中显示它。我的代码如下。谁来帮帮忙。提前谢谢。

代码语言:javascript
复制
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;
    }
}
代码语言:javascript
复制
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
代码语言:javascript
复制
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;
        }
    }
    
 
}

EN

回答 2

Stack Overflow用户

发布于 2014-11-10 16:03:48

在walkdir方法()中有一个空指针异常。

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

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

在你的主要活动的第113行上,有一些东西导致了NPE,如果你已经复制了所有的代码,那就是这一行:

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

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

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

  1. 在执行循环的其余部分之前添加了一个listFilei.exists()检查(学究,但它有时也有帮助)。另外,我推荐使用循环迭代器。
  2. 最重要的是,这不是编写图库的好方法。您永远不应该在getView()方法中解码位图,这是一个非常糟糕的想法。看看这个例子-- http://javatechig.com/android/android-gridview-example-building-image-gallery-in-android。基本上,每次滚动时都会调用get view方法,所以如果您每次看到新项时都要解码位图(一个非常昂贵的操作),我向您保证,您的代码将导致ANR。您应该有一个位图持有者,并且只对它们解码一次,然后从列表(位图或包含位图的对象)中获取getView中的位图。
票数 0
EN

Stack Overflow用户

发布于 2015-03-06 15:23:51

我做了SD卡图像的Gridview标题,我在下面的链接中分享了整个项目。我希望它能帮上大忙。

android gridview header solution with adapter recycling cells

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26838559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档