views:

32

answers:

1

I'm having trouble reading in from a .CSV file in an android app. Mainly a "FileNotFound" error. Where would be the easiest place to put the file, and what would be the address to it. I have been messing around with a few different places but have had no luck.

Can anyone point me in the right direction?

+1  A: 

You'll probably want it on the removable storage (SD card). First you'll want to check if the storage is available, then read/write.

The docs have some notes on this: http://developer.android.com/intl/de/guide/topics/data/data-storage.html#filesExternal (Note the API level 8 stuff there, such as getExternalFilesDir, I haven't used that yet, but looks handy, if you can guarantee >=8.)

You can check if storage is there with something like:

public boolean isExternalStorageAvail() {
      return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
   }

If it's not there show a Toast (at a minimum) or otherwise let the user know.

Then read it like:

File f = new File(Environment.getExternalStorageDirectory() + "/mycsvlocation/myfile.csv");

Then you can use the regular File methods to check if it's there, it's readable, etc., and then use it.

Also note that the docs recommend you use a location on the SD card like "Android/data//files", and that's a reasonable recommendation, but many apps just use "/appname/" or such.

And -- one more thing, you can put the file there just by mounting the SD card and creating that structure and copying a file over, of course. Alternatively, you could do that programatically (from your app) as well, but it sounds like you already have the file, and just want to read it.

Charlie Collins
Thanks for the answer, but I don't think I can read it from the SD card. I just want to read from the CSV file, put the info into a database, and then use it from there. This app is going to be sold commercially so I don't think the external storage solution would work. But thanks anyway.(I edited because I said text file when I meant CSV)
TehGoose
Well, if you want to ship a pre-defined CSV file *with* your application, that's a bit different. That is a "raw" resource. You can put your file in res/raw and access it from there with Resources.openRawResource. http://developer.android.com/intl/de/reference/android/content/res/Resources.html#openRawResource(int)
Charlie Collins
Also, you can skip the resources thing altogether and use /assets, which can be retrieved with the AssetManager. The best approach really depends on what you're trying to do (read static data, vs read/write data, vs create data and persist, etc.).
Charlie Collins
That is a 'raw' resource."I tried the raw resource, and I have gotten it to work. Thank you for your help :)
TehGoose
Glad to hear you got it to work, cool. As for the "Answer," would you like me to add the comments to the answer so it can be accepted, or does it work as is (you have to accept it, if you think it's worthy).
Charlie Collins