0

Hi i am creating folder in external storage.first i need to check that Sd card is present or not.In my mobile i dont have sd card.i am using redmi mobile.Below is my code.I dnt have sd card bt i am getting sd card is mounted.Then i checked my internal storage i cant found the folder what i created.i had tried so many codes,please help me.i also added read and write external permission. my code is:`

String state;
        state=Environment.getExternalStorageState();

        if(Environment.MEDIA_MOUNTED.equals(state)){

            Toast.makeText(this, "Sd card found", Toast.LENGTH_SHORT).show();
            File root=Environment.getExternalStorageDirectory();

            File dir=new File(root.getAbsolutePath()+"/myappfile");

            if(!dir.exists()){
                dir.mkdir();
            }


        }
        else {
            Toast.makeText(this, "SD card not found", Toast.LENGTH_SHORT).show();
        }`
Haem
  • 929
  • 6
  • 15
  • 31
lucky
  • 77
  • 9
  • Which is the version of Android where you are trying it? If it is upper v6 (API 23) you need to request runtime permission to write in the external storage – Alberto Méndez Mar 01 '17 at 13:13
  • `dir.mkdir();`. You are not checking the return value. You should check it as it might fail to create the directory. If it fails display a toast to the user telling so. And return. Do not continue with the code. – greenapps Mar 01 '17 at 14:21
  • `i am creating folder in external storage.first i need to check that Sd card is present or not`. No not at all as external storage directory has nothing to do with a removable micro SD card. External storage is always present. – greenapps Mar 01 '17 at 14:24
  • @ alberto..thank you .i forgot to write run time permissions for mmarshmallow...now folder is created.. – lucky Mar 03 '17 at 06:45

2 Answers2

0

Try this code -

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

if(isSDPresent)
{
  // yes SD-card is present
 }
else
{
 // Sorry
 }

Source - https://stackoverflow.com/a/7429264/1649353

And also check Environment.isExternalStorageRemovable()

Community
  • 1
  • 1
Ambuj Kathotiya
  • 369
  • 4
  • 18
0

Try someting like this

if(Environment.MEDIA_MOUNTED.equals(Environnement.getExternalStorageState()))
{
   File f = new File(Environment.getExternalStorageDirectory(), "/myappfile");
   if (!f.exists()) {
      if.mkdirs();
   }
}
creekorful
  • 351
  • 4
  • 14