• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Crios · Aug 23, 2014 at 02:19 AM · xmlserializer

How to use XMLSerializer and Filestream on Android? (C#)

I've been using the example from this tutorial: Saving and Loading Data: XMLSerializer

to load data from an XML file saved in a "Resources" folder using the XML.Serialization library, and then create classes from the information in that file. Everything works fine when I test the code in the Unity Editor, but not when I build the game for Android.

From the example code, Filestream takes a string for the path as an argument, but since I have to include the "Assets" folder in the path (e.g. "Assets/Resources/file.xml") the game can't find the file when I build to Android (because Android doesn't see the "Assets" folder, only the "Resources" folder e.g. Resources/file) while it works fine in the Editor. Is there any way to get this to work on Android, or am I missing something about paths in Android?

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Aug 23, 2014 at 02:24 AM 0
Share

Try the Strea$$anonymous$$gAssets folder. See reference page for path setup.

http://docs.unity3d.com/$$anonymous$$anual/Strea$$anonymous$$gAssets.html

avatar image Crios · Aug 23, 2014 at 05:47 AM 0
Share

Ok, so from your link it looks like Application.strea$$anonymous$$gAssetsPath will return the path to the Strea$$anonymous$$gAssets folder that is in the Assets directory. But since this directory is located in a jar file, you have to unzip or use Unity's WWW to access it. How do I use WWW to get a path that I can then use Filestream to read from? Once again, when I run the game in the editor it is able to find the path that points to my resources, but not when I build it for Android. The relevant code I am using is the following:

 WWW www = new WWW (Application.strea$$anonymous$$gAssetsPath + "/Cards.xml");
 AllCards = Bucket.Load (www.url);
     
 public static Bucket Load(string path) //Load data from X$$anonymous$$L file
 {
      var serializer = new XmlSerializer(typeof(Bucket));
      using (var stream = new FileStream(path, File$$anonymous$$ode.Open))
      {
         return serializer.Deserialize(stream) as Bucket;
      }
 }

Running the game in the editor reads the path from "www.url" that points to the xml file, which contains paths to assets in the "Resources" directory. Android is still not able to read this file. Are there any working examples of something similar to this?

2 Replies

· Add your reply
  • Sort: 
avatar image
3

Answer by Crios · Aug 24, 2014 at 12:12 AM

I managed to get my game working on Android, using the StreamingAssets hint that robertbu provided (thanks), although getting it to work was a bit more involved and hacky than I'd like it to be.

I basically had to use the WWW api to begin downloading the file from my Assets/StreamingAssets folder in a Coroutine, wait for the file to finish downloading, then copy the downloaded file to the Application.persistentDataPath directory. I was then able to read the copied file using Filestream and use XMLSerializer on it. I hate how I have to download a file already included in the game in order to read from it, but I guess that's just how it is.

Here's the relevant code for those who are interested:

 using UnityEngine;
 using System.Collections;
 using System.IO;
 
 public class readTheFile : MonoBehavior {
     
     WWW www;
     
     void Start () {
         StartCoroutine("Downloader");
     }
     
     void Update () {
         
     }
 }
 
 IEnumerator Downloader ()
         {
                 #if UNITY_ANDROID && !UNITY_EDITOR //For running in Android
                 www = new WWW ("jar:file://" + Application.dataPath + "!/assets/Cards.xml");
                 #endif
                 #if UNITY_EDITOR // For running in Unity
                 www = new WWW ("file://" + Application.streamingAssetsPath + "/Cards.xml");
                 #endif
                 yield return www; //will wait until the download finishes
                 if (www.isDone == true) {
                     File.WriteAllBytes (Application.persistentDataPath + "/Cards.xml", www.bytes);
                 }        
         }

Now I can close my 50 tabs I have open about this. Or if anyone has a better answer i'd like to see it.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Aug 24, 2014 at 12:47 AM 0
Share

I agree that seems really hacky. If you have to go this route, then it would be easier to include the file as a TextAsset. Then you would not need the WWW loading logic. In addition, I believe on iOS I can setup my XCode project so that files are included and are at Application.persistentDataPath. I don't know if anything similar exists on Android, or what kind of format the file would need to be in to be read.

avatar image silentassassin47 · Jun 23, 2015 at 02:58 PM 0
Share

Nice, was stuck at this for 2 days until I found this. You should add more tags to this question as it was quite difficult to find this although it gives a great answer to what I guess would be a common problem!

avatar image
0

Answer by Ziron999 · Oct 15, 2017 at 07:05 PM

Updated to be more bug free for those interested in more dynamic solutions. Google ftw?

 using UnityEngine;
 using System.Collections;
 using System.IO;
 
 public class XMLSaveLoad : MonoBehaviour
 {
     WWW www;
 
     void Start()
     {
         StartCoroutine(SaveXML("CharacterData", false));
     }
 
     IEnumerator SaveXML(string SaveXML, bool save)
     {
         //first time run
         if (!Directory.Exists(Application.dataPath + "/XMLData/"))
             Directory.CreateDirectory(Application.dataPath + "/XMLData/");
         //create file if it's missing
         if (!File.Exists(Application.dataPath + "/XMLData/" + SaveXML + ".xml"))
             File.Create(Application.dataPath + "/XMLData/" + SaveXML + ".xml");
 
 #if UNITY_ANDROID && !UNITY_EDITOR //For running in Android
          www = new WWW ("jar:file://" + Application.dataPath + "!/assets/XMLData/" + SaveXML + ".xml");
 #endif
 #if UNITY_EDITOR // For running in Unity
         www = new WWW("file://" + Application.dataPath + "/XMLData/" + SaveXML + ".xml");
 #endif
         yield return www; //will wait until the download finishes
         if (www.isDone == true)
         {
             if (save)
                 File.WriteAllBytes(Application.dataPath + "/XMLData/" + SaveXML + ".xml", www.bytes);
         }
     }
 }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

XML Serializable "if" 1 Answer

[SOLVED] XML Deserialization of a single XML file into multiple objects 2 Answers

[Possible Bug] Unity3d XmlSerializer ShouldSerialize not working? 2 Answers

XML parsing c# in unity 1 Answer

XMLSerializer does not save unless I open Monodevelop? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges