Android files in jar library not accessible when using with Unity - android

I am new to Unity. I have an Android library jar that I want to offer also as a plugin with Unity.
Within the library jar I have a folder html which contains a file temp.json. In the jar file (if I unzip it) the structure is like this: html/temp.json (Note here that jar works fine when running with any Android app outside Unity)
These are the steps that I followed to call my library through Unity:
1) Created folder Assets/Plugins/ Android in my Unity project hierarchy
2) Placed my library jar file there along with AndroidManifest.xml
3) Created a bridge.cs file that I use to call the functions in the jar file
Functions from the jar are called, but within the code of the jar somewhere on the Android side during the library lifecycle I call:
InputStream inputStream = MyClass.class.getClassLoader()
.getResourceAsStream("html/temp.json");
and I get a ResourceNotFound exception
From what I have read Unity ignores these files(like .json) when packaging. Therefore from what I understood in order to keep them in the Jar when packaging I created the following Unity structure:
Assets/Plugins/Android/assets/StreamingAssets/html/temp.json
I realise that any file that is placed within the StreamingAssets folder get copied in the assets folder of the library.
and in Java I call now:
inputStream = activity.getResources().getAssets().open("html/temp.json");
However I still get an exception that the file is not found.
Can anyone please help me/explain to me the procedure I have to follow to be able to read these files on the Java side while executing on Unity for Android?

Try this code:
private void readJson() {
String json = null;
try {
InputStream is = getAssets().open("html/temp.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
}
And save your json file to:
Assets/Plugins/Android/assets/html/temp.json
If you still can not do it, plz contact me
Br,
Frank

Related

Trouble Finding CSV File (with and without OpenCSV) in Eclipse for Android

I'm having trouble reading from a csv file for my Android project. I'm using a Mac, with Eclipse ADT, and have imported OpenCSV.
The problem that I keep running into is that the file is not found. I have tried putting it everywhere, including: in the root folder (where the src folder is located), inside the src folder, and inside res/raw. I have refreshed the view, I have cleaned and rebuilt the project, I have restarted Eclipse, I have tried importing the file by drag and drop as well as by using the import option. For some reason, it still refuses to be found.
When I look at its path and absolute path (using file.getPath() and file.getAbsolutePath() they are: "abc.csv" and "/abc.csv" respectively. I have also double checked the file name, it is not named abc.csv.csv or anything similar.
I've used the following lines of code and these are the ones that have returned the error:
(This is from the OpenCSV site.)
CSVReader reader = new CSVReader(new FileReader("abc.csv"));
(#2 and #3 are not from OpenCSV and are just me experimenting around.)
AssetFileDescriptor descriptor = getAssets().openFd("abc.csv");
CSVReader reader = new CSVReader(new FileReader(descriptor.getFileDescriptor()));
3.
File file = new File("abc.csv");
try
{
Scanner inputStream = new Scanner(file);
while(inputStream.hasNext())
{
String data = inputStream.next();
}
inputStream.close();
}
catch(FileNotFoundException e)
{
Log.i(TAG, "File not found.");
}
Place the file in the assets folder and use AssetManager.

Apache POI xlsx read error "limit exceeds 65536 methods for dex file" Android

I trying to read xlsx files using POI library in Android. There are five jar files. 3 of them are main rest are dependencies. If i exclude any i get errors(class missing).
When i include all 5 jars in my project(sample empty project), it doesn't compiles and give error methods limit exceeds 65536 that dex can have. I have tried following to figure this out:
enabled project proguard
try to create multiple dex files, but due to dependencies problem, i m unable to put them in separate dex file.
enabled to dex.force.jumbo =true in project properties but didn't work.
I m trying following code
public void getto()
{
int totalRows;
String destDir = Environment.getExternalStorageDirectory()+ "/Download/csv_contract_sample2.xlsx";
try {
System.out.println("destDir==> "+destDir);
XSSFWorkbook workBook = new XSSFWorkbook(destDir);
XSSFSheet sheet = workBook.getSheetAt(0);
totalRows = sheet.getPhysicalNumberOfRows();
System.out.println("total no of rows >>>>"+totalRows);
} catch (IOException e) {
e.printStackTrace();
}
}
It is working perfectly fine if i create a java project. But for Android above problem is there. Is there a good solution or any other library for xlsx read?
xls is a zip file. So we can extract zip and get xml files inside and then we can parse it ourself to get sheet data.
This will work for both For both xls and xlsx.
There is even no other API than POI available to read xlsx file.

Android Library Project - Error when calling context.getResources().openRawResource()

I'm developing an android library project that should read from an xml file in its raw resources (let's call it xml_file_name.myextension).
What I do is basically creating a jar file of the library project including these folders:
src
gen
lib
res/raw
and referencing it as a library in a test app. This is the code that I use (inside the library project) in order to get the xml file:
int xml_res_id = -1;
for (Field f : R.raw.class.getFields()) {
System.out.println("Raw resource found: " + f.getName());
if (f.getName().equalsIgnoreCase("xml_file_name"))
xml_res_id = f.getInt(null);
}
if(xml_res_id != -1){
System.out.println("xml_file_id: " + xml_res_id);
InputStream is = context.getResources().openRawResource(xml_res_id);
// Decode xml file with SAXParser..
}
(I have the app context because the app explicitly passes it to the library project.)
What happens is that when I launch the test app (and call the method that reads the xml file) I get this error:
It seems that the xml file is actually in the right folder, because:
1) The for loop actually prints "Raw resource found: xml_file_name.myextension" and "xml_file_id: 2130968576"
2) If I put a file named "xml_file_name.myextension" in the res/raw folder of the app, it does not compile, and the error is: "Error generating final archive: Found duplicate file for APK: res/raw/xml_file_name.myextension". This basically gives me the proof that the
file is correctly "imported" from the library project.
Please Note:
I also tried in this other way
InputStream is = context.getResources().openRawResource(R.raw.xml_file_name);
getting the same error.
I honestly don't understand what could be the problem.. what am I doing wrong?
Edit:
for anyone interested in this issue:
I finally realized that this is not possible, basically because when I try to get a resource through context.anymethod I refer to the R file of the app, so I can't give the resource ID got from the R file of my library project.
It will compile, because the library project jar file contains the resource (R.raw.xml_file), but the call to context.something will always give null as a result because it refers to the app R file, that does not have that particular resource in it.
I finally had to put my xml file in the res/raw folder of the app, and access the xml_file raw resource in this way:
int xml_id = context.getResources().getIdentifier("xml_file_name", "raw", context.getPackageName());
// Getting input stream from xml file
InputStream is = context.getResources().openRawResource(xml_id);
I have actually done this with success - the library object should be within the app context. However, it only works with Activity and no other type that I have found. Using the same library with a FragmentActivity fails with NoClassDefFoundError.
EDIT****
It may work with a FragmentActivity within the same root namespace as the library. I was accessing from a different root namespace.
END EDIT****
I have a library project that references an xml file:
InputStream is = context.getResources().openRawResource(R.raw.application_table_defs);
when I call the library method that executes the previous line I have to pass in a context:
Context context = this.getContext();
The key is fully qualifying the getResource to context.getResources()... that was injected.

Android access to resources outside of activity

I would like to know - are there ways to access android resources and/or assets files (or files from any other folder) outside of an Activity (without passing context)?
Can't access without context:
getResources().getIdentifier("resource_name", "drawable", getPackageName());
getAssets().open("file_in_assets_folder_name");
Throws Exception if not in Activity:
try {
Class class = R.drawable.class;
Field field = class.getField("resource_name");
Integer i = new Integer(field.getInt(null));
} catch (Exception e) {}
Also tried the below, but it complains file doesn't exist (doing something wrong here?):
URL url = new URL("file:///android_asset/file_name.ext");
InputSource source = new InputSource(url.openStream());
//exception looks like so 04-10 00:40:43.382: W/System.err(5547): java.io.FileNotFoundException: /android_asset/InfoItems.xml (No such file or directory)
If the folders are included in the Project Build Path, you can use ClassLoader access files under them outside the android.content.Context, for instance, from a POJO (in case if you don't want to pass a reference of android.content.Context):
String file = "res/raw/test.txt";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);
The res folder is included into Project Build Path by default by all Android SDK version so far.
The assets folder was included into Project Build Path by default before Android SDK r14.
To add folders into Project Build Path, right click your project -- Build Path -- Configure Build Path, add your folder (for example, assets if using later SDK version) as a Source folder in build path.
Check out the similar question I answered before at here.
Android framework when compile your app create static class call:
your.namespace.project.R
you can statically call this class like:
your.namespace.project.R.string.my_prop
this.context.findViewById(your.namespace.project.R.id.my_id_prop);
Maybe you can access dynamic resources this way:
Resources res = this.context.getResources();
int id = res.getIdentifier("bar"+Integer.toString(i+1), "id", this.context.getPackageName());

Android: Linking external file to Eclipse project

The application that I work on has a external SQLite database (sitting in the assets folder). My friend is using the same DB file in the iPhone version of the app. Content of the DB file is updated continuously. As both projects are in the same repository we created a Shared folder where we keep the DB file so both of use can link to that shared resource. It works in the iPhone project but fails in Android.
When in Eclipse, I click on the assets/new/file and click on Advanced and then Link to file in the file system. The file appears in the assets folder (in Eclipse) but I cannot access it from JAVA code.
Why that doesn't work? Is there any other was of linking external files to the project in Eclipse?
Thanks
EDITED:
I use this code for opening the assets file:
OutputStream os = new FileOutputStream(db_path + DB_NAME);
byte []b = new byte[1024];
int i, r;
//load list of files from 'data' folder
String[] fileCollection = am.list("data");
Arrays.sort(fileCollection);
for(i=0;i<fileCollection.length;i++)
{
//String fn = String.format(DB_NAME"%dd.db", (i + 1));
String fn = DB_NAME + "." + (i + 1);
if(fileCollection[i].equals(fn) == false){
break;
}
InputStream is = am.open("data/"+fn);
while((r = is.read(b)) != -1) {
os.write(b, 0, r);
}
is.close();
}
os.close();
From, the detail you given in question, I conclude that you can not use database file directly from the asset directory, you have to copy that database file into application's internal storage data/data/database/ and then use it.
EDIT:
I think Android environment can't recognize the physical path of you system files, so when we try to link any file for asset or any folder which are in android project hierarchy then it can not find the file which one linked from a system path.
So to make it working in android you have to put that file in your asset directory physically, not virtually (by putting file link in asset).
Hope I am not wrong in this. If yes then let me know on this topic.
Thanks.

Categories

Resources