1

I am working on a app where I have to make a custom gallery. For this I have to search all images and folders of images from sd card and show it in a grid view. My code is as follows. Someone please help. Thanks in advance.

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;
        }
    }
    
 
}
Wasim Reza
  • 136
  • 6

2 Answers2

0

There's a nullpointer exception in your walkdir method().

As you can see from this line in your exception:

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

there's something that's causing a NPE on line number 113 of your main activity, which, if you've copied all the code is this line:

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

Since you've already done a check on listFile[i] in the preceeding if condition, this means that FilePathStrings is null (which, from your code, seems quite likely).

As another general piece of advice, I'd like to offer a few other recommendations:

  1. Add a check of listFile[i].exists() before doing the rest of loop (pedantic, but it helps sometimes). Also, I'd recommend using an iterator for the loop.

  2. Most importantly, this is not a good way to write a gallery. You should never be decoding a bitmap in the getView() method, that's a really bad idea. Take a look at this example - http://javatechig.com/android/android-gridview-example-building-image-gallery-in-android. Basically, the get view method gets called on every scroll, so if you go about decoding bitmaps (a very expensive operation) every time a new item is seen, I promise you, your code will cause an ANR. You should have a holder for bitmaps, and decode them only once, then fetching the bitmaps in the getView from a list (of either bitmaps, or objects that contain bitmaps).

-1

I did Gridview header for sd-card images and i shared entire project in below link. I hope it will help full.

android gridview header solution with adapter recycling cells

Community
  • 1
  • 1
Murali Mohan
  • 65
  • 2
  • 5