0

My code used to work but now I can't even make a directory. (Notice that "1" isn't printed to the logcat.) I have no idea what I broke. I am trying to save an image in a folder I create, here is my code:

    String storedir = "/sdcard";
    String separator = "/";
    String mDateTime = formatter.format(cal.getTime());
    File newdir1 = new File(storedir + "/" + mDateTime);
            if (newdir1.mkdir())
                System.out.println("1");

    File newdir2 = new File(storedir + "/" + mDateTime + "/");
            if (newdir2.mkdir())
                System.out.println("2");

   // Fall into the catch because of ;
                if (fileNameLower.indexOf(".jpeg") > 0)
            fileExt = ".jpeg";
                String rand_fileName = Long.toString(System.currentTimeMillis());// +fileExt;
        String last_fileName = rand_fileName + fileExt;
            File storefile = new File(storedir + "/" + mDateTime + "/" + separator
                + last_fileName);
        String picAddress = storedir + "/" + mDateTime + "/" + separator
                + rand_fileName + ".png";
        System.out.println("135 : [" + storefile.toString() + "]/n");

        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try {
            Log.w("Process : " , "Starting to download process.");
            bos = new BufferedOutputStream(new FileOutputStream(storefile));
            bis = new BufferedInputStream(in);
            int c;
            while ((c = bis.read()) != -1) {
                bos.write(c);
                bos.flush();
            }
            Log.w("Process : " , "The image is downloaded.");
        } catch (Exception exception) {
            exception.printStackTrace();
            throw new Exception("151 : !");
        } finally 
        {
            bos.close();
            bis.close();
        }



04-29 21:29:20.648: W/The image's type(5733): .jpeg
04-29 21:29:20.648: I/System.out(5733): log : [.jpeg]/n
04-29 21:29:20.652: I/System.out(5733): log : [/sdcard/2012-04-29/1335734960650.jpeg]/n
04-29 21:29:20.652: W/Process :(5733): Starting to download process.
04-29 21:29:20.652: W/System.err(5733): java.io.FileNotFoundException: /sdcard/2012-04-29/1335734960650.jpeg (Permission denied)
04-29 21:29:20.672: W/System.err(5733):     at org.apache.harmony.luni.platform.OSFileSystem.open(Native Method)
04-29 21:29:20.672: W/System.err(5733):     at dalvik.system.BlockGuard$WrappedFileSystem.open(BlockGuard.java:232)
04-29 21:29:20.682: W/System.err(5733):     at java.io.FileOutputStream.<init>(FileOutputStream.java:94)
04-29 21:29:20.682: W/System.err(5733):     at java.io.FileOutputStream.<init>(FileOutputStream.java:66)
04-29 21:29:20.682: W/System.err(5733):     at com.mobil.eposta.Baglanti.saveFile(Baglanti.java:345)
04-29 21:29:20.692: W/System.err(5733):     at com.mobil.eposta.Baglanti.saveAttachMent(Baglanti.java:255)
04-29 21:29:20.692: W/System.err(5733):     at com.mobil.eposta.Baglanti.EkiKaydet(Baglanti.java:235)
04-29 21:29:20.692: W/System.err(5733):     at com.mobil.eposta.Baglanti.Position(Baglanti.java:224)
04-29 21:29:20.692: W/System.err(5733):     at com.mobil.eposta.GoruntuleActivity$1.onClick(GoruntuleActivity.java:75)
04-29 21:29:20.707: W/System.err(5733):     at android.view.View.performClick(View.java:2485)
04-29 21:29:20.707: W/System.err(5733):     at android.view.View$PerformClick.run(View.java:9080)
04-29 21:29:20.712: W/System.err(5733):     at android.os.Handler.handleCallback(Handler.java:587)
04-29 21:29:20.712: W/System.err(5733):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-29 21:29:20.712: W/System.err(5733):     at android.os.Looper.loop(Looper.java:123)
04-29 21:29:20.712: W/System.err(5733):     at android.app.ActivityThread.main(ActivityThread.java:3683)
04-29 21:29:20.712: W/System.err(5733):     at java.lang.reflect.Method.invokeNative(Native Method)
04-29 21:29:20.712: W/System.err(5733):     at java.lang.reflect.Method.invoke(Method.java:507)
04-29 21:29:20.722: W/System.err(5733):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-29 21:29:20.732: W/System.err(5733):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-29 21:29:20.732: W/System.err(5733):     at dalvik.system.NativeStart.main(Native Method)

What should I do for the sdcard's mounted situation?

In this code the result is "NOT GOOD" statement. How can I change this situation?

private static boolean  checkExternalMedia()
{
    boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        // Something else is wrong. It may be one of many other states,
        //  to know is we can neither read nor write
        Log.i("TAG","State="+state+" Not good");
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }

    Log.i("TAG","Available="+mExternalStorageAvailable+"Writeable="+mExternalStorageWriteable+" State"+state);
    return (mExternalStorageAvailable && mExternalStorageWriteable);
}
Merve Gül
  • 1,377
  • 6
  • 23
  • 40
  • Thank you for including your logcat, but it is a little small. Next time please use the disk icon (labeled "Export Selected Items...") in the upper right of your logcat window to post a _text_ copy. – Sam Apr 29 '12 at 21:40

3 Answers3

1

You need

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

in your Manifest file. See other questions on stackoverflow for example Permission to write to the SD card

Community
  • 1
  • 1
bart
  • 2,378
  • 2
  • 19
  • 21
  • I write it already. Like I said this code was working yesterday. I dont know what happened, but today isnt working. – Merve Gül Apr 29 '12 at 21:22
1
  • Instead of using "/sdcard" constant string, use Environment.getExternalStorageDirectory().getAbsolutePath()

This will give you the sdcard root path (which may not be just "/sdcard" in some devices

  • It's normally "/mnt/sdcard", not "/sdcard". If you want to experiment with things, the first thing to do is get some facts straight.

  • You initialized a "separator" constant, yet you keep on using "/" to create your paths. This is quoted from the code you pasted with your question:

    File storefile = new File(storedir + "/" + mDateTime + "/" + separator + last_fileName);

Can you see anything wrong with it?

josephus
  • 8,284
  • 1
  • 37
  • 57
  • Thanks for your reply I change "storedir" with "Environment.getExternalStorageDirectory().getAbsolutePath()" . And I delete the separator from the lines which are wrong. But it doesnt still working. I add almost my whole code but my problem is at fifth line. newdir1.mkdir() the exception is happening because of it. It doesnt create – Merve Gül Apr 29 '12 at 21:35
  • I'm seeing part of "Permission Denied" error in your logs, just along the lines of FileNotFoundException. Are you really sure you have the permission in your manifest? – josephus Apr 29 '12 at 21:38
  • Yes, I am absoultely sure about this. I know, I added that. But for your reply I checked it and the permission is in manifest. – Merve Gül Apr 29 '12 at 21:41
  • mkdirs instead of mkdir should ensure that File deliberately creates folders if they don't exist, to satisfy the path you defined. As I assume you're using eclipse, may I remind you that everything I mentioned here is readily available information within the javadoc popups. – josephus Apr 29 '12 at 21:45
  • I used mkdirs, but it didnt work too. I am not sure that you are saying to me use mkdirs.. I already used it but it didnt change anything.. what about createnewfile? Can I use it for this situation? – Merve Gül Apr 29 '12 at 21:52
  • I am assuming it was happening because of "mounted". I found a method for this and my code is fall write and read = false. How can I change this situation to write and read = true? – Merve Gül Apr 29 '12 at 22:04
  • While running your code, is your phone's sdcard mounted to your pc? Remove that. This will be my last comment. I suggest you update your code and logs so others can take a shot at your problem. Also try to do things first before asking if "will it work" - should be a hell lot easier than waiting for someone to tell you it will. – josephus Apr 29 '12 at 22:07
0

It is much safer and simpler to use the File class to build your paths.

Try it that way:

if (!checkExternalMedia()) {
    // show error dialog here.
    return;
}

File storedir = Environment.getExternalStorageDirectory();

String mDateTime = formatter.format(cal.getTime());
File savedir = new File (storedir, mDateTime);

if (fileNameLower.indexOf(".jpeg") > 0) {
    fileExt = ".jpeg";
}
String rand_fileName = Long.toString(System.currentTimeMillis());// +fileExt;
String last_fileName = rand_fileName + fileExt;

File storefile = new File(storedir, last_fileName);

// create all directories required for that file
if (!storefile.mkdirs()) {
    Log.e("Process", "can't create directories:" + storefile.getParent());
    // return here too
}

// here be streams
zapl
  • 63,179
  • 10
  • 123
  • 154
  • Thanks, I tried this code and it is not solve the exception. Meanwhile, I found a code sample (I edit it to my question) . And the result is "Not good" statement. What should I do for the sdcard's mounted situation? – Merve Gül Apr 30 '12 at 09:51
  • You can't do anything if the sdcard is not mounted (`if (!checkExternalMedia())`). In that case you can only show an error dialog or something like that. If you have your devices connected via USB to your PC and the sdcard is shared then unshare it so the sdcard can be used by Android again. – zapl Apr 30 '12 at 10:03
  • "If you have your devices connected via USB to your PC and the sdcard is shared then unshare it so the sdcard can be used by Android again." Could you please elaborate on how one can do that? – RenniePet Feb 23 '15 at 10:44