I've got the sqlite db working in the editor just fine. However when using it in Android, I get an error saying data path not found.
I believe I have the needed libsqlite.so files in the correct plugins/ android folder and the other DLLs that the editor looks for.
Here is my code:
string filepath = Application.dataPath + "/" + "Players.db"; //.db
if(!File.Exists(filepath))
{
// if it doesn't ->
// open StreamingAssets directory and load the db ->
try {
WWW loadDB = new WWW ("jar:file://" + Application.persistentDataPath + "!/Assets/" + "StreamingAssets/Players.db"); // .db this is the path to your StreamingAssets in android
while (!loadDB.isDone) {
} // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
// then save to Application.persistentDataPath
File.WriteAllBytes (filepath, loadDB.bytes);
} catch (Exception ex) {
GameObject.Find ("Advice").GetComponent<Text> ().text = ex.Message;
}
}
You are using Application.DataPath to save files. In editor mode it refers to Assets folder but in android build it refers to APK package which is a compressed file and you have no access to it. So use Application.persistentDataPath instead.
string filepath = Application.persistentDataPath + "/" + "Players.db"; //.db
Related
I am using this code, but I am not able to access the expansion file content, i want to show gif image from expansion file, how can i do?
String packageName = getPackageName();
File root = Environment.getExternalStorageDirectory();
File expPath = new File(root.toString() + "/Android/obb/" + packageName);
try {
if (expPath.exists()) {
String strMainPath = expPath
+ File.separator
+ "main."
+ getPackageManager().getPackageInfo(
getPackageName(), 0).versionCode + "."
+ packageName + ".obb";
File f = new File(strMainPath);
if (f.exists()) {
Log.e("Path ", "=====>Exists");
} else {
Log.e("Path ", "=====> Not Exists");
}
ZipResourceFile zip = new ZipResourceFile(strMainPath);
InputStream iStream = zip.getInputStream("stage1_popup.gif");
BitmapFactory.Options option = new BitmapFactory.Options();
option.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeStream(iStream, null, option);
Glide.with(SampleDownloaderActivity.this).load(bitmap).into(image);
}
} catch (Exception e) {
}
http://prntscr.com/kp25qz
The Play APK expansions files library is completely open source, and you can see the sourcecode for ZipResourceFile here.
It looks like stage1_popup.gif is not in your obb file. To investigate it, why not use adb pull to get the file off your device and see what it actually contains. Or download the source code and attach to your IDE so you can step into the getInputStream() call and see where it is going wrong.
As mentioned in this answer, ZipResourceFile isn't able to deal with too much little files and neither is ZipFile. So try to divide your files in more directories.
Also, it's quite possible that there isn't any file with the name, stage1_popup.gif.
Alternatively, you can get all Entries via zipResourceFile.getAllEntries() and findout if the file exists.
How to add files and folders to the apk file when building it in unity.
What I need is to have some files and a folder to be present in the parent directory of the application ( android/data/com.company.product/files) after installing it on Android.
This is my code for copying files from streaming assets into android persist path:
using System.IO;
using UnityEngine;
public static class FileManager
{
public static string RereadFile(string fileName)
{ //copies and unpacks file from apk to persistentDataPath where it can be accessed
string destinationPath = Path.Combine(Application.persistentDataPath, fileName);
#if UNITY_EDITOR
string sourcePath = Path.Combine(Application.streamingAssetsPath, fileName);
#else
string sourcePath = "jar:file://" + Application.dataPath + "!/assets/" + fileName;
#endif
//UnityEngine.Debug.Log(string.Format("{0}-{1}-{2}-{3}", sourcePath, File.GetLastWriteTimeUtc(sourcePath), File.GetLastWriteTimeUtc(destinationPath)));
//copy whatsoever
//if DB does not exist in persistent data folder (folder "Documents" on iOS) or source DB is newer then copy it
//if (!File.Exists(destinationPath) || (File.GetLastWriteTimeUtc(sourcePath) > File.GetLastWriteTimeUtc(destinationPath)))
{
if (sourcePath.Contains("://"))
{
// Android
WWW www = new WWW(sourcePath);
while (!www.isDone) {; } // Wait for download to complete - not pretty at all but easy hack for now
if (string.IsNullOrEmpty(www.error))
{
File.WriteAllBytes(destinationPath, www.bytes);
}
else
{
Debug.Log("ERROR: the file DB named " + fileName + " doesn't exist in the StreamingAssets Folder, please copy it there.");
}
}
else
{
// Mac, Windows, Iphone
//validate the existens of the DB in the original folder (folder "streamingAssets")
if (File.Exists(sourcePath))
{
//copy file - alle systems except Android
File.Copy(sourcePath, destinationPath, true);
}
else
{
Debug.Log("ERROR: the file DB named " + fileName + " doesn't exist in the StreamingAssets Folder, please copy it there.");
}
}
}
StreamReader reader = new StreamReader(destinationPath);
var jsonString = reader.ReadToEnd();
reader.Close();
return jsonString;
}
}
I hope it helps.
I am downloading a pdf file from server and saving it on sd card without extension (for security purpose so that normal user can't open that file from file manager).For e.g.- I am downloading abc.pdf and saving it on sd card with abc on below path
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "files");
And later I want to view that file by adding extension.
So when I am accessing that file from code by using below code then its gives error file does't exist..
String s=Environment.getExternalStorageDirectory() + "/files/" + "abc";
File pdfFile = new File(s+".pdf");
So how can I save file in sd card without extension and later open that file with extension.
Workaround for your problem is to rename your saved pdf file without extension to filename with .pdf extension & after completing/accessing view or read operation on your new pdf extension file again you can rename it to file without extension
Example Usage:
String currentFileName = Environment.getExternalStorageDirectory() + File.separator
+ "files" + File.separator + "abc";
String renamedFilename = currentFileName + ".pdf";
boolean isRenamed = renameFile(currentFileName, renamedFilename);
Log.d("isRenamed: ", "" + isRenamed);
if(isRenamed {
//perform your operation
}
Again rename the file if not in use (here exchange renameFile() parameters):
boolean renameAfterOperation = renameFile(renamedFilename, currentFileName);
Log.d("renameAfterOperation : ", "" + renameAfterOperation );
And here is renameFile(currentFilePath, renamedFilePath):
public boolean renameFile(String currentFilePath, String renamedFilePath){
File currentFile = new File(currentFilePath);
File newFile = new File(renamedFilePath);
boolean isrenamed = currentFile.renameTo(newFile);
return isrenamed;
}
In this way whenever you want to perform operation on saved file first rename it to .pdf & whenever it's not in use, again rename it without extension. Let me know if this works for you..
i can read and write file with this method for storing game progres.
filePath = Application.dataPath + "/";
filenam= "SavedGame";
extension = ".txt";
Lettura ----------------
var FRead = new File.OpenText(filePath + fileNam + extension);
for (var i : int= 0; i<N; i++) {
FRead.ReadLine();
}
Scrittura--------------------
var FWrite: StreamWriter = new StreamWriter(filePath + filenam + extension);
FWrite.WriteLine("AAAA");
A run time in the Unity editor all work perfectly.
But in Android device Application.dataPath seems dont work.
I tryed Application.persistentDataPath that work fine but in (Read Only),but i need place the SavedGame.txt manually in the patch.
I tried a fantomatic "jar:file://" + Application.dataPath + "!/assets/"; but dont work.
Note when i build the project in apk packege semms dont appear my SavedGame.txt,that
in the editor is in UnityProject\Assets .
Come posso risalire al percorso giusto del mio SavedGame.txt, posizionato in ad esempio in UnityProject\Assets nei device?
How i cand do this in a correct way read and write SavedGame.txt in android device?
On android you might not have direct write access to the dataPath of the project.
Try using Application.persistentDataPath instead. This is where save files are intended to be stored.
Change:
filePath = Application.dataPath + "/";
to
filePath = Application.persistentDataPath + "\\";
I have a zip file in my asset folder and when trying to copy this file to the external download folder I cannot open it. It seems as if the file copy does not finish as it is a few kb short of what it should be.
I am using the following code to achieve this:
using (Stream stream = activity.Assets.Open (PINPAD_FOLDER + "/" + file))
{
stream.CopyTo (System.IO.File.Create (outputPath));
stream.Close ();
}
Output folder is:
string outputPath = Path.Combine (Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath, filename);
All I need is to get the path to this zip file from my application which does not seem possible from the Asset directory as we can only get a stream back. Hence I am having to copy it to a directory I know the path of.
Try this one
using (Stream stream = activity.Assets.Open (PINPAD_FOLDER + "/" + file))
{
using(var fileStream = System.IO.File.Create (outputPath))
{
stream.CopyTo(fileStream );
}
}