Tuesday, 25 August 2015

String manipulations

One my friend asked me how to memorize these string manipulation functions in most of modern programming languages. Why the hek first argument in substring is zero based and second one is one based?

Everything will be easier if you realize that these offsets are not characters but something between characters. Imagine that characters in your string are separated by lines, and numbers are actually indexes of these separators rather than indexes of characters. The picture below will illustrate it well:

So, when you say “substring”, you ask computer to take a string between these separators and (a – b) will be amount of numbers to substring. If a==b, then you substring zero characters. The same about functions like insert, it inserts a string onto the separator, because you usually need to insert the string between characters, not onto them.

Monday, 17 August 2015

Reading XLSX on Android 5+

New Android Build Tools (21+) and Android 5 (ART) seems to easily fix the problem with 65K methods for Apache POI.

All you need to do is to copy the following files into libs dir of your project:
xmlbeans-2.6.0.jar - the hero of the day, this jar is deffective in maven repo, so it's needed to repack this jar.

See also the repo with repacked POI 3.12 jars and gradle config examples: https://github.com/andruhon/android5xlsx

Add the following into your app/build.gradle to compile your project with multi-dex to fix 65K method's limit and --core-library, to avoid the warning about javax namespace in your libs.
apply plugin: 'com.android.application'

android {
    // ...your other project settings...
    project.tasks.withType(com.android.build.gradle.tasks.Dex) {
dependencies {
    // ...deps settings...
    compile 'com.android.support:multidex:1.0.0' //enable multi-dex

You still might want to do a 'aavax' hack, to avoid conflicts with future android releases.

If xmlbeans not broken it would be possible to achieve the same results with just adding 'org.apache.poi:poi-ooxml:3.12' into dependencies, however it will not work straighforwardly because xmlbeans jar in maven is defective and contains duplicates of classes, these duplicates are ok for desktop JVM, but android chokes with them. So it is required to add some routine to re-pack xmlbeans and disable preDex. It will work. however the build process will be quite slow, so it is easier just to prepare jars once and put them into libs directory (as described above)

Special thanks to Heiko Johann for pointing onto new Android Build Tools features

https://github.com/andruhon/android5xlsx - config example
http://www.docx4java.org/trac/docx4j - another project of reading OpenXML from Java

Previous posts: