Tuesday, 10 November 2015

Wrap-up JavaOne'15

It might be a little late for the post but there is much to be said..

Another JavaOne is over, not only a JavaOne but 19th JavaOne on 20th year of Java!!

I just feel JavaOne is turning into a old friends gathering event for me than the technical conference it used to be. The conference is shrinking in terms of contents and number of sessions while Oracle Open World expands to sessions rooms which were part of JavaOne.

Don't get me wrong, I still enjoy going JavaOne, meeting friends and community. However, variety of sessions become much limited. The 20th year of Java keynote must have been the most boring one except for the part Scott McNealy was on screen. Actually it might have been the only worth to watch part of the whole keynote!

So what happened... why J1 is just fading away? Is java and us getting old?

It is not a secret that J1 has lost a lot of blood after being kicked out Moscone in 2010 but it got worsen with loosing the mobile track with the going down of Java ME. Since moved out of Moscone J1 was hosted in the Hotel trio Hilton, Nikko and Park55. However this the trio has become duo leaving another hotel to Oracle Open World. I really wonder if OOW need so many rooms (Moscone South/North/West and now an additional hotel!) while j1 is shrinking.
Also this year before J1, Oracle terminated contracts of many veteran Java Evangelists which left most fun part of Java and J1 in the dark. One may argue that Java does not really need evangelism anymore but than where was the fun stuff such as minority report demo at the keynote?

So what to do now? How can we bring back the spirit?

Here are my 2 cents to Oracle...

- I respect and understand you want to highlight stuff you are doing in the keynote but believe me it is boring. Either find a fun way to talk about it or just delegate this to session speakers. For the last 3 years we are just listening the same jigsaw and lambda slides and how Oracle is investing and engineering java! For the keynote, for once, forget marketing and make fun!
- Let's face it Java ME is long time dead on mobile but may re-born for IoT. This year was a good sign that Java ME can really shine with IOT but thats it.
- So Java lost the mobile phones?? No, hell no.... Even if you like it or not, Android has become the most widely used mobile OS and even if it does not run on JVM, it is still the Java language! The lawsuit is over, make peace and let Java survive on mobile! Let's face it what will happen if google walks away from java on android! Be wise Oracle, even Microsoft is investing on Android...
- Please, please, please keep j1 keynote in moscone!
- Finally, we are on the same boat Oracle... please don't just let it sink..

Tuesday, 14 July 2015

I will be speaking at JavaOne'15

In case you are planning to attend JavaOne, let me pitch my recently accepted sessions.

My first talk will be about Design Patterns in JavaEE which I recently published a book on and the better I am honored to give this talk with Reza Rahman. Below you may find the official abstract.

Java EE revisits GoF Design Patterns
Design Patterns are not only cool but also bring years of collective wisdom to every level of developers. Since GoF, many books have been written and words shed, as well as many new concepts like Enterprise and Domain Design Patterns extended the coverage the Design Patterns, originally shared by the famous Gang of Four. Unlike the J2EE 1.4 era, Java EE provides easy and out of box implementations of many well known design patterns such as Singleton, Facade, Observer, Factory, Dependency Injection, Decorator, Data Access Patterns, MVC and even more. Many classical design patterns are actually just one annotation away from your project. Attend this talk to watch and learn by live coding demos of Design Patterns in Java EE.

The next talk is about mobile apps. Well I might hear people mourning about JavaME but worry not. The talk will about GWT which would enable developers to write Java which would be compiled and packed as an HTML5 app. And guess what, yes it does run on iOS.

Mobile Java with GWT, Still "Write Once Run Everywhere"
Times have changed and although JavaME still has a market share, it is not available on all devices anymore. Java/JavaME developers had no problem moving to Blackberry or Android but had faced challenges on iOS. HTML5+phonegap apps promised a magic silverbullet for write once run on all devices approach via several frameworks which in the end offered painful javascript and css development. While GWT offers a great Java to JS compiler and debugger, MGWT introduces native looking widgets both on ios, android and even blackberry. Also with the addition of gwt-phonegap projects, now you can code native looking html apps which can use native apis only with regular, type-safe, well known beatiful Java without coding a single line of html+JS.

I am excited to give my 8th talk in my 7th JavaOne. Don't hesitate to stop by and say hi if you will be around!

Permissions in Android M Preview

Milkyway? Well I guess so but macaroon, muffin, marsmallow are still good candidates to become the name of the new Android version. We have more to make guesses until the final version is relased in quarter 3. Following last years tradition of releasing a preview version at the time IO, Google has already released M Preview. Unlike last year this preview release pretty much functional and two more previews will be release (end june and end july) before the final version.

Let's forget about the naming and deep dive into technical parts of 'M'. If you are planning to have hands on experience on M, the system images for your devices are located here. If your android studio is subscribed the preview channel for sdk updates, you should have already been informed about an available sdk update which is called "android-MNC".

The most significant change with M is the permissions. Android applications ask for permissions before the installiation of an app. Once the app is given the permissions it is asking for, disabling a permission is not an option for the user. This was a simple design decision (both for users and developers) but introduced undesired app behavior for a user. However, on M, permissions are granted or denied at runtime.

If the permission is denied the app may receive an empty object, a null object or may even got a security exception. Since apps relied on permissions to be granted automatically until M, this would introduce an important change to legacy apps.

If you do not update you app compiled with target sdk pointing M, the application will ask for list of needed permissions at the time of install. However, the user can always turn of a granted permission which leaves the app to deal with denied permission. A dialog saying the app may crash will be shown while if user disables a permission. If you compiled your app with M as the the target sdk, the app will install silently and ask for each needed permission at the time execution.

This a big change which may effect previous code. Simply you need to revisit your old apps make sure you handle the cases where permission is not granted. In most cases the app should recover and continue working.

I think this a very good change. Users tend to not read permissions while installing (do any of you read agreements?) but asking permissions in runtime always gets the attention of the user. Plus the user would realize what current context and judge if the permissions makes sense.

Welldone Android team, let's see how old apps will survive the change..

Thursday, 11 June 2015

How email fails to share experience or help others..

- Help me Obi-Wan Kenobi, you're my only hope!
Projection light goes off and Obi-Wan turns to Luke...

Well we are all familiar with the scene right? Sending a holographic video message with an astro droid is pretty much like sending an email (it is electronic, send to a recipient can even have attachments :) ) and it saved the galaxy.

However, I don't think thats the case with real life. I started programming at an early age on Commodore 64, of course it was Basic. When I got my Amiga, I discovered a new more capable programming language called Amos. One day I managed to find a copy of an Amos manual. It was just a bad photocopy but come on it was much before internet and it was all I need to boost my coding skills on Amos. Very soon I became pretty popular between high school friends who are interested in Amos. I read code sniplets from the book on phone to help them solve their code issues.

Since than I enjoyed anyone who asked for help. Tried reply every single email, write blogs, give talks and even write a book (it is exhausting!!). However, a recent event just made me realize email is not the platform to share experience or help each other.

I was contacted by a kind lady whom was a friend of a friend seeking help. Basically she had an activity which fires a TimerTask to retrieve data from backend periodically. When the user navigates to another activity the dialog from the TimerTask continued to show up and actually that was it.

The email was actually not longer than a paragraph of text with the activity code.

Most of you may have already figured out what is wrong. The activity fires an AsyncTask but since the AsyncTask ran on its own thread, it has no idea if the activity is still in use, paused or even destroyed. However, there was more. The backend was a Secure SOAP Webservice. So each time the asynctask is executed, it creates a new connection, does login, prepares the soap message, makes request, decodes the soap response and finally displays the data which was actually only a two integer!

So I wrote a long detailed email to point each problem...

- Calling a soap webservice from a mobile device is waste of bandwidth. The backend service can be wrapped into a simple rest service which could serve the same 2 digit integer in either xml or json. This would also enable to encapsulate the changes in webservice.
- AsyncTask is easy and great but not for repetitive and long running jobs. Creating an asynctask is expensive. Besides creating asynctask periodically may also cause to follow the order of the responses. The proper way to retrieve data periodically from a backend would be either using Services or via ContentProvider (with or without a Loader). This way the connection can be created for only once and the login process doesn't need to take place each time. Also since the activity would either stop listening updates or unbinds the service so the data won't popup on other activities.
- Finally if all those create a huge burden (provided that this is just a school project, which need to be delivered tomorrow and won't go live ever) than Volley can be used instead of AsyncTask, which would cancel the request when the activity is not active as well as giving the option to cancel or pending requests.

Btw, my email started with asking if she would consider posting the question to StackOverFlow and if she does, I would love to re write the solution once again there.

..and she disappeared :) of course I am not expecting a box of chocolate or a thanks note but don't have any idea if she liked the answer or what level of fix she decided to implement. Besides all the data is lost forever, no one would benefit from my answer or may be her brilliant idea which overrides my solution.

So.. not really sure, email really helps and acts as a tool to solve problems or share knowledge at all..

Monday, 9 March 2015

Hitchhiker's Guide to Modern Android Development: The Pitfalls and Cryptic Errors

No platform or language is perfect, each has its own problems, pitfalls and cryptic errors of its own. Thanks to Java heritage, Android usually offers smooth, easily learning curve with a huge database of blogs, forums and stackoverflow answers.
After running and mentoring the Study Jam series for two weeks, I decided to compile a set of common pitfalls developers came across which tend to be cryptic or not google friendly.

Error: Gradle DSL method not found: 'runProguard()'
Possible causes:<ul><li>The project 'XX' may be using a version of Gradle that does not contain the method.
<a href="open.wrapper.file">Open Gradle wrapper file</a></li><li>The build file may be missing a Gradle plugin.
<a href="apply.gradle.plugin">Apply Gradle plugin</a></li>

This is one of the most cryptic error you may come across on Android. If you have been using Android Studio from Beta, you will/did probably face this error after upgrading to gradle version 0.14.0 (Android Studio 0.9). Simply the Android Tools team decided to rename runProguard to minifyEnabled. Similarly zipAlign has been enabled to zipAlignEnabled. You may find the full list of changes here.

Error:The project is using an unsupported version of the Android Gradle plug-in (X.X.X). The recommended version is X.X.X.
<a href="fixGradleElements">Fix plugin version and re-import project</a>

Similar to previous issue, this problem occurs each time you get an update to Android Studio and Gradle. Unlike the previous one, this can easily be solved by clicking the Fix plugin version link provided in the Gradle Messages window.


You may come across this error if it is your first network call ever or you are updating an old app to post Honeycomb. Beginning from 4.0 (Ice Cream Sandwich) Android OS does not allow performing network operations on main (UI) thread which should have been this way since day 0. The main thread's main responsibility is running the UI smoothly. Networking, file i/o or any other lengthy operation will block the UI updates resulting in non smooth UI/UX. Networking might be the worst of all since the speed of the connection can rely on many different factors.
The solution is simple. Anything which is not part of UI should not be done in the main thread. Android offers an easy way to use threads which is called AsyncTask. Simply use an AsyncTask to perform lengthy operations.

I use an AsyncTask but still getting android.os.NetworkOnMainThreadException

To start an Asynctask, you need to call the .execute method on the Asynctask object. Calling the .doInBackground method will bypass the creation of a new thread and run the network operation on the main thread.

java.lang.SecurityException: Permission Denial: ... requires Android.permission.X

Android is based on linux and each app runs on its own sandbox with very limited permissions. If you need access a common system resource such as camera, bluetooth, internet or file system, you need to ask users permission. The permission are added to AndroidManifest.xml between the manifest and application tags. You can refer this for a complete set of permissions which can be added with uses-permission tag.

I added the permission java.lang.SecurityException: Permission Denial: ... requires Android.permission.X

Having a valid AndroidManifest.xml does not necessarily mean it is just working. Adding the uses-permission tags in the application tag, does not break the xml structure but doesn't reserve the permissions you asked either. List your uses-permission tags out of the application tag.

Permission Denial: … requires android.permission.WRITE_EXTERNAL_STORAGE

If you are sure you reviewed the previous two items but still getting the error, this should be because of the android:maxSdkVersion="18" property inside the uses-permission tag. To allow your app to use the write permission above version 18 you need to remove maxSdkProperty.
<uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE"/>

My Fragment's overflow menu displays a menu item (settings) not in menu.xml

Fragments can add their own menu items by overriding onCreateOptionsMenu(). However this does not mean cleaning up the menu items added by the activity. Since a fragment is always hosted by activity and uses the activity's context, it would inherit such stuff from the hosting activity. The item which you believe (settings is given as the default menu item) is not relevant belongs to the activity. Navigate the menu.xml which belongs to the activity and remove the unwanted item(s).

The method replace or commit in the type FragmentTransaction is not applicable for the arguments 

You are passing a fragment object to a method which is expecting a fragment object but still complaining? Well, not all fragments are the same. Java's design allow classes with same names as long as they are in different packages. Android SDK team decided to introduce the fragment support package with the same class name (Fragment) but in a different package (android.support.v4.app.Fragment vs android.app.Fragment). Navigate to imports and remove the wrong import and add the appropriate one.

onOptionsItemsSelected(), onCreateOptionMenu(), afterTextChange(Editable s), onPostExecute() or any other method which should have been called is not called?!?

The @Override annotation must have been the most underrated annotation of all time. It exists for a very specific reason. Unlike C++ every method is virtual in Java. Thus, unless it is final any method can overriden. The @Override simply checks if the implementation is really overriding a method from the parent class. All the methods above has a typo which any level of developer may do. Removing the override annotation also removes the ability of the compiler to detect any typos in the so-called overriden methods. This typos may occur in the method or even in the parameter list. Simply if a listener or a method which should have been called will silently failed to be executed. You can easily detect such errors by placing the @Override to every overriding method.