SupposeXYZ SupposeXYZ - 7 months ago 128
Java Question

Directory not creating using mkdir() or mkdirs()

Below is my code for MainActivity.java.The error according to toasts is in creating directory.

MainActivity.java

@Override
protected void onActivityResult(int requestcode,int resultcode,Intent data){
super.onActivityResult(requestcode,resultcode,data);
if (requestcode == TAKE_PICTURE)
{
if(resultcode== Activity.RESULT_OK){

ImageView imageHolder = (ImageView)findViewById(R.id.image_camera);
Bitmap bitmap = (Bitmap)data.getExtras().get("data");

String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);

// display the image from SD Card to ImageView Control
String storeFilename = "photo_" + partFilename + ".jpg";
Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
imageHolder.setImageBitmap(mBitmap);
}
}
}

private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date(0));
return currentTimeStamp;
}
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Toast.makeText(MainActivity.this, "WriteMode ON", Toast.LENGTH_SHORT).show();
return true;
}
Toast.makeText(MainActivity.this, "WriteMode OFF", Toast.LENGTH_SHORT).show();
return false;
}

/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
Toast.makeText(MainActivity.this, "Mounted or ReadMode", Toast.LENGTH_SHORT).show();
return true;
}
Toast.makeText(MainActivity.this, "no-Mounted or no-ReadMode", Toast.LENGTH_SHORT).show();
return false;
}

private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
boolean isAvailable=isExternalStorageWritable();
if(isAvailable){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,90, bytes);
String imgUri = "photo_" + currentDate + ".jpg";
File appDirectory = new File(Environment.getExternalStorageDirectory(),"CountDotsAppImages");
boolean success = appDirectory.mkdirs();
if (success) {
Toast.makeText(MainActivity.this, "Directory Created", Toast.LENGTH_SHORT).show();

} else {
Toast.makeText(MainActivity.this, "Failed - Error", Toast.LENGTH_SHORT).show();
}
File destination = new File(Environment.getExternalStorageDirectory(),"CountDotsAppImages/"+imgUri);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

private Bitmap getImageFileFromSDCard(String filename){
File storageDir = new File(Environment.getExternalStorageDirectory() + "/", "CountDotsAppImages");

Bitmap bitmap = null;
File imageFile = new File(storageDir.getPath()+File.separator + filename);
try {
FileInputStream fis = new FileInputStream(imageFile);
Toast.makeText(MainActivity.this, imageFile.toString() , Toast.LENGTH_LONG).show();
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}


AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
permission is added

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.countdots"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>


Toasts Output :

Mounted or ReadMode

WriteMode ON

Directory Does Not Exist, Create It

Failed -Error //Error in creating directory mkdir

I tried using both mkdir() and mkdirs()

Answer

Figured it out.
As, I was compiling with Android 6.0. It requires user to grant permission from user. So,following code should be inserted and checked if user grants app permission or not.Then if user grants permission to read and write manifest will be updated and volia !!!

if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        1);
            } else {
                //do something
            }
        } else {
                //do something
        }
Comments