Use Sample data directory from a library - android

I created Sample data directory for my Android app using the process described in this article. I would like to share this set of sample data between my projects, so I created a library that only has sample data inside. But as far as I can see sampledata folder is not being compiled into the library. Is there a way to share sample data between multiple Android projects?

As already said, you can't do that with a library because sampledata simply can't be part of an Android library.
One thing you could though, host your names file somewhere and then fetch it with a gradle task, you could just add to an app's build.gradle
clean.doFirst {
println "cleanSamples"
def samplesDir = new File(projectDir.absolutePath, "sampledata")
if (samplesDir.exists()) {
samplesDir.deleteDir()
}
}
task fetchSamples {
println "fetchSamples"
def samplesDir = new File(projectDir.absolutePath, "sampledata")
if (samplesDir.exists()) {
println "samples dir already exists"
return
}
samplesDir.mkdir()
def names = new File(samplesDir, "names")
new URL('http://path/to/names').withInputStream { i ->
names.withOutputStream {
it << i
}
}
}
You can see 2 functions there, the first one is run before a clean task and it will just delete your sampledata folder. The second one is a task run on every build, it won't download the file every time but only if the directory is not there.
I understand you might as well copy paste names file, but, with this method you need to copy paste the tasks only once and you would be able to change names in any project just by uploading a new file and doing a clean build.

The short answer is no, you can't do that with sampledata folder. Basically, the format of the Android Libraries is AAR. If you reference the official documentation, it says that:
The file itself is a zip file containing the following mandatory entries:
/AndroidManifest.xml
/classes.jar
/res/
/R.txt
/public.txt
Additionally, an AAR file may include one or more of the following optional entries:
/assets/
/libs/name.jar
/jni/abi_name/name.so (where abi_name is one of the Android supported ABIs)
/proguard.txt
/lint.jar
So, sampledata can't be a part of AAR library.
UPDATE
Instead of your own data samples, you can use predefined sample resources. For example #tools:sample/first_names will randomly select from some common first names, eg., Sophia, Jacob, Ivan.
Example of usage:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="#tools:sample/first_names" />

Related

How do I access a text file for JUnit test in Android?

How can I access a text file in my directory 'src/test/resources'
I can't seem to get it to pickup during my JUnit test
mobile/build.gradle:
sourceSets {
test {
java {
srcDirs = [ 'src/test/java' ]
}
resources {
srcDirs = [ 'src/test/resources' ]
}
}
}
Test method:
#Test
public void test_file() {
URL resource = getClass().getResource("file_four_lines.txt");
File file = new File(resource.getFile()); // Get NullPointerException here
...
}
Prefix the file path with /.
Basically, you'd do something like this:
File helloBleprintJson = new File(
getClass().getResource("/helloBlueprint.json").getPath());
Above snippet is taken from here.
I think this link will help. In your case why not hard code strings for testing? Why not use String.xml instead of "file_four_lines.txt". Internationalization requires a directory structure for each resource file having different language, screen size, orientation, flavor, night/day vision version. For this reason resources are compiled and accessed from the R file. You are trying to bypass this convention by using .txt instead of .xml and accessing the resource directly, it just feels wrong. I don't think testing is you problem as much as not following convention.
Forgive me for posting twice, I do have an answer from the official documentation" Arbitrary files to save in their raw form. To open these resources with a raw InputStream, call Resources.openRawResource() with the resource ID, which is R.raw.filename.
However, if you need access to original file names and file hierarchy, you might consider saving some resources in the assets/ directory (instead of res/raw/). Files in assets/ are not given a resource ID, so you can read them only using AssetManager." Json and txt are non-standard(unsupported) so you have to provide your own implementation/parcer to read this type file. Thanks for this post. I knew something about resources but thanks to your prodding now I know even more. To recap The Android resource system keeps track of all non-code assets associated with an application. The Android SDK tools compile your application's resources into the application binary at build time. To use a resource, you must install it correctly in the source tree (inside your project's res/ directory) and build your application. As part of the build process, the SDK tools generate symbols for each resource, which you can use in your application code to access the resources and of course the symbols referred to are in the generated R file

openalpr on android - path to config and runtime_data

I want to use open alpr (automatic licences plate recognition) library in my android project. I compiled everything successfully and now it is time to use open alpr in app but...
to create Alpr class object properly I have to provide path to config file and path to runtime_data folder which contains some mandatory files needed by open alpr (ocr and trained data).
I tried something like:
Alpr alpr = new Alpr("eu", "android_assets/alpr.conf", "android_assets/runtime_data");
but Alpr.isLoaded() returns false which means that config or runtime_data have not been found.
Path to assets folder in project is: src/main/assets.
Can someone explain to me how path to "runtime_data" directory and "alpr.conf"
should looks to be visible by open alpr?
Thanks in advance.
I am not familiar with the specific library, but on newer Android devices (Android 6 and up), you can not rely on your application files residing under /data/data/your.package.name
The actual library name still includes the package name of your app, but also has some identifier appended to it in base64 format.
This identifier is unique per installation, and it will change if you uninstall and reinstall the app on the same device.
So, if your library needs to use a configuration file with a path to some other files, there are 2 options:
The right way:
Get the real address of your application files folder using Context.getFilesDir().
Unpack you files from the assets folder of the APK on the device using AssetManager.
Programmatically rewrite your configuration file with the path returned by getFilesDir().
The "hacky" but simpler way:
Use public storage to unpack your files.
You will need to add WRITE_EXTERNAL_STORAGE permission to your app, and unpack the assets files to the external storage.
For backwards compatibility this will be available under /sdcard folder on most Android devices, even with the latest Android version.
The second method is not recommended since using /sdcard directly is deprecated and strongly discouraged by Google.
Also, not all Android devices have /sdcard link to their public storage, but this is the only way to avoid dynamically editing the configuration file after installation.
Important note before you start implementing those steps. This library supports only arm CPU architecture. Good news is, most probably, your physical device is using arm architecture but to make sure just double-check it before implemting those steps.
I've recompiled this library to a new wrapper library. In original library, you need to manually configure openalpr.conf file and edit its content with correct path to your data directory. Manual configuration is cumbersome because since Android 5 multiple user accounts is supported and we can't simply hardcode data directory as /data/data/com.your.packagename/..... Because every user gets their symlink to data directory as /data/user/0/com.your.packagename/..... All those manual steps are gone in recompiled wrapper library.
Implementation
Add this in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Add the dependency into app module:
dependencies {
...
implementation 'com.github.mecoFarid:openalpr:1.0.0'
}
And you're done. Please check this sample app to get started with UI.
Troubleshooting:
If your target sdk is targetSdkVersion >= 24 and you're running your app on a device with Android API 24+ you'll get following error:
android.os.FileUriExposedException: file:///storage/emulated/0/OpenALPR/2019-09-21-01-32-13.jpg exposed beyond app through ClipData.Item.getUri()
To solve this error: you can add following lines into onCreate() of your Activity as a workaround or you may use this thread for offical solution:
if(Build.VERSION.SDK_INT>=24){
try{
Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
m.invoke(null);
}catch(Exception e){
e.printStackTrace();
}
}
TEST:
You can use this image to test your app.
"/data/data/yourpackagename" + File.separatorChar + "runtime_data"
+ File.separatorChar + "openalpr.conf";

Android/Cyanogenmod building: remove-project from roomservice.xml

I want to remove a device-related project from the roomservice.xml generated by brunching in CM and add a different repo myself.
Theoretically (in my localmanifest, called mint.xml), I should just need to
<remove-project name="Cyanogenmod/....
But repo sync tells me that
remove-project element specifies non-existant project
Is that because my local manifest is sourced before the roomservice.xml?
The question is a bit related to this one:
trouble-with-cyanogenmod-local-manifest
Additional sources:
CM Wiki about removing projects
Do you know how to source the own manifest after the roomservice.xml or somehow achieve the same?
Thanks for any answers.
As seen in Repo's manifest_xml.py,
LOCAL_MANIFESTS_DIR_NAME = 'local_manifests'
...
class XmlManifest(object):
...
def _Load(self):
...
local_dir = os.path.abspath(os.path.join(self.repodir, LOCAL_MANIFESTS_DIR_NAME))
try:
for local_file in sorted(os.listdir(local_dir)):
if local_file.endswith('.xml'):
local = os.path.join(local_dir, local_file)
nodes.append(self._ParseManifestXml(local, self.repodir))
except OSError:
pass
local manifest files are read in alphabetical order. Your file mint.xml is therefore loaded before roomservice.xml, so at the time you try to remove the project that's defined in roomservice.xml it doesn't actually exist. Rename your file to something that sorts after roomservice.xml.

android gradle mergeDebugAssets

android project with files in assets, these file need encrypt before generator apk
every times i changed some file in assets,
i need copy out these file , encrypt ,then copy into assets
what i want is:
keep file in assets not encypt (can edit it conveniently) ,
but file in .apk encrypted
encrypt work do automatically by gradle.build
my basic idea is thad add some task before mergeDebugAssets (or mergeReleaseAssets)
before mergeDebugAssets, i replace all file in file://$MODULE_DIR$/build/assets
code like below
task processAssetFile {
// code : replace file in build/assets
}
mergeDebugAssets.dependsOn processAssetFile
the problem is
mergeDebugAssets is not available in gradle.build
error log below:
Could not find property 'mergeDebugAssets' on project ':gradle'.
so is there some idea can achieve my goals ?
android studio ver :0.52
You can always find the task by its name.
I would also suggest that you want to perform encryption for other build variants (makes sense for release even more than for debug).
This requires a little bit of coding since you need to create a task for each variant, too.
It is best to create those tasks dynamically so you don't forget a variant.
Say you're encrypting with some command-line tool, the code you need to add could look like this:
android.applicationVariants.all { variant ->
String suffix = variant.variantData.name.capitalize()
Task mergeAssetsTask = tasks.findByName("merge${suffix}Assets")
Task processAssetFileTask = tasks.create(name: "process${suffix}AssetFile", type: Exec)
processAssetFileTask.commandLine "path/to/your/encryption/tool",
"--input-file=${inputFilePath}",
"--output-file=${outputFilePath}"
mergeAssetsTask.dependsOn processAssetFileTask
}

greenDAO schema generation with relative output path; failing with i/o not found

Following along with this tutorial, I've been able to create a working app module that compiles and runs, but fails if I pass a relative path to the generateAll method. It works fine if I specify an absolute path. My android studio project is composed of a few modules, structured like
project_root, with sub directories for each of it's modules
/daogenerator
/app
Each has it's own src directories, and I'm calling the generateAll like:
new DaoGenerator().generateAll(schema,
"../app/src");
which results in an io error, indicating that the directory doesn't exist. I've modified the path to many reasonable alternatives, and confirmed that the paths exist on disk, but still getting the error. The absolute path works fine, so I'm trying to understand what I'm missing to get it working with a relative path. Thanks.
The outDir parameter is expected to be relative to the project directory.
For example, suppose your MyDaoGenerator class is in module1 under projectA and you want to generate the DAO classes into a separate module2 of the same project ...
projectA
module1/
src/main/java/com.my.package/MyDaoGenerator.java
module2/
src/main/java/ <-- target directory
... the outDir parameter would be module2/src/main/java.
In my case I had to change the package to this
new DaoGenerator().generateAll(schema, "app/src/main/java");
from this
new DaoGenerator().generateAll(schema, "../app/src/main/java");
Perhaps you could check the run configurations.
If your dao generator code is in a class named M.java, you can edit the run configuration for it:
Then you should ensure that it is pointing to the right working directory:
Finally, we can generate the dao code:
public static void main(String[] args) throws Exception
{
...
new DaoGenerator().generateAll(schema, "."); // direct to working directory
}
It worked for me. Hope it help.
Source: this tutorial

Categories

Resources