For a robot simulation I use a csv file with data. I read data as follows:
string dbPath = ""; string realPath; // Android string oriPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Data.csv");
// Android only use WWW to read file
WWW reader = new WWW(oriPath);
while (!reader.isDone) { }
realPath = Application.persistentDataPath + "/db";
System.IO.File.WriteAllBytes(realPath, reader.bytes);
dbPath = realPath;
using (StreamReader sr = new StreamReader(dbPath))
{...}
In the Unity Editor version the simulation works as expected but on Android the arm ofthe robot moves in a strange way as you can see in the videos. I compared the two db files (on the Windows and Android paths) and the content is identical. What could be the reason of the strange movemenz?
Editor https://streamable.com/7z4qob Android https://streamable.com/rv4nm2
Thank you!
To get StreamingAssets WWW you need to add prefix jar:file:///
To get Application.persistentDataPath you need to add prefix file:///
If files are identical then problem is not in getFile code, why did you provide it?
Related
I'm building an Oculus Go app with Unity but I can't figure out how to save a txt file to the Oculus Storage. I have read everything I've found online about it, including using solutions proposed on this website here and here.
I'm trying to create a text file that records which button from a toggle group was selected by the user.
When I build the same thing for PC the code works but I can't find the files inside the Oculus Go. I have edited the OVR android manifest and have a very simple script made from following a couple of tutorials.
Any help would be appreciated, thank you!
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using System.IO;
public class SubmitandWriteButtonOVR : MonoBehaviour
{
//GameObject
public ToggleGroup toggleGroup;
public void onClick()
{
string selectedLabel = toggleGroup.ActiveToggles()
.First().GetComponentsInChildren<Text>()
.First(t => t.name == "Label").text;
//Path of the file
string path = Application.persistentDataPath + "/Answers.txt";
//Create file if it doesn't exist
if (!File.Exists(path))
{
File.WriteAllText(path, "Answers");
}
//Content of the file Get the label in activated toggles
string content = "Selected Answers: \n" + System.DateTime.Now + "\n" + selectedLabel;
//Add some text
File.AppendAllText(path, content);
}
}
There are several things that could be the error here:
1) Try to set your rootpath like this
rootPath = Application.persistentDataPath.Substring(0, Application.persistentDataPath.IndexOf("Android", StringComparison.Ordinal));
2) Even if your rootpath is set correctly the file might not show up. Try putting Answers.txt manually onto your GO, write something into Answers.txt from inside your App, restart your go and check again in Explorer if it wrote to your file. I read that it has to do with the Android file system not realizing that this file has been created/updated, so it doesn't show.
3) Make sure you have write permissions on externalSD via PlayerSettings
Here is my solution for a StreamWriter on Android:
private void WriteLogToFile()
{
Debug.Log("Starting to Write Logfile");
string path = Path.Combine(rootPath, "Logs.txt");
StreamWriter writer = new StreamWriter(path, true);
writer.WriteLine("TEST");
writer.Close();
Debug.Log("Logging Done");
}
Try if that, in combination with all of the tips above, helps you to reach your goal and let me know.
I have some level definitions in xml format (with .txt extension) inside (without any subfolders) my project's rescources folder
I for more scalability, I have a plain text file naming all these level definition XMLs
I read that file using
TextAsset WorldList = (TextAsset)Resources.Load("WorldList");
And then I load the needed world:
TextAsset TA = (TextAsset)Resources.Load(/*"LevelDefs/" +*/ Worlds[worldToload]);
xps.parseXml(TA.text);
loadLevel(levelToLoad);
(you see that I have moved these rescources out of subfolder to reduce the chance of them not loading)
worldToload here is the index number of that world
program works fine on windows but nothing loads on my android test device.
I seem to have problems debugging on device so I only guess something went wrong in loading phase.
any suggestions?
From Unity Documentation:
Most assets in Unity are combined into the project when it is built.
However, it is sometimes useful to place files into the normal
filesystem on the target machine to make them accessible via a
pathname. An example of this is the deployment of a movie file on iOS
devices; the original movie file must be available from a location in
the filesystem to be played by the PlayMovie function.
Any files placed in a folder called StreamingAssets in a Unity project
will be copied verbatim to a particular folder on the target machine.
You can retrieve the folder using the Application.streamingAssetsPath
property. It’s always best to use Application.streamingAssetsPath to
get the location of the StreamingAssets folder, it will always point
to the correct location on the platform where the application is
running.
So below snippet should work:
// Put your file to "YOUR_UNITY_PROJ/Assets/StreamingAssets"
// example: "YOUR_UNITY_PROJ/Assets/StreamingAssets/Your.xml"
if (Application.platform == RuntimePlatform.Android)
{
// Android
string oriPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Your.xml");
// Android only use WWW to read file
WWW reader = new WWW(oriPath);
while ( ! reader.isDone) {}
realPath = Application.persistentDataPath + "/Your"; // no extension ".xml"
var contents = System.IO.File.ReadAll(realPath);
}
else // e.g. iOS
{
dbPath = System.IO.Path.Combine(Application.streamingAssetsPath, "Your.xml");
}
Thanks to David I have resolved this problem.
for more precision I add some small details:
1-As David points out in his answer (and as stated in unity documentations), we should use StreamingAssets if we want to have the same folder structure. One should use Application.streamingAssetsPathto retrieve the path.
However, files are still in the apk package in android's case, so they should be accessed using unity android's www class.
a good practice here is to create a method to read the file (even mandatory if you are going to read more than one file)
here is one such method:
private IEnumerator LoadDataFromResources(string v)
{
WWW fileInfo = new WWW(v);
yield return fileInfo;
if (string.IsNullOrEmpty(fileInfo.error))
{
fileContents = fileInfo.text;
}
else
fileContents = fileInfo.error;
}
This is a coroutine, and to use it we need to call it using
yield return StartCoroutine(LoadDataFromResources(path + "/fileName.ext"));
Yet another remark: we can not write into this file or modify it as it's still inside the apk package.
I am making a report in Unity3D with iTextSharp. When I start app from Unity it creates PDF and works perfect. But when I build App on Android device, I have a problem with creating font. Here is what I do:
BaseFont bf = BaseFont.CreateFont(System.IO.Path.Combine(Application.streamingAssetsPath, "ADOBEARABIC-BOLD_0.OTF"), BaseFont.IDENTITY_H, false);
As I have seen, the first parameter for font creation is the path to the font. My font is in /Assets/StreamingAssets/ folder.
When I try to load it with WWW class, it can find it, but when I give just the path to the creator it won't work.
Any idea what should I do? Or is there any other way to create a font that supports Arabic characters?
EDIT:
Ok, I have somehow managed to get to the font. First I copy font from Assets to the root of the APP:
IEnumerator CopyFiles()
{
string fromPath = Application.streamingAssetsPath + "/";
string toPath = Application.persistentDataPath + "/";
string filesNamesToCopy = "ADOBEARABIC-BOLD_0.OTF";
WWW www1 = new WWW(fromPath + filesNamesToCopy);
yield return www1;
File.WriteAllBytes(toPath + filesNamesToCopy , www1.bytes);
}
And then I make BaseFont:
BaseFont bf = BaseFont.CreateFont(System.IO.Path.Combine(Application.persistentDataPath, "ADOBEARABIC-BOLD_0.OTF"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Now I get new error when try to build on Android device:
ArgumentException: Encoding name 'windows-1252' not supported
Parameter: name
You have to put some DLL files to project folder. Which one depends what encoding you have to use.
http://answers.unity3d.com/questions/42955/codepage-1252-not-supported-works-in-editor-but-no.html
I am trying to upload a file inside a repository on Alfresco.
I am using the Alfresco Mobile SDK for Android that is well documented and easy to use.
The problem is that I didn't find how to create an object ContentFile from a file (the one that I want to upload), in order to use the method:
public Document createDocument(Folder folder, String nameFile,
Map<String,Serializable> properties, ContentFile contentFile)
(this method works great, I am able to create a file without content).
I am pretty sure it is not big deal but I am looking around and don'y manage to find what I need.
Thanks in advance for your help.
ServiceRegistry serviceRegistry = Login.session.getServiceRegistry();
DocumentFolderService documentFolderService =
serviceRegistry.getDocumentFolderService();
Folder folder = (Folder)
documentFolderService.getNodeByIdentifier(repository.getIdentifier());
Map<String,Serializable> properties = new HashMap<String,Serializable>();
// here I would like to take the content from the fileFrom:
ContentFile contentFile = null;
// fileFrom is a File object:
String nameFile = fileFrom.getName();
documentFolderService.createDocument(folder, nameFile, properties, contentFile);
You should use the ContentFileImpl class:
//...
String location = "..."; // wherever you have to point to
ContentFile contentFile = new ContentFileImpl(new File(location));
//...
How to display .mht(MHTML) file on android webview. I tried to open the .mht file on default android browser but that didn't open but i am able to open same on opera mobile browser. So i tried with MHTUnpack java library. I didn't succeed in that.
Here's a link!
Please if anybody has used this MHTUnpack let me how can i use that in android. And also let me know if there is any other library.
Thanks
Found this unknown google project which appears to be working.
This utility decodes the mhtml file and save it on given path(internal or external). After saving it returns the html file path which could be loaded into webview.
Try it.
After overcoming frustration about WebView.saveWebArchive() format change in Android 4.4, I tried the "unknown google project" Chitranshu Asthana mentioned in his answer, but code provided there is slow (~10s for 1MB *.mht file with a dozen of pictures) and doesn't handle attached file names correctly.
MHT Unpack library combined with Java Mail for Android (not the one provided by Oracle) worked perfectly for me.
EDIT: Fixed the link to MHT Unpack library. Also, here's usage example:
// contentPath - path to input .mht file
public static String unpackMht(String contentPath) throws IOException {
// dstPath - path where file will be unpacked
String dstPath = openTempDir(null) + File.separator;
String indexFileName = dstPath + new File(contentPath).getName();
try {
Collection<Attachment> attachments = MHTUnpack.unpack(new File(contentPath));
for (Attachment attachment : attachments) {
String filename = attachment.getFileName();
String path = filename == null ? indexFileName : dstPath + filename;
File newFile = new File(path);
if (newFile.exists()) {
newFile.delete();
}
attachment.saveFile(path);
}
return indexFileName;
} catch (MessagingException e) {
throw new IOException(e);
}
}