oblac / jodd

Jodd! Lightweight. Java. Zero dependencies. Use what you like.
https://jodd.org
BSD 2-Clause "Simplified" License
4.06k stars 723 forks source link

[Android] JSON parsing fails on main thread because of network calls #748

Closed neroux closed 4 years ago

neroux commented 4 years ago

Using the JSON library in an Android project and calling it from the main thread will eventually throw an android.os.NetworkOnMainThreadException exception, as the parser uses UnsafeUtil.getChars which in turn SystemUtil.info().isAndroid() to initialise IS_ANDROID.

The problem here is SystemUtil.info() returns a SystemInfo instance, which is eventually derived from HostInfo and that class makes a call to InetAddress.getLocalHost(), which is not permitted in the context of the main thread on Android.

https://github.com/oblac/jodd/blob/71c4b65eaf196022abe21a32edd416749863836e/jodd-core/src/main/java/jodd/system/HostInfo.java#L45

I wouldnt call it a bug per se (a workaround would be to have the JSON parsing done on a separate thread) but it is still something to take into account.

igr commented 4 years ago

Dang. I used to have a mobile version of jars, with some classes removed.

btw, is there now any tool that can tell me which methods are problematic?

igr commented 4 years ago

It's so interesting how somethings look good one day and then, sometime later, you think: why the hell I wrote that? Why did I put all these classes extending each other?

igr commented 4 years ago

This should fix it.

neroux commented 4 years ago

Good Lord, that was fast! 😃

As for a tool, I am afraid I wouldnt be aware of one. For most of it Android is just yet another Java, however there are subtle differences like mentioned network communication on the main thread, which will throw an exception to prevent people from doing so.

Additionally Java 1.8 compatibility still has to be manually enabled, as otherwise it wont recognise it.

igr commented 4 years ago

I am kinda back to dev mode :)

Yeah, just wonder how come no one built a static analyzer and simply lint the code, after all this time.

neroux commented 4 years ago

@igr, any chance to get 5.1.4 with this fix? Right now the Gradle way doesnt work because of this issue (and I have no idea how to configure Gradle to overwrite one class with a local version), so I went back to my traditional ways of including JAR files :)

igr commented 4 years ago

Sure @neroux ! Give me a day or so!

igr commented 4 years ago

@neroux should be released!

neroux commented 4 years ago

Merci, @igr