- Home /
JSON file not written/read on application exit on android
Hi everyone in my game im trying to save a json file in the OnApplicationQuit() and load it in the start method. This works perfectly in the unity editor but, when I run the game on an android device the file isn't written or maybe not read. Is OnApplicationQuit() not called on android? Or do you have to read JSON differently on Android?
This is were I load the JSON file:
public static string filePath = Application.persistentDataPath + "/gamestats.json";
public static GameStats loadStats(GameObject[] defualtBlocks)
{
GameStats stats = new GameStats ();
stats.blockDatas = new BlockData[defualtBlocks.Length];
if (File.Exists (filePath))
{
string sourceJSON = File.ReadAllText (filePath);
stats = JsonUtility.FromJson<GameStats> (sourceJSON);
}
else
{
for(int i = 0; i < defualtBlocks.Length; i++)
{
stats.blockDatas [i] = defualtBlocks [i].GetComponent<Block> ().blockData;
}
}
return stats;
}
This is were I save the JSON File:
public static void saveGame(GameStats stats, GameObject[] allBlocks)
{
Debug.Log (allBlocks.Length);
for(int i = 0; i < allBlocks.Length; i++)
{
stats.blockDatas [i] = allBlocks [i].GetComponent<Block> ().blockData;
}
string gameStatsJSON = JsonUtility.ToJson (stats);
File.WriteAllText (filePath, gameStatsJSON);
}
And I call loadStats in the Start() method and saveGame() in the OnApplicationQuit() method.
Thanks for your help in advance!!!
Answer by $$anonymous$$ · Dec 29, 2016 at 01:48 AM
First check if file is created on your android device, and if it exits, does it have something, mb its empty.
On android you should create files in a different way. I use this method, it works for me. I thinks there is nothing too complicated to adapt this for you.
if (Application.platform == RuntimePlatform.Android)
{
if (file == "")
{
currentSetting = new Setting(new RandomStats(0.25, 0.5), new RandomStats(0.66, 1.0), new RandomStats(0.66, 1.0),1000,0);
string filepath = Application.persistentDataPath + "/" + "Settings" + ".json";
Debug.Log("Running system");
if (!File.Exists(filepath))
{
WWW loadDB = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "Settings" + ".json");
//TODO A coroutine instead of this dangerous cliff
while (!loadDB.isDone) { }
File.WriteAllBytes(filepath, loadDB.bytes);
}
File.WriteAllText(filepath, PrettyPrint(currentSetting));
}
else
{
currentSetting = JsonMapper.ToObject<Setting>(json_settingsData.ToJson());
}
}
Hey Le_Vailus thanks for the answer and im sure your way would have worked here but I put my save call somewhere else ins$$anonymous$$d of OnApplicationQuit() and it worked perfectly. For some reason OnApplicationQuit() isn't called on Android.