Android - Accessing storage locations - android

Ok, Quick heads up that I am new to android programming.
I have very basic experience with java from uni.
I've recently been messing around with android studio and app building for my Samsung Galaxy Tab.
Sorry if this has been asked before but i couldn't see it.
I have tried to make an app that displays all the names of files on my SD card. Just at the top level. I made a quick interface with just a button and a text view to start (i'm away a single text view wont display a list but had problems but i got to that anyway)
ended up with the following code.
*public void ShowFolder(View view){
TextView test = (TextView)findViewById(R.id.View);
root = new File(Environment.getRootDirectory().toString());
File[] Files;
Files = root.listFiles();
String[] File_List;
File_List = root.list();*
I then ran this using the debugger to see what ended up in both the array lists.
I ran this code three times over but varied the "Environment.getRootDirectory" to "getExternalStorageDirectory()" and "getDataDirectory()".
Only the getRootDirectory version will return anything.In both other instances the debugger shows NULL for both Files and Files_list.
I know they are valid locations because used those commands then outputted to strings which i can manually find on my tablet with a file browser.
So, simply put, why dont all three of these options return file lists?
My first thought it permissions but I was unsure how to confirm this.
(Sorry for the long post)

Don't use toString() to create File. getRootDirectory() already returns File object.
Try something like this:
File root = Environment.getRootDirectory();
String[] rootList = root.list();
File[] rootListFiles = root.listFiles();
Also you need to obtain READ_EXTERNAL_STORAGE permission as you can see here in the docs of getExternalStorageDirectory()

Related

Where is my file in Android application(Xamarin)?

I wrote a test Android app in Xamarin, where sample data was stored in a file. Somehow I copied test data file to emulator, successfully run the app and forgot about the project for couple of months.
Now I am resuscitating the project and - I can't find the file in Android Device Manager although it is still accessible in the emulator. It drives me nuts, I need to edit it!
Perhaps someone can point me to the right way to locate the file. Thanks!
Following is the code fragment that reads the file. I added debug output in the comments after each relevant line
var fileName = "NursePurse.jobjson1.txt";
var assembly = typeof(pageJobs).GetTypeInfo().Assembly;
//assembly.base.CodeBase = "file:///storage/emulated/0/Android/data/NursePurse.Droid/files/.__override__/NursePurse.dll"
String fname = assembly.FullName;
//fname = NursePurse, Version=1.0.6504.22050, Culture=neutral, PublicKeyToken=null
Stream stream = assembly.GetManifestResourceStream(fileName);
List<String> t = assembly.GetManifestResourceNames().ToList();
// there are two entries
// "NursePurse.AppResources.resources","NursePurse.jobjson1.txt"
// here is my file! But I don't see neither of these files in the android device manager.
Question - where is it?
Following is the screenshot of Android Dev.Manager View and Device definition with SIM card

How to load Textures with Unity3d on Android

i am trying to get this really easy setup to work, and it works on my computer but not on Android.
After trying it for the whole day im now asking since i cant find a single example on the internet.
The setup:
I have a lot of *.png files in a folder. Since the problem is with android i put them into a "StreamingAssets" folder
I have a RawImage called "Overlay"
I have a Dropdown called "Dropdown"
What should happen:
1. The Dropdown_script checks the StreamingAssets folder for all *.png files and adds every Filename to the dropdown options menu.
2. Once the user chooses one of the dropdown values my "Overlay" image changes its texture to the according file.
Pretty easy on PC ... impossible on android(with unity3d) as it seems.
My Dropdown Script:
public class DDScript : MonoBehaviour {
void Start () {
GameObject obj = GameObject.Find("Dropdown");
//Get all filenames
var info = new DirectoryInfo(Application.streamingAssetsPath);
var fileInfo = info.GetFiles("*.png");
//Clear the DropDown Menu Items from the Inspector
obj.GetComponent<Dropdown>().options.Clear();
//Make the first chosen item the first filename
obj.GetComponent<Dropdown>().captionText.text = fileInfo[0].Name.Substring(0, fileInfo[0].Name.IndexOf("."));
foreach (var file in fileInfo)
{
Dropdown.OptionData list = new Dropdown.OptionData(file.Name.Substring(0, file.Name.IndexOf(".")));
obj.GetComponent<Dropdown>().options.Add(list);
}
}
Its not working. It is working on my Computer but it is just not working on Android. I know that under Android everything gets packed into a jar file and there is nothing like a folderstructure. StreamingAssets should still have the files but i can understand that this part maybe cant work. Which would not be that bad, since it just finds the names and puts it into an array, i could do that within the program by hand. Since i know from beforehand how much and which files will be in the folder and it wont change ever.
This is my Change Texture Method
It is invoked by the Dropdown OnValueChange so the "newOverlay" is simply the int from the Dropdown. For debugging purposes i set the filepath to a specific file. later it will change depending on newOverlay
public IENumerator SetOverlay(int newOverlay)
{
GameObject obj = GameObject.Find("Overlay");
img = (RawImage)obj.GetComponent<RawImage>();
string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "testfile.png");
WWW www = new WWW(filePath);
yield return www;
img.texture = www.texture;
}
And i do not understand why this is not working!
The Documentation reads:
" This means that if you do not use Unity’s WWW class to retrieve the file then you will need to use additional software"
So using www is the right way. But it is not working!
No Texture gets loaded. i dont get the red questionmark, my image is just plain white. Please can someone help me here? Maybe i just cant see the forest due to all of the trees or the day was too long.
I really just cant believe that it is this hard to load a bunch of images that are within my apk file wiht unity :(
Thank you very much in advance
Edit: Solution (somehow)
First of all the problem was that System.IO.Path.Combine adds a back-slash between file and folder, but not between the folders themself!!!!
public void SetOverlay(int newOverlay)
{
GameObject obj = GameObject.Find("Overlay");
img = (RawImage)obj.GetComponent<RawImage>();
string filePath = Application.streamingAssetsPath + "/testfile.png";
WWW www = new WWW(filePath);
while (!www.isDone)
{}
img.texture = www.texture;
GameObject.Find("DebugText").GetComponent<Text>().text = filePath;
}
Havent found a solution to the Filename problem yet but im glad that this stupid "bug" is resolved
Have you tried putting the png files into the drawable folder and accessing them with BitmapFactory.decodeResources()?

Air for android ignores external swf files

I am working on some app that loads external swfs from the application directory
the problem is that some swf files get loaded correctly and others give ioerror url not found
i put the paths in an array and use a loader to load the path
var arr:Array = ["Games/1.swf", "Games/2.swf"];
var loader:Loader = new Loader();
loader.load(new URLRequest(arr[0]));
this is just example and it is the same in loading all the files but does not work on all files.
what would be the problem?
Firstly, whenever you load something, listen for the appropriate error events so you know what's going on:
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
When using mobile, you should use the app:// shorthand as a reference to the application directory (which I assume is where your Game folder is. Relative paths do not usually work.
So it should look like this:
var arr:Array = ["app://Games/1.swf", "app://Games/2.swf"];
For more information/options, you can look at my answer to this question

Titanium 3.X getFile() from local storage

Using Titanium on Android 4+ I want to access a jpeg file which has been taken with the camera. I need to achieve 2 objectives, namely, return the EXIF data and transfer the bytes to an API endpoint. My problem is I'm unable to access the file...
I'm using a 3rd party module to handle the file selection (Multi Image Picker) which returns a list of file locations, using the File Manager app on the emulator (GenyMotion) I can confirm the location on disk is correct. However, the following always returns false...
var file = Ti.Filesystem.getFile('/mnt/sdcard/DCIM/Camera/IMG_20140901_083735.jpg');
Ti.API.info('Do we have a file? ' (file.exists()? 'YES' : 'NO'));
The output for the above would be... Do we have a file? NO
Further reading shows Titanium has 5 predefined folder locations which can be passed into the getFile() method and one possible reason for the above code not working would be it is defaulting to the 'Resouces' folder location? That said all but one folder location is app specific, the exception being externalStorageLocation. Now my understanding of an Android device is that any image taken with the camera will be stored on the internal storage system unless an SD card is present. This is true in my case as the following lists 0 files...
var extDir = Ti.Filesystem.getExternalStorageDirectory();
var dir = Ti.Filesystem.getFile(extDir);
var dir_files = dir.getDirectoryListing();
Ti.API.info('External files... ' + dir_files.length);
The output for the above would be... External files... 0
So am I right in thinking Appcelerator have simply not included the ability to access local storage (outside of any app specific folders) within their API? Or am I missing something and there is in fact another way?
Thanks to #Bharal I was able to find a solution...
By using the Ti.Media.openPhotoGallery() method I was able to identify the correct native path for the image by inspecting the event object returned from the success callback.
The path was missing 'file://' at the beginning, I couldn't be 100% sure but I suspect this forces the getFile() method to use an absolute path and not a relative path from within the Resources folder.
To confirm, the following will return a file object...
var file = Ti.Filesystem.getFile('file://[path]');
Where [path] is the folder location as reported within the File Manager app on the device, for example '/mnt/sdcard/DCIM/Camera/IMG_20140901_083735.jpg'
Yah mon, i dunno.
Here is wat i used when i was doin pictures on my Ti app, but then i got rid of that section because i realised i didn't need to be doin pictures. Pictures mon, dey ain' what you want sometimes, yo?
Ti.Media.openPhotoGallery({ //dissall jus' open up a piccha selectin' ting. ez.
success:function(event){
var image = event.media;
if (event.mediaType==Ti.Media.MEDIA_TYPE_PHOTO){
//so image.nativePath is the path to the image.
// profileImg be jus' some Ti.UI.createImageView ting yo be puttin in yo' page.
//meyybe yo be wantin' alert(image.nativePath); here too, dat be helpin?
profileImg.image = image.nativePath;
}
},
cancel:function(){
//we cancelled out, why we doin' that?
}
});
Now that isn't going to really be helpin' you, but yo can use that to see wat the native path yo piccha be usin' be, and then be seein' if maybe what yo be puttin' in yo code be sam ting.
Jus' wrap the above as an addEventListener("click", function(){ ... } ); on sam ting in yo page, and jus' add sam element to put th' piccha in if yo be wantin' to see the piccha but i be tellin' you picchas mon, sometimes dey ain' worth time.
But meyybe yo wantin' use not an emulator for dis ting, dey can be actin' weird yo should be usin some small phone maybe? Dat way you can be findin' if yo got dem memory leeks and meyybe some memory sprouts, an memory onions too.

Using 'FileWriter' to Write to a Text File on an SD Card in Android

I've researched this problem for a while now and I've only found really complicated answers so I'm very confused. Keep in mind that I'm not an expert programmer so don't expect me to know a ton about this!
All I want to do is print a new line of characters to a text file located in the downloads folder of an SD card in Android. I set up my emulator to have an SD card and placed the text file in the downloads folder. This piece of code is for a database class that will access a text file in an SD card to read the data. I know that the class works outside of Android so assume that all of the methods are working as they should to read the data!
I get an IOException when I run this method in another class:
public void addRecordToDataBase(ChildRecord c) throws IOException
{
FileWriter outFile = new FileWriter("/mnt/sdcard/download/database.txt");
PrintWriter out = new PrintWriter(outFile);
out.println(c.printToDataBase());
out.close();
}
The weird thing is I can read from the database just fine in other methods using that same path; no problems there. I just can't write to it. I've read somewhere that you can use "regular Java methods" to write to an SD card in Android without those crazy "OutputStream" things all over the place. Is this true? I debugged this thing and found out that the line of code that is throwing the exception is right here:
FileWriter outFile = new FileWriter("/mnt/sdcard/download/database.txt");
If anyone has any idea why I'm geting this IOException, I would be really grateful! I did try all the crazy methods that Android wants to use but I think I got lost in it so I just reverted back to what I knew how to do.
Thank you so much!
My guess is you can't access such directory with writing permissions, at least in that manner.
Did you take a look at http://developer.android.com/guide/topics/data/data-storage.html#filesExternal?
That reference and this one (http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)), explaining how getExternalFilesDir works, may be of help to you!
Have you declared the WRITE_EXTERNAL_PERMISSION permission in your apps manifest file?

Categories

Resources