kenan shukurov
kenan shukurov

Reputation: 21

My File[] Nullpointerexecption error

String folder = Environment.getExternalStorageDirectory()+ "/books";
File file=new File(folder);

File[] f;
f=file.listFiles(); //////f==null; 

Toast.makeText(getApplicationContext(), f[1].toString(),    
Toast.LENGTH_SHORT).show();

I am not able to fix the error . I need to help. Thanks.

Upvotes: 0

Views: 44

Answers (3)

Karthik
Karthik

Reputation: 5040

I think your directory path does not exists.

Check the documentation of File.listFiles(). It says

An array of abstract pathnames denoting 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.

You are giving a incorrect directory path, that is why file.listFiles(); is returning null.

As you are using Environment.getExternalStorageDirectory(), may be you have not enabled external storage for emulator. Just make sure that you have enabled external storage, this link will be helpful.

It's safer to check if f is null before accessing it:

   if(f!=null){
      Toast.makeText(getApplicationContext(), f[1].toString(),    
      Toast.LENGTH_SHORT).show(); // also size of f[], if you really want to access f[1]
   } 

Upvotes: 0

osimer pothe
osimer pothe

Reputation: 2897

'file' is of File not Folder . That is why you can not get anything on calling file.listFiles() .

String path = Environment.getExternalStorageDirectory().toString()+"/books";
Log.d("Files", "Path: " + path);
File f = new File(path);        

 if (f.isDirectory()){
File file[] = f.listFiles();
  Toast.makeText(getApplicationContext(), file[1].toString(), Toast.LENGTH_SHORT).show();

 }else{

 Toast.makeText(getApplicationContext(), "folder is empty", Toast.LENGTH_SHORT).show();

 }

Upvotes: 0

Moubeen Farooq Khan
Moubeen Farooq Khan

Reputation: 2885

what you can do is you can have a check like below

String path = Environment.getExternalStorageDirectory().toString()+"/books";
Log.d("Files", "Path: " + path);
File f = new File(path);        
File file[] = f.listFiles();
if(file!=null&&file.length>0){

  Toast.makeText(getApplicationContext(), f[1].toString(), Toast.LENGTH_SHORT).show();

 }else{

 Toast.makeText(getApplicationContext(), "folder is empty", Toast.LENGTH_SHORT).show();

 }

what above code is doing basically it is checking that if length is greater the 0 and file objext is not null. that display the toast containing second file name in the list.

Upvotes: 1

Related Questions