Loading a JSON file to android device in Unity3D - android

I need to load my json file in my device. It is working perfectly fine in Unity Editor but when I transferred it to my device, json isn't there. Currently using this code for adding data in my json file:
TextAsset file = Resources.Load("Products") as TextAsset;
string jsonString = file.ToString ();
Debug.Log (jsonString);
if (jsonString != null)
{
jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);
data.products.Add(product);
Debug.Log(data.products[1].code);
jsonString = JsonUtility.ToJson(data);
Debug.Log(jsonString);
}
And this for retrieving:
TextAsset file = Resources.Load("Products") as TextAsset;
string json = file.ToString ();
//string path = Application.streamingAssetsPath + "/Products.json";
string path = Application.persistentDataPath + "/Resources/Products.json";
string jsonString = File.ReadAllText (path);
jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);
It can be use in Unity editor but not in my android device. What seems to be the problem? Very big thanks

As explained here, you can't read file from the Resources folder with anything other than Resources.Load. You must use Resources.Load to read anything placed in the Resources folder.
It doesn't matter if it works in the Editor or not the code below that reads from the Resources folder should not work in any build:
string path = Application.persistentDataPath + "/Resources/Products.json";
string jsonString = File.ReadAllText (path);
You don't seem to understand when the Resources folder should be used. This is used to store files that does not need to be changed during run-time. For example, your textures, sound, video files and prefabs. These are not meant to be modified during run-time Also, using it to store default value for a text file is fine.
What need to do is to read the file with Resources.Load("Products") then store it in a string. After you modify it, save to another directory with
Save:
string tempPath = Path.Combine(Application.persistentDataPath + "/data/", dataFileName + ".txt");
File.WriteAllBytes(tempPath, modifiedJson);.
Load:
string tempPath = Path.Combine(Application.persistentDataPath + "/data/", dataFileName + ".txt");
jsonByte = File.ReadAllBytes(tempPath);
I made a generic class in another question, to handle that easily so you that you don't even need to use the Resources folder or read the file manually. It handles all the errors too.
From your question, your data is stored in jsonParser class. You should rename that class to actually reflect what you are storing such as PlayerInfo or ProductInfo.
Grab the DataSaver class from here. With your current jsonParser data, you can save and load with the code sample below:
Save:
jsonParser products = new jsonParser();
DataSaver.saveData(products, "Products");
Load:
jsonParser loadedProducts = DataSaver.loadData<jsonParser>("Products");
Delete:
DataSaver.deleteData("Products");
Very easy. That should work on any Platform.

Another simple variant, if you ONLY want to get JSON's text from Resourse:
1.⠀You have file in Resource/Jsons folder, example "simple.json"
2.⠀You use this code:
TextAsset file = Resources.Load("Jsons/simple") as TextAsset;
string json = file.text;
3. Now, you have JSON in string variable! 4. Thats all! Glory to Robots!

Related

To create xml file inside the direct of the project of my mobile XAMARIN

I want to create an xml file inside the directory of my project, so also create a command where I can edit and subscribe it. How can I increment this in my project in a simple and basic way?
XDocument rss = System.Xml.Linq.XDocument.Load(url);
rss.Save(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "/inicio.xml"));
var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var filename = Path.Combine(path, "inicio.xml");
rss.Save(filename);
using (StreamReader streamReader = new StreamReader(assets.Open(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + #"/rss.xml")))
{
xmlString = streamReader.ReadToEnd();
}
This way of error

JSON file works on Unity Editor but not on Android device

Currently using LitJson in my development. Json is working perfectly fine in Unity Editor but not in android device. Tried various ways in loading the json file but nothing worked. Here is my latest code:
string path = Application.persistentDataPath + "/Products.json";
string jsonString = File.ReadAllText (path);
if(File.Exists(path)) {
jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);
data.products.Add (product);
Debug.Log (data.products [1].code);
string jsonString2 = JsonUtility.ToJson (data);
Debug.Log (jsonString2);
File.WriteAllText (path, jsonString2.ToString());
} else{
File.WriteAllText (path, jsonString);
}
Big thanks!
I suggest you using Resources loading instead of IO since the least is something platform specific.
So if you create a "Resources" folder in the root of Assets folder of your project and put your json file in it so it looks like this "/Assets/Resources/Products.json"
and change you code to this
string jsonString = Resources.Load<string>("Products.json");
if (jsonString != null)
{
jsonParser data = JsonUtility.FromJson<jsonParser>(jsonString);
data.products.Add(product);
Debug.Log(data.products[1].code);
jsonString = JsonUtility.ToJson(data);
Debug.Log(jsonString);
}
using (FileStream fs = new FileStream("Products.json", FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(fs))
{
writer.Write(jsonString);
}
}
UnityEditor.AssetDatabase.Refresh();
everything should work fine.

Can't read lines from file by using StreamReader on Unity3d (Android)

I need to read a text stream by using StreamReader from file on android platform. File is about 100k lines, so even editor is getting stuck if i try to load it all to TextAsset or if i use WWW.
I simply need to read that file line by line without loading it all to a string. Then i'll do a tree generation from the lines that i got from the file. (But probably that part doesn't matter, i just need help on file reading part.)
I'm giving the code that i wrote down below. It works perfectly on editor, but fails on android.
I would be glad if anyone tell me, what am i missing.
(ps. english is not my native and this is my first question on the site. so sorry for the any mistakes that i may have done.)
private bool Load(string fileName)
{
try
{
string line;
string path = Application.streamingAssetsPath +"/";
StreamReader theReader = new StreamReader(path + fileName +".txt", Encoding.UTF8);
using (theReader)
{
{
line = theReader.ReadLine();
linesRead++;
if (line != null)
{
tree.AddWord(line);
}
}
while (line != null);
theReader.Close();
return true;
}
}
catch (IOException e)
{
Debug.Log("{0}\n" + e.Message);
exception = e.Message;
return false;
}
}
You can't use Application.streamingAssetsPath as a path on Android because streaming assets are stored within the JAR file with the application.
From http://docs.unity3d.com/Manual/StreamingAssets.html:
Note that on Android, the files are contained within a compressed .jar
file (which is essentially the same format as standard zip-compressed
files). This means that if you do not use Unity’s WWW class to
retrieve the file then you will need to use additional software to see
inside the .jar archive and obtain the file.
Use WWW like this in a coroutine:
WWW data = new WWW(Application.streamingAssetsPath + "/" + fileName);
yield return data;
if(string.IsNullOrEmpty(data.error))
{
content = data.text;
}
Or, if you really want to keep it simple (and your file is only a few 100k, stick it in a resource folder:
TextAsset txt = (TextAsset)Resources.Load(fileName, typeof(TextAsset));
string content = txt.text;

How to load different html file in different language Android environment?

I have some different language html file for different language environment, and all of those html files contain images. Now I want to show suitable html files with WebView adapt to current language of Android. How can I do that? Thanks.
You can give special names for non-English files like file-de.html for German and then use the following code:
private static String getFileName() {
Configuration config = getResources().getConfiguration();
InputStream stream = null;
try {
String name = "file-" + config.locale.getLanguage() + ".html";
stream = getAssets().open(name);
return name;
} catch (IOException exception) {
return "file.html";
} finally {
if (stream != null) {
stream.close();
}
}
}
You might use "string values" to get Android language dependent HTML file names without using any additional java code and just using getString(). Here's an example for 2 languages:
In file values/strings.xml:
<string name="html_help_basepage">en_help.html</string>
In file de/strings.xml:
<string name="html_help_basepage">some_german_help.html</string>
And so on...
For your Java code (loading from local file in asset folder as in question)
helpView = (WebView) findViewById(R.id.wv_help);
String adaptedToLanguage = getString(R.string.html_help_basepage)
helpView.loadUrl("file:///android_asset/" + adaptedToLanguage);
No additional Java code is needed. I hope this is helpful and answers the question.
Added a new answer, which should be more precise by providing an example.

how to return a list from servlet to my android application

There are some pdf files in my d drive.In my android application I have to return the list of files from a servlet to my activity class,but through my codes it is returning the name of all files as a string.But i need each name separetly.How to do that,
You a using HTTP to pass data from your servlet to your Android application. HTTP doesn't care about the content of the response, so there is no standard way of defining the structure of the data you are passing. You are pretty much free to do as you please.
One option therefore would be to put your filenames into a comma-separated list in the servlet. In your Android application you chop the String apart into an array of Strings each representing one file name:
String[] filenames;
filenames = responseString.split(",");
That's the easy way. You could also create XML from your filenames in your servlet, and parse the XML in your Android application. That would look nicer, but it is more work.
Use JSONObject
JSONObject jsEmployeeObj = new JSONObject();
JSONArray empArray = new JSONArray();
while (condition) {
JSONObject jsObject = new JSONObject();
jsObject.accumulate("name", res.getString("name"));
empArray.add(jsObject);
}
if ((empArray != null) && (empArray.size() > 0)) {
jsEmployeeObj.accumulate("employeeList", empArray);
} else {
jsEmployeeObj.accumulate("employeeList", "empty");
}
String output = jsEmployeeObj.toString();
return the string ... u can parse JSON in android

Categories

Resources