-2

please help me.i write this code :

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        File[] files=dir.listFiles();
        Toast.makeText(this,files.length+"",Toast.LENGTH_LONG).show();

    }
}

and it has this error :

Caused by: java.lang.NullPointerException
    at ir.itpro.videosample.MainActivity.onCreate(MainActivity.java:20)

i put 3 files in directory downloads .

how to fix it now??

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49

2 Answers2

0

Make sure you have added the following permission:

READ_EXTERNAL_STORAGE

Also, how are you putting the files in that directory? Through download manager or programmatically?

0

Have you added read external storage permission to your manifest? If not, please add

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

line to it.

If the app don't have the permission, then

dir.listFiles()

returns null, so you call length on a null array.

If your targetSdkVersion is greater than 22, then you need to handle permissions runtime. Further description about runtime permissions can be found here.