How to read data from /data folder

Hello,
i'm using PCLStorage in my app, and PCLStorage has as default storage folder for Android the folder /data/data/package-name/files,
so i'm saving some data on it, but i'm unable to access it (with code calls) afterwards
what am i missing ?

Answers

  • TroelsThistedTroelsThisted DKMember ✭✭
    edited May 2016

    allright so how i do this is as follows:

    In my PCL i have saved interfaces like below:

    public interface InterfaceAudio
    {
    void PlayMp3File(string fileName);
    }
    

    I have a interface that is used to play audio, this audio is placed in a folder in the android project.

    In my android project i have a class, that is implementing the above interface from the PCL:

    [assembly: Dependency(typeof(AudioService))]
    namespace _app.Droid.Interfaces
    {
       public class AudioService : InterfaceAudio
       {
          private List<string> _positives;
          private List<string> _negatives;
    
          private static Random _rand = new Random();
    
    
          public AudioService()
          {
             _positives = new List<string>();
             _positives.Add("Positiv1.mp3");
             _positives.Add("Positiv2.mp3");
             _negatives = new List<string>();
             _negatives.Add("Negative1.mp3");
             _negatives.Add("Negative2.mp3");
          }
    
          private MediaPlayer _mediaPlayer;
    
          public void PlayMp3File(string fileName)
          {
             if(_mediaPlayer != null && _mediaPlayer.IsPlaying)
             {
                _mediaPlayer.Stop();
                _mediaPlayer.Release();
             }
             _mediaPlayer = MediaPlayer.Create(global::Android.App.Application.Context, Resource.Raw.tone);
             _mediaPlayer.Start();
          }
       }
    }
    

    Then in my PCL, i can call this method by doing like below!

        DependencyService.Get<InterfaceAudio>().PlayMp3File("tone.mp3");
    

    plays the audio tune no problem!

    Hope it helps!

  • Yeah it might help indeed, i'm going to check what i can do with this in my code, thanks a lot @TroelsThisted. Would it work the same on iOS side ? I go back to you if I got some difficulties or so

  • TroelsThistedTroelsThisted DKMember ✭✭
    edited May 2016

    @FranoisGrzybowski It should work just fine, as long as you implement the interface in your class on the IOS project!
    It is pretty much doing the exact same thing!

  • TroelsThistedTroelsThisted DKMember ✭✭

    @FranoisGrzybowski said:
    Yeah it might help indeed, i'm going to check what i can do with this in my code, thanks a lot @TroelsThisted. Would it work the same on iOS side ? I go back to you if I got some difficulties or so

    btw i see that i wrote somwthing wrong up there.... the interface should be placed in your PCL project. and the class that inherit the interface should be placed in the android/IOS projekt!

  • ThomasBurkhartThomasBurkhart DEMember ✭✭✭✭

    How do you acess/save your dat with PCLStorage? It works fine for me. Please show use some of you code.

  • TroelsThistedTroelsThisted DKMember ✭✭
    edited May 2016

    Ohh god i think i have misread the question in here... PCL storage is for saving data on the phone right? :open_mouth:

    What i have been writing about is how to transfer data between your shared library and your phone projects >.<

  • FranoisGrzybowskiFranoisGrzybowski FRMember
    edited May 2016

    @ThomasBurkhart here's my code, it's a draft so it's quite messy.
    First the PCL code
    Step 1 - I retrieve a base64 string from a web service
    Step 2 - I decode the base64 back to zip file and save it to the device
    Step 3 - I unzip it, create folders and files
    I call this method in a InitActivity so that the property IndexURL is set. Then I pass this string to my MainActivity where i must use it.

    public class FileManager(){
    ...
        public string IndexURL {get;set;}
        private async void ManageFiles()
                {
                    string base64str = "";
                    //Step1
                    try
                    {
                        string url = Constantes.ZIP_FILE_URL;
                        using (HttpClient client = new HttpClient())
                        using (HttpResponseMessage response = await client.GetAsync(url))
                        using (HttpContent content = response.Content)
                        {
                            base64str = await content.ReadAsStringAsync();
                            Debug.WriteLine(Messages.FM_WEBSERVICE_CALL_SUCCESS_MESSAGE);
                        }
                    }
                    catch (Exception e)
                    {
                        base64str = "error";
                        Debug.WriteLine(Messages.FM_WEBSERVICE_CALL_ERROR_MESSAGE + e.Message);
                    }
    
                IFolder currFolder;
                //Step2
                try
                {
                    string content = base64str.Substring(1, base64str.Length - 2);
                    byte[] contentAsBytes = System.Convert.FromBase64String(content);
    
                    using (MemoryStream contentStream = new MemoryStream())
                    {
                        await contentStream.WriteAsync(contentAsBytes, 0, contentAsBytes.Length);
                        contentStream.Position = 0;
    
                        zipFile = await worldSubFolder.CreateFileAsync("world.zip", CreationCollisionOption.ReplaceExisting);
                        using (Stream fileHandler = await zipFile.OpenAsync(FileAccess.ReadAndWrite))
                        {
                            contentStream.Position = 0;
                            await contentStream.CopyToAsync(fileHandler);                        
                        }
                        //Step 3
                        using (Stream stream = await zipFile.OpenAsync(FileAccess.ReadAndWrite))
                        {
                            using (ZipInputStream s = new ZipInputStream(stream))
                            {
                                ZipEntry entry;
                                while ((entry = s.GetNextEntry()) != null)
                                {
                                    string direName = Path.GetDirectoryName(entry.Name);
                                    string fileName = Path.GetFileName(entry.Name);
    
                                    if (direName.Length > 0 && !direName.StartsWith("__MACOSX"))
                                    {
                                        currFolder = worldSubFolder.CreateFolderAsync(direName, CreationCollisionOption.OpenIfExists).Result;
    
                                        if (fileName != String.Empty)
                                        {
                                            IFile currFile = await currFolder.CreateFileAsync(fileName, CreationCollisionOption.FailIfExists);
                                            using (Stream sWriter = await currFile.OpenAsync(FileAccess.ReadAndWrite))
                                            {
                                                await sWriter.CopyToAsync(stream);
                                                Debug.WriteLine(Messages.FM_ZIPFILE_UNZIP_FILE_CREATED_SUCCESS_MESSAGE + fileName + " , @:" + direName);
                                            }
    
                                            if (fileName.EndsWith(".html"))
                                            {
                                                Debug.WriteLine(currFile.Path);
                                                IndexURL = currFile.Path;
                                            }
                                        }
    
                                    } else if (direName.Length == 0) {
    
                                        currFolder = worldSubFolder;
    
                                        if (fileName != String.Empty)
                                        {
                                            IFile currFile = await currFolder.CreateFileAsync(fileName, CreationCollisionOption.FailIfExists);
                                            using (Stream sWriter = await currFile.OpenAsync(FileAccess.ReadAndWrite))
                                            {
                                                await sWriter.CopyToAsync(stream);
                                                Debug.WriteLine(Messages.FM_ZIPFILE_UNZIP_FILE_CREATED_SUCCESS_MESSAGE + fileName + " , @:" + direName);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    Debug.WriteLine(Messages.FM_ZIPFILE_UNZIP_ERROR_MESSAGE + e.Message.ToString());
                }
    }
    

    Now in the MainActivity I already called this big method and i have the file's url, WORLD_URL correspond to the same file in my assets in case i can't launch the one i just unzipped

    protected override void OnCreate(Bundle bundle)
            {
        string WORLD_URL = "planetmodel/index.html";
                base.OnCreate(bundle);
                SetContentView(Resource.Layout.Main);
                worldURL = ("file://" + Intent.GetStringExtra("worldURL")) ?? WORLD_URL ; 
                System.Console.WriteLine(">> WORLD URL: " + worldURL);
                Title = TITLE;
    
                _architectView = FindViewById<ArchitectView>(Resource.Id.architectView);
                var config = new StartupConfiguration(Constantes.WIKITUDE_LICENSE_KEY);
                _architectView.OnCreate(config);
                this._architectView.RegisterSensorAccuracyChangeListener(this);
                this.locationProvider = new Locations.LocationProvider(this, this);
            }
    protected override void OnPostCreate(Bundle savedInstanceState)
            {
                base.OnPostCreate(savedInstanceState);
                if (_architectView != null)
                {
                    _architectView.OnPostCreate();
                    try
                    {
                        _architectView.Load(worldURL);
                    }
                    catch (Exception e)
                    {
                        Log.Error("WIKITUDE_SAMPLE", e.ToString());
                    }
                }
            }
    
  • ThomasBurkhartThomasBurkhart DEMember ✭✭✭✭

    Where do you create worldSubFolder?

    Also why do you first save the zip-File to a File and then again read it to decode it? Why not directly decode it from your contentStream?

  • @ThomasBurkhart here's the rest of the class as you request it

    public FileManager()
            {
                if (CreateFolderStructureIfNotExist())
                {
                    ManageFiles();
                }
            }
    private bool CreateFolderStructureIfNotExist()
            {
                try
                {
                    IFolder localStorage = FileSystem.Current.LocalStorage;
                    appFolder = localStorage.CreateFolderAsync("GFI", CreationCollisionOption.OpenIfExists).Result;
                    modelSubFolder = appFolder.CreateFolderAsync("Models", CreationCollisionOption.OpenIfExists).Result;
                    worldSubFolder = appFolder.CreateFolderAsync("Worlds", CreationCollisionOption.OpenIfExists).Result;
                    Debug.WriteLine(Messages.FM_FOLDER_CREATION_SUCCESS_MESSAGE);
                    return true;
                } catch (Exception e) {
                    Debug.WriteLine(Messages.FM_FOLDER_CREATION_ERROR_MESSAGE + e.Message);
                    return false;
                }
            }
    

    Yes i could get rid of the part where i save the zip file and unzip it as you say. It's actually what i have attempted to do as I tried to ameliorate my draft since, works fine on Android but gets me an error on iOS "No data available for encoding 850" and i couldn't understand why was going on, so I went back to this messy method ManageFiles() that actually unzip the file correctly

  • ThomasBurkhartThomasBurkhart DEMember ✭✭✭✭

    Hmmm, why do you use .Result instead of await? could make problems.
    How does your filesystem look like after CreateFolderStructureIfNotExist?

    If you don't have it, https://qtadb.wordpress.com/ is great to inspect the android filesystem.

    What exactly happens when you try to acess the files?

Sign In or Register to comment.