Saving a txt file to the Oculus Go Internal Storage - android

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.

Related

Reading and existing file in Xamarin withC#

This code works:
string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "File.text");
File.ReadAllText(file);
Pretty straight-forward, but when I display the variable "file" using a Pizel 5 simulator I get a weird path: /data/user/0/com.companyname.aikidohours/files/.local/share/File.text. I can write new data to the file and read from it. but I now want to read from an existing file and I can't figure out where to put the file. Can someone tell where to put a text file full of basic information that I need to read from in Xamarin for adnroid?
Thanks
Todd
If you want to deploy that file with your application, you can add it to the 'Assets' folder inside your_project_name.Android project.
WARNING!!! File put in this folder are READONLY!
In case this is ok for you,this is the code to access the file:
using Xamarin.Essentials;
using (var reader = new StreamReader(await FileSystem.OpenAppPackageFileAsync("file_path")))
{
string content = reader.ReadToEnd();
}

How can I make my Android app read and write a .txt file?

I'm using Xamarin, C# and Monogame and I'm taking a fully-working Desktop game and porting it over to Android.
My problem is that I have this "Content folder" that you would always use in the Desktop version of the app. But I cannot access it or any other folder through the code directly using Android.
basicShader = new Effect(game1.GraphicsDevice,System.IO.File.ReadAllBytes("Content/TextureShader.mgfxo"));
This works just fine in the Desktop app but throws System.IO.DirectoryNotFoundException:'Could not find a part of the path "/Content/TextureShader.mgfxo".' on Android.
I'd like to mention that I already had the code and the project working perfectly when it was a desktop program. I also have a private class-level variable string[] list_of_files and in the constructor, I had the line list_of_files = Directory.GetFiles("./Content","*.txt");
This is for saving and loading player data. It may have been rudimentary but I had a fully functioning program that saved and loaded data on my computer. I am transitioning this program to be an Android app and this is the only part of the project that isn't working. When I run the code as it was originally written, I get "System.IO.DirectoryNotFoundException: 'Could not find a part of the path '/Content'.' ".
I've tried playing around with trying to read the contents of different folders.
I've messed around with different paths, including the Resources folder instead.
I added <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> to my manifest.
I know that I'm trying to access internal storage, not external, so I also tried <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" /> just to see if that might work.
Nothing works.
In another stack overflow post, a guy commented:
For the people who are facing NullPointerException - you are trying to access the files in the app's internal storage which are private sorry you can't do that. –
coderpc
Jun 23, 2017 at 16:00
I cannot imagine why this would be true. Why would a programmer not be able to write a program that can access it's own internal storage? That makes no sense to me. Obviously my app needs to be able to read and write it's own internal storage! And if this is true, then how else can I save persistent data on my phone? I don't want a database or a shared thingamabobber that uses key-value pairs, I have a self-made system that works as a text file and I want to continue to use it. I refuse to believe that an Android app can't keep track of a simple .txt file in one of it's own folders, that's just too hard for me to imagine. It can't be true.
I wanted to ask the commenter about his comment but Stack Overflow wouldn't let me because I don't have over 50xp.
Just like CommonsWare sayed, you can use the Intent.ActionOpenDocument to get the uri of the file. Such as
static readonly int READ_REQUEST_CODE = 1337;
Intent intent = new Intent(Intent.ActionOpenDocument);
intent.AddCategory(Intent.CategoryOpenable);
intent.SetType("*/*");
StartActivityForResult(intent, READ_REQUEST_CODE);
And override the OnActivityResult method:
if (requestCode == READ_REQUEST_CODE && resultCode == Result.Ok)
{
// The document selected by the user won't be returned in the intent.
// Instead, a URI to that document will be contained in the return intent
// provided to this method as a parameter. Pull that uri using "resultData.getData()"
if (data != null)
{
Android.Net.Uri uri = data.Data;
DocumentFile documentFile = DocumentFile.FromSingleUri(this.ApplicationContext,uri);
// Then you can operate the file with input and output stream
}
}
More information please check the simple on the github:
https://github.com/xamarin/monodroid-samples/blob/main/StorageClient/StorageClientFragment.cs
In addition, if you can ensure the file's path. You can use the StreamWriter and the StreamReader to write and read the file. Such as:
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(content);
}
Furthermore, you can try to create the content folder and the txt file in the Android with the following code.
var filename1 = Android.App.Application.Context.GetExternalFilesDir(System.DateTime.Now.ToString("Content")).AbsolutePath;
var filename = System.IO.Path.Combine(filename1, "xxx.txt");
using (System.IO.FileStream os = new System.IO.FileStream(filename, System.IO.FileMode.Create))
{
}
The folder and the files created by this way belongs to the app and you can access it easily.
You can read the official document about the storage in the Android.
Link : https://developer.android.com/training/data-storage/shared/documents-files

Why does the Android version contain robot artifacts?

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?

Finding a saved file from my app in the Android file system

I've created a new file using XmlSerializer and StreamWriter to persist data. From the test I did with my app, storing and restoring data using this method is working. Just for curiosity, I've tried to find the file created in the Android File System, without success. I've tried to find it with an Android app (ES File Explorer) and a desktop app (on Mac, Android File Transfer). In both case, I was unable to find the created file.
XmlSerializer xmlSerializer = new XmlSerializer (typeof(GAData));
TextWriter writer = new StreamWriter (FilePath);
xmlSerializer.Serialize (writer, this);
writer.Close ();
Console.WriteLine ("Data saved");
Where FilePath is define here :
// Determining the path
var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
FilePath = Path.Combine (documentsPath, "AppData.txt");
Console.WriteLine (Path.GetFullPath (FilePath));
The last Console.WriteLine is logging : /data/data/com.domain.myapp/files/AppData.txt
The exact same code is working like a charm on iOS, and I can see the file in the File System using an app on my Mac. Why can I find it in the Android File System? Or, where is it saved if it's somewhere else?
/data/data/com.domain.myapp/files/AppData.txt
That is private internal memory. Private as only your app has access.
Your app can reach it using getFilesDir().
Other app like ES File Explorer have no access.
You should be using FilesDir from the ContextWrapper
Path.Combine(FilesDir.Path , "MyFile.text");
Example, copies a file that is in the assets folder to the local file system
if (!File.Exists(Path.Combine(FilesDir.Path , "myFile.Text")))
{
using (var asset = Assets.Open("TextToCopyTo.txt"))
{
using (var dest = File.Create(Path.Combine(FilesDir.Path , "MyFile.text")))
{
asset.CopyTo(dest);
}
}
}

How to Write float data into Text file in Android Working with Unity and C#

im trying to Write the data Stored in a float variable into a text file.
it works well in PC using Streamwriter
using (System.IO.StreamWriter file = new System.IO.StreamWriter();
but not on Android.
please tell me what is the way to Write it into a text file .
all i need is a similar way to write the above which works on android as well.
*collecting data from leap motion
*each frame data has to be written into Text file.
There's lots of good resources in the Unity documentation/forums for this. Look up 'Unity File I/O' and you will find links to articles that are helpful.
Here's some sample code to help you with your specific problem:
public void WriteToFile()
{
string FILE_PATH = Application.persistentDataPath + "/MYFILENAME.txt";
if (File.Exists(FILE_PATH))
{
Debug.Log(FILE_PATH + " already exists.");
return;
}
StreamWriter sr = System.IO.File.CreateText(FILE_PATH);
sr.WriteLine ("This is line 1 to be written in file.");
sr.WriteLine ("This is line 2.");
sr.Close();
}
I hope that helps!

Categories

Resources