Unity Gear VR error on build - android

I.m trying to setup and build https://resources.samsungdevelopers.com/Gear_VR/030_Create_VR_App_or_Game_Using_a_Game_Engine/Exercise_2%3A_Create_a_Splash_Screen/Step_7%3A_Build_and_Run_the_Application
When I try and build the application it throws the following error:
Assets/Workshop/Scripts/TextureLoader.cs(114,31): error CS1105: `TextureLoader.GetFilesWithExtensions(this DirectoryInfo, params string[])': Extension methods must be declared static
// Gets the list of files in the directory by extention and filters for our specified ones (images)
public IEnumerable<FileInfo> GetFilesWithExtensions (this DirectoryInfo dir, params string[] extensions) {
IEnumerable<FileInfo> files = dir.GetFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
public bool isFinishedLoadingFirstTexture() {
return mFinishedFirstTexture;
}
I have already changed it to a public static class in the header.

The class being static doesn't do much for the methods. You need to make your method static for the extensions to work!
public static IEnumerable<FileInfo> GetFilesWithExtensions (this DirectoryInfo dir, params string[] extensions) {
IEnumerable<FileInfo> files = dir.GetFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
I wrote an extension method here if you need another example!

I order to make an extension method, the class must be public and static.
The function must be public and static too. You missed this part.
public static class TextureLoader
{
public static IEnumerable<FileInfo> GetFilesWithExtensions(this DirectoryInfo dir, params string[] extensions)
{
IEnumerable<FileInfo> files = dir.GetFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
}

Modify your code this way, the error will disappear
private IEnumerable<FileInfo> GetFilesWithExtensions(DirectoryInfo dir, string[] extensions)
{
IEnumerable<FileInfo> files = dir.GetFiles();
return files.Where(f => extensions.Contains(f.Extension));
}

Related

Cordova plugin Android Activity - accessing resources

I am developing a Cordova plugin for Android and I am having difficulty overcoming accessing project resources from within an activity - the plugin should be project independent, but accessing the resources (e.g. R.java) is proving tricky.
My plugin, for now, is made up of two very simple classes: RedLaser.java and RedLaserScanner.java.
RedLaser.java
Inherits from CordovaPlugin and so contains the execute method and looks similar to the following.
public class RedLaser extends CordovaPlugin {
private static final string SCAN_ACTION = "scan";
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals(SCAN_ACTION)) {
this.cordova.getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
scan(args, callbackContext);
}
});
return true;
}
return false;
}
private void scan(JSONArray args, CallbackContext callbackContext) {
Intent intent = new Intent(this.cordova.getActivity().getApplicationContext(), RedLaserScanner.class);
this.cordova.startActivityForResult((CordovaPlugin) this, intent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Do something with the result
}
}
RedLaserScanner.java
The RedLaserScanner contains the Android Activity logic and inherits from BarcodeScanActivity (which is a RedLaser SDK class, presumably itself inherits from Activity);
A very simple structure is as follows:
public class RedLaserScanner extends BarcodeScanActivity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.preview_overlay_new_portrait);
}
}
I am having trouble because I need to access the project's resources to access R.layout.preview_overlay_new_portrait (which are scatted in the Eclipse project) - but I cannot do this unless I import com.myProject.myApp.R - which makes my plugin have a dependency on the project itself.
I did some investigation and found cordova.getActivity().getResources() which seems useful, but this is not accessible from within my RedLaserScanner - because it does not inherit from CordovaPlugin.
Can somebody please help me with some pointers?
Thanks
I just ran into the same issue and it turns out to be pretty easy to solve. RedLaserScanner extends an activity, so you can just call getResources() like this:
setContentView(getResources("preview_overlay_new_portrait", "layout", getPackageName()));
Hooks can be used to replace source file contents to remove wrong imports and/or add the right imports of resources.
I created a script that do it without needing to specify the files. It tries to find source files (with .java extension), removes any resource import already in it and then put the right resources import (if needed), using the Cordova application package name.
This is the script:
#!/usr/bin/env node
/*
* A hook to add resources class (R.java) import to Android classes which uses it.
*/
function getRegexGroupMatches(string, regex, index) {
index || (index = 1)
var matches = [];
var match;
if (regex.global) {
while (match = regex.exec(string)) {
matches.push(match[index]);
console.log('Match:', match);
}
}
else {
if (match = regex.exec(string)) {
matches.push(match[index]);
}
}
return matches;
}
module.exports = function (ctx) {
// If Android platform is not installed, don't even execute
if (ctx.opts.cordova.platforms.indexOf('android') < 0)
return;
var fs = ctx.requireCordovaModule('fs'),
path = ctx.requireCordovaModule('path'),
Q = ctx.requireCordovaModule('q');
var deferral = Q.defer();
var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/src');
var pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');
var androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
var appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];
fs.readdir(pluginSourcesRoot, function (err, files) {
if (err) {
console.error('Error when reading file:', err)
deferral.reject();
return
}
var deferrals = [];
files.filter(function (file) { return path.extname(file) === '.java'; })
.forEach(function (file) {
var deferral = Q.defer();
var filename = path.basename(file);
var file = path.join(pluginSourcesRoot, filename);
fs.readFile(file, 'utf-8', function (err, contents) {
if (err) {
console.error('Error when reading file:', err)
deferral.reject();
return
}
if (contents.match(/[^\.\w]R\./)) {
console.log('Trying to get packages from file:', filename);
var packages = getRegexGroupMatches(contents, /package ([^;]+);/);
for (var p = 0; p < packages.length; p++) {
try {
var package = packages[p];
var sourceFile = path.join(platformSourcesRoot, package.replace(/\./g, '/'), filename)
if (!fs.existsSync(sourceFile))
throw 'Can\'t find file in installed platform directory: "' + sourceFile + '".';
var sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
if (!sourceFileContents)
throw 'Can\'t read file contents.';
var newContents = sourceFileContents
.replace(/(import ([^;]+).R;)/g, '')
.replace(/(package ([^;]+);)/g, '$1 import ' + appPackage + '.R;');
fs.writeFileSync(sourceFile, newContents, 'utf8');
break;
}
catch (ex) {
console.log('Could not add import to "' + filename + '" using package "' + package + '". ' + ex);
}
}
}
});
deferrals.push(deferral.promise);
});
Q.all(deferrals)
.then(function() {
console.log('Done with the hook!');
deferral.resolve();
})
});
return deferral.promise;
}
Just add as an after_plugin_install hook (for Android platform) in your plugin.xml:
<hook type="after_plugin_install" src="scripts/android/addResourcesClassImport.js" />
Hope it helps someone!
I implemented a helper for this to keep things clean. It also helps when you create a plugin which takes config.xml arguments which you store in a string resource file in the plugin.
private int getAppResource(String name, String type) {
return cordova.getActivity().getResources().getIdentifier(name, type, cordova.getActivity().getPackageName());
}
You can use it as follows:
getAppResource("app_name", "string");
That would return the string resource ID for app_name, the actually value still needs to be retrieved by calling:
this.activity.getString(getAppResource("app_name", "string"))
Or for the situation in the original question:
setContentView(getAppResource("preview_overlay_new_portrait", "layout"));
These days I just create a helper which returns the value immediately from the the helper:
private String getStringResource(String name) {
return this.activity.getString(
this.activity.getResources().getIdentifier(
name, "string", this.activity.getPackageName()));
}
which in turn you'd call like this:
this.getStringResource("app_name");
I think it's important to point out that when you have the resource ID you're not always there yet.
try using android.R.layout.preview_overlay_new_portrait

Is there a "cleaner" way to refer to a file with a given extension? [duplicate]

Is there a Java equivalent for System.IO.Path.Combine() in C#/.NET? Or any code to accomplish this?
This static method combines one or more strings into a path.
Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.
If you're using Java 7 or Java 8, you should strongly consider using java.nio.file.Path; Path.resolve can be used to combine one path with another, or with a string. The Paths helper class is useful too. For example:
Path path = Paths.get("foo", "bar", "baz.txt");
If you need to cater for pre-Java-7 environments, you can use java.io.File, like this:
File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:
public static String combine(String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
In Java 7, you should use resolve:
Path newPath = path.resolve(childPath);
While the NIO2 Path class may seem a bit redundant to File with an unnecessarily different API, it is in fact subtly more elegant and robust.
Note that Paths.get() (as suggested by someone else) doesn't have an overload taking a Path, and doing Paths.get(path.toString(), childPath) is NOT the same thing as resolve(). From the Paths.get() docs:
Note that while this method is very convenient, using it will imply an assumed reference to the default FileSystem and limit the utility of the calling code. Hence it should not be used in library code intended for flexible reuse. A more flexible alternative is to use an existing Path instance as an anchor, such as:
Path dir = ...
Path path = dir.resolve("file");
The sister function to resolve is the excellent relativize:
Path childPath = path.relativize(newPath);
The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing, such as the concat() method.
platform independent approach (uses File.separator, ie will works depends on operation system where code is running:
java.nio.file.Paths.get(".", "path", "to", "file.txt")
// relative unix path: ./path/to/file.txt
// relative windows path: .\path\to\filee.txt
java.nio.file.Paths.get("/", "path", "to", "file.txt")
// absolute unix path: /path/to/filee.txt
// windows network drive path: \\path\to\file.txt
java.nio.file.Paths.get("C:", "path", "to", "file.txt")
// absolute windows path: C:\path\to\file.txt
I know its a long time since Jon's original answer, but I had a similar requirement to the OP.
By way of extending Jon's solution I came up with the following, which will take one or more path segments takes as many path segments that you can throw at it.
Usage
Path.combine("/Users/beardtwizzle/");
Path.combine("/", "Users", "beardtwizzle");
Path.combine(new String[] { "/", "Users", "beardtwizzle", "arrayUsage" });
Code here for others with a similar problem
public class Path {
public static String combine(String... paths)
{
File file = new File(paths[0]);
for (int i = 1; i < paths.length ; i++) {
file = new File(file, paths[i]);
}
return file.getPath();
}
}
To enhance JodaStephen's answer, Apache Commons IO has FilenameUtils which does this. Example (on Linux):
assert org.apache.commons.io.FilenameUtils.concat("/home/bob", "work\\stuff.log") == "/home/bob/work/stuff.log"
It's platform independent and will produce whatever separators your system needs.
Late to the party perhaps, but I wanted to share my take on this. I prefer not to pull in entire libraries for something like this. Instead, I'm using a Builder pattern and allow conveniently chained append(more) calls. It even allows mixing File and String, and can easily be extended to support Path as well. Furthermore, it automatically handles the different path separators correctly on both Linux, Macintosh, etc.
public class Files {
public static class PathBuilder {
private File file;
private PathBuilder ( File root ) {
file = root;
}
private PathBuilder ( String root ) {
file = new File(root);
}
public PathBuilder append ( File more ) {
file = new File(file, more.getPath()) );
return this;
}
public PathBuilder append ( String more ) {
file = new File(file, more);
return this;
}
public File buildFile () {
return file;
}
}
public static PathBuilder buildPath ( File root ) {
return new PathBuilder(root);
}
public static PathBuilder buildPath ( String root ) {
return new PathBuilder(root);
}
}
Example of usage:
File root = File.listRoots()[0];
String hello = "hello";
String world = "world";
String filename = "warez.lha";
File file = Files.buildPath(root).append(hello).append(world)
.append(filename).buildFile();
String absolute = file.getAbsolutePath();
The resulting absolute will contain something like:
/hello/world/warez.lha
or maybe even:
A:\hello\world\warez.lha
If you do not need more than strings, you can use com.google.common.io.Files
Files.simplifyPath("some/prefix/with//extra///slashes" + "file//name")
to get
"some/prefix/with/extra/slashes/file/name"
Here's a solution which handles multiple path parts and edge conditions:
public static String combinePaths(String ... paths)
{
if ( paths.length == 0)
{
return "";
}
File combined = new File(paths[0]);
int i = 1;
while ( i < paths.length)
{
combined = new File(combined, paths[i]);
++i;
}
return combined.getPath();
}
This also works in Java 8 :
Path file = Paths.get("Some path");
file = Paths.get(file + "Some other path");
This solution offers an interface for joining path fragments from a String[] array. It uses java.io.File.File(String parent, String child):
public static joinPaths(String[] fragments) {
String emptyPath = "";
return buildPath(emptyPath, fragments);
}
private static buildPath(String path, String[] fragments) {
if (path == null || path.isEmpty()) {
path = "";
}
if (fragments == null || fragments.length == 0) {
return "";
}
int pathCurrentSize = path.split("/").length;
int fragmentsLen = fragments.length;
if (pathCurrentSize <= fragmentsLen) {
String newPath = new File(path, fragments[pathCurrentSize - 1]).toString();
path = buildPath(newPath, fragments);
}
return path;
}
Then you can just do:
String[] fragments = {"dir", "anotherDir/", "/filename.txt"};
String path = joinPaths(fragments);
Returns:
"/dir/anotherDir/filename.txt"
Assuming all given paths are absolute paths. you can follow below snippets to merge these paths.
String baseURL = "\\\\host\\testdir\\";
String absoluteFilePath = "\\\\host\\testdir\\Test.txt";;
String mergedPath = Paths.get(baseURL, absoluteFilePath.replaceAll(Matcher.quoteReplacement(baseURL), "")).toString();
output path is \\host\testdir\Test.txt.

Calling static jar function from Unity3D

I made and compiled a Android Library, containing a simple class and a simple static function:
package moo;
public class MyTestClass {
public static String Foo(){
return "Foo from Moo";
}
}
I placed the .jar in my Assets/Plugins/Android Folder. Then In Unity:
void OnGUI () {
string somestring = "foooooooooooOOooo";
AndroidJavaClass testClass = new AndroidJavaClass("moo.MyTestClass");
somestring = testClass.CallStatic<string>("Foo");
GUI.Label (new Rect (20, 20, 100, 20), somestring);
}
And I get an error:
JNI: Unable to find method id for 'Foo' (static)
UnityEngine.AndroidJavaObject:CallStatic(String, Object[])
Am I missing something to call my static method?
Thanks!
there are 2 problem as far as I can see:
you have to put your jar package to Assets/Plugins/Android/bin;
you will always get this error on your windows/mac editor, you have to run this on your android device;

How to provide data files for android unit tests

I am developing software that loads information from XML files using Android's implementation of java.xml.parsers.DocumentBuilder and DocumentBuilderFactory. I am writing unit tests of my objects and I need to be able to provide a variety of xml files that will exercise the code under test. I am using Eclipse and have a separate Android Test Project. I cannot find a way to put the test xml into the test project such that the code under test can open the files.
If I put the files in /assets of the test project, the code under test cannot see it.
If I put the files in the /assets of the code under test, it can of course see the files, but now I'm cluttering up my actual system with test only data files.
If I hand copy the files to the /sdcard/data directory, I can open them from the code under test, but that interferes with automating my tests.
Any suggestions of how to have different xml test files reside in the test package but be visible to the code under test would be greatly appreciated.
Here is how I tried to structure the unit test:
public class AppDescLoaderTest extends AndroidTestCase
{
private static final String SAMPLE_XML = "sample.xml";
private AppDescLoader m_appDescLoader;
private Application m_app;
protected void setUp() throws Exception
{
super.setUp();
m_app = new Application();
//call to system under test to load m_app using
//a sample xml file
m_appDescLoader = new AppDescLoader(m_app, SAMPLE_XML, getContext());
}
public void testLoad_ShouldPopulateDocument() throws Exception
{
m_appDescLoader.load();
}
}
This did not work as the SAMPLE_XML file is in the context of the test, but AndroidTestCase is providing a context for the system under test, which cannot see an asset from the test package.
This is the modified code that worked per answer given:
public class AppDescLoaderTest extends InstrumentationTestCase
{
...
protected void setUp() throws Exception
{
super.setUp();
m_app = new Application();
//call to system under test to load m_app using
//a sample xml file
m_appDescLoader = new AppDescLoader(m_app, SAMPLE_XML, getInstrumentation().getContext());
}
Option 1: Use InstrumentationTestCase
Suppose you got assets folder in both android project and test project, and you put the XML file in the assets folder. in your test code under test project, this will load xml from the android project assets folder:
getInstrumentation().getTargetContext().getResources().getAssets().open(testFile);
This will load xml from the test project assets folder:
getInstrumentation().getContext().getResources().getAssets().open(testFile);
Option 2: Use ClassLoader
In your test project, if the assets folder is added to project build path (which was automatically done by ADT plugin before version r14), you can load file from res or assets directory (i.e. directories under project build path) without Context:
String file = "assets/sample.xml";
InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);
For Android and JVM unit tests I use following:
public final class DataStub {
private static final String BASE_PATH = resolveBasePath(); // e.g. "./mymodule/src/test/resources/";
private static String resolveBasePath() {
final String path = "./mymodule/src/test/resources/";
if (Arrays.asList(new File("./").list()).contains("mymodule")) {
return path; // version for call unit tests from Android Studio
}
return "../" + path; // version for call unit tests from terminal './gradlew test'
}
private DataStub() {
//no instances
}
/**
* Reads file content and returns string.
* #throws IOException
*/
public static String readFile(#Nonnull final String path) throws IOException {
final StringBuilder sb = new StringBuilder();
String strLine;
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"))) {
while ((strLine = reader.readLine()) != null) {
sb.append(strLine);
}
} catch (final IOException ignore) {
//ignore
}
return sb.toString();
}
}
All raw files I put into next path: ".../project_root/mymodule/src/test/resources/"
Try this for Kotlin:
val json = File("src\\main\\assets\\alphabets\\alphabets.json").bufferedReader().use { it.readText() }

Getting files from other folders in android

I want to make an array of specific types of files with .txt that are found in all android folders.
I am bit off I need to loop through all folders then create a list out of all the items found with the file name of ".txt".
My question is what method do I need to start from the top of all the folders? Also I need a method to open a specific folder(So I can loop through the FileNameFilter method).
Also I don't mind any recommendation on how to do this kind of method.
public String getFile(int position){
File root = Environment.getExternalStorageDirectory();//This is incorrect it just goes to it's current environment it's folder found for this application.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
return !filename.endsWith(".txt");
}
};
ArrayList<File> items = new ArrayList<File>(Arrays.asList(root.listFiles(filter)));
String returned = items.get(position).toString();
return returned;
You need a recursive method that will loop through a folder and, for each child : if the child is a folder, call itself with the child as parameter. If the child is a file, check its name and add it if needed.
You can do something like
public void findAllFilesWithExtension( File dir, String extension, List<File> listFiles ) {
List<File> listChildren = Arrays.asList(dir.listFiles());
for( File child : listChildren ) {
if( child.isDirectory() ) {
findAllFilesWithExtension( child, extension, listFiles );
} else if( child.getName().endsWith( extension ) ) {
listFiles.add( child );
} //else
} //for
}//met
And call it first on your root directory.

Categories

Resources