0

My logcat is indicating a null pointer exception, and I don't know how to solve these null pointer exceptions.

Null Pointer exception in my adapter class:

  File dir=new File(Environment.getExternalStorageDirectory(),"/myImages/");

  int count=dir.list().length; 

  String[] fileNames = dir.list();

Check the above lines... that is a value returning null.

My code:

package ImageViewExample.ImageViewExample;

   import java.io.File;

   import android.R.string;
   import android.app.Activity;
   import android.content.Context;
   import android.content.Intent;
   import android.database.Cursor;
   import android.graphics.Bitmap;
   import android.graphics.BitmapFactory;
   import android.net.Uri;
   import android.os.Bundle;
   import android.os.Environment;
   import android.provider.MediaStore;
   import android.view.View;
   import android.view.ViewGroup;
   import android.widget.AdapterView;
   import android.widget.BaseAdapter;
   import android.widget.Gallery;
   import android.widget.GridView;
   import android.widget.ImageView;
   import android.widget.AdapterView.OnItemClickListener;

    public class ImageViewExample extends Activity {
    /** Called when the activity is first created. */
    private Cursor imagecursor, actualimagecursor;
    private int image_column_index, actual_image_column_index;
    GridView imagegrid;
    private int count;
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      init_phone_image_grid();
     }
     private void init_phone_image_grid() {
      String[] img = { MediaStore.Images.Thumbnails._ID };
      imagecursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, 
     img, null,null, MediaStore.Images.Thumbnails.IMAGE_ID + "");


     System.out.println("path"+managedQuery(MediaStore.Images
    .Thumbnails.EXTERNAL_CONTENT_URI, img, null,null, MediaStore.Images
     .Thumbnails.IMAGE_ID + ""));
      image_column_index =   
     imagecursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
      System.out.println("index"+imagecursor.getColumnIndexOrThrow
     (MediaStore.Images.Thumbnails._ID));
      count = imagecursor.getCount();
      imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);

      imagegrid.setAdapter(new ImAdapterh(this));
      System.out.println("index"+this);
      imagegrid.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View v,int position, long id) {
                          System.gc();
      String[] proj = { MediaStore.Images.Media.DATA };
    actualimagecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
    proj,null,null, null);
       actual_image_column_index =   
    actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                  actualimagecursor.moveToPosition(position);
                  String i = actualimagecursor.getString(actual_image_column_index);
                  System.gc();
                  Intent intent = new Intent(getApplicationContext(), ViewImage.class);
                  intent.putExtra("filename", i);
                  startActivity(intent);
            }
      });
    }


   public class ImAdapterh extends BaseAdapter{

   File dir=new File(Environment.getExternalStorageDirectory(),"/Pictures/");
   int count=dir.list().length; 
   String[] fileNames = dir.list();

    private Context mContext;

   public ImAdapterh(Context c) {
       mContext = c;
    }

      public int getCount() {
       return count;
      }

      public Object getItem(int position) {
       return null;
      }

     public long getItemId(int position) {
       return 0;
      }

   // create a new ImageView for each item referenced by the Adapter
     public View getView(int position, View convertView, ViewGroup parent) {
       ImageView imageView = null;        


     for(String bitmapFileName : fileNames)
     {
          if (convertView == null) 
          {  // if it's not recycled, initialize some attributes
              imageView = new ImageView(mContext);
              imageView.setLayoutParams(new Gallery.LayoutParams(85, 85));
              imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
              imageView.setPadding(8, 8, 8, 8);                   

              Bitmap bmp = BitmapFactory.decodeFile(dir.getPath() + "/" +   
               bitmapFileName);
              System.out.println(dir);
              imageView.setImageBitmap(bmp);  
           }else 
           {
           imageView = (ImageView) convertView;            

           }
   } 
       return imageView;
       }
      }}

Logcat error:

05-04 01:41:31.705: ERROR/AndroidRuntime(1417): FATAL EXCEPTION: main
05-04 01:41:31.705: ERROR/AndroidRuntime(1417): java.lang.RuntimeException: Unable to  
start activity  
ComponentInfo{ImageViewExample.ImageViewExample/ImageViewExample
.ImageViewExample.ImageViewExample}: java.lang.NullPointerException
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at   
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
android.os.Handler.dispatchMessage(Handler.java:99)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
android.os.Looper.loop(Looper.java:123)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at   
android.app.ActivityThread.main(ActivityThread.java:4627)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
java.lang.reflect.Method.invokeNative(Native Method)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
java.lang.reflect.Method.invoke(Method.java:521)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
dalvik.system.NativeStart.main(Native Method)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417): Caused by:   
java.lang.NullPointerException
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
ImageViewExample.ImageViewExample.ImageViewExample$ImAdapterh.<init>
(ImageViewExample.java:71)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
ImageViewExample.ImageViewExample.ImageViewExample
.init_phone_image_grid(ImageViewExample.java:49)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at  
ImageViewExample.ImageViewExample.ImageViewExample.onCreate(ImageViewExample.java:36)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at 
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     at   
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-04 01:41:31.705: ERROR/AndroidRuntime(1417):     ... 11 more
TofferJ
  • 4,678
  • 1
  • 37
  • 49
viji
  • 1
  • 2
  • Can you post the stacktrace of the `NullPointerException`? – Boris Pavlović May 04 '11 at 10:12
  • What line gives you the error? It looks to me you're implying it is the last line, but if so then `dir` would be NULL, and then the middle one should also give a nullpointer. Maybe your `FILE` command is failing? – Nanne May 04 '11 at 10:13
  • how to correct my file command? – viji May 04 '11 at 10:16
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Krease Dec 15 '15 at 16:06

3 Answers3

1

The list() method of File can return null. From the Javadoc:

Returns: An array of strings naming the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
0

seems to me that the list() is the one which resulting error, which can be happen because there is no file inside that folder ( "/myImages/" )

To fix that you have to check if the folder is empty or not :

File dir=new File(Environment.getExternalStorageDirectory(),"/myImages/");
if(dir!=null &&dir.list()!=null)
{
 int count=dir.list().length; 
 String[] fileNames = dir.list();
 //...<REST OF THE CODE>
}else
{
  //do empty folder handler here.
}

or

File dir=new File(Environment.getExternalStorageDirectory(),"/myImages/");
if(dir.list()==null)
{
  dir.setList(new ArrayList());// IF LIST is null, create empty list.
}
int count=dir.list().length; 
String[] fileNames = dir.list();
//..<REST OF THE CODE> ..
Rudy
  • 7,008
  • 12
  • 50
  • 85
  • public class ImAdapterh extends BaseAdapter{ File dir=new File(Environment.getExternalStorageDirectory(),"/myImages/"); if(dir!=null &&dir.list()!=null) { int count=dir.list().length; String[] fileNames = dir.list(); //... }else { //do empty folder handler here. } int count=dir.list().length; String[] fileNames = dir.list(); private Context mContext; – viji May 04 '11 at 10:27
  • now i am trying to implement your code..its indicate Syntax error, insert "}" to complete Block – viji May 04 '11 at 10:29
  • try to format your code **(CTRL+SHIFT+F)**and see whether you have extra "{" – Rudy May 04 '11 at 10:36
  • Multiple markers at this line - ArrayList is a raw type. References to generic type ArrayList should be parameterized - The method setList(ArrayList) is undefined for the type File – viji May 04 '11 at 11:00
0

The null pointer exception will be raised when listing the contents or number of files of a directory that does not exist or one that you do not have permissions to.

Check the following:

  1. If external storage access has been mentioned in the manifest.
  2. If the directory whose files you want listed actually exists within the external storage.

Also post the stack trace and logCat outputs. That would also help people help you.

HTH,
Sriram

Sriram
  • 10,298
  • 21
  • 83
  • 136