Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android

I try to write something into my phone memory.

At first, I hard-coded the path as:

myFile = new File("/sdcard/" + txtName.getText() + ".txt");

This works totally ok.

And then, eclipse gives me a warning saying that I shouldn't have hard-coded the path like that instead, I should do the following:

myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ txtName.getText() + ".txt");

Then I follow the correction suggestion and avoid the warning.

However, I encountered a runtime exception on the writer class.

Then, I print out Environment.getExternalStorageDirectory().getAbsolutePath() for debugging purpose. The result is

/storage/sdcard0

. But the hardcoded one that worked perfectly fine before is actually

/sdcard

.

Why would this happen?

And if I wish to avoid the warning, how can I get the path directory in a more "formal and right" way instead of hardcoding the path?

P.S.: My phone is HTC One X, which has NO external SD card slot. I guess the 32GB storage comes with a built-in SD card, and therefore, the essence should be the same.

like image 254
Sibbs Gambling Avatar asked Jun 20 '13 13:06

Sibbs Gambling


People also ask

What is environment getExternalStorageDirectory ()?

Environment. getExternalStorageDirectory() returns top-level directory of the primary external storage.

Where is Getexternalfilesdir?

It returns the path to files folder inside Android/data/data/your_package/ on your SD card. It is used to store any required files for your app (e.g. images downloaded from web or cache files).


1 Answers

Why would this happen?

Because the path to external storage has changed over the years, which is why you should have never hard-coded the path in the first place.

how can I get the path directory in a more "formal and right" way instead of hardcoding the path?

Use Environment.getExternalStorageDirectory().

On your test environment, /sdcard is a symlink or hardlink to /storage/sdcard0, as set up by the device manufacturer. However, there is no guarantee that all devices will have such an /sdcard symlink.

I guess the 32GB storage comes with a built-in SD card

External storage is a portion of your on-board 32GB of flash memory.

like image 85
CommonsWare Avatar answered Oct 16 '22 14:10

CommonsWare