bharath bharath - 9 months ago 34
Android Question

Lenovo not allowing to create folder in sd card

I'm trying to create a folder in android sd card...For that I've added permission in manifest file and My this is my code..

public void createFile(View view)
{
String state= Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
res=wallpaperDirectory.mkdir()
if(res){
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "Failed", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(this, "Make sure that you have a memory card mounted...", Toast.LENGTH_SHORT).show();
}
}


When I ran the same code in kitkat emulator its creating folder but Its always saying failed in lenovo...Thanks in advance...

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="bk.acs">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SubActivity1"></activity>
</application>

</manifest>

Answer Source

You are NOT suppose to hard code file paths in Android. /sdcard/ doesn't work for all Android devices.

Use Environment.getExternalStorageDirectory() instead.

Here's how:

String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
    File wallpaperDirectory = new File(Environment.getExternalStorageDirectory(), "Wallpaper");
    if(!wallpaperDirectory.exist()) {
        wallpaperDirectory.mkdir();
        ...
    }
}

Also, if you are testing on 6.0+ Android version, just declaring permission in AndroidManifest.xml is not enough. You need to request permission during run time. That is another reason why it might be working KitKat but not on newer Android versions.