Saturday, October 31, 2015

Globalization & RTL Mirroring - Android

Developers working with global applications which need to support languages including Arabic, Farsi, Hebrew etc will have considerations and issues with them in mirroring layouts to support these languages.

Layout Mirroring is a term used to describe the ability of software to reorder the UI elements to match the right to left flow for that locale. In Android with API 17, automatic layout mirroring was introduced.

RTL For Right-To-Left (RTL) languages like Arabic, not only does the text alignment and text reading order go from right to left, but also the UI elements layout should follow this natural direction of going from right to left. Of course, this layout change would only apply to localized RTL languages. Mirroring is in fact nothing else than a coordinate transformation:


  • Origin (0,0) is in the upper RIGHT corner of a window
  • X scale factor = -1 (i.e. x values increase from right to left 









To use layout mirroring  in android flag this support in the <application> element in android manifest file.

android:supportsRtl="true"

All the layouts "left/right" properties should be changed to "start/end" equivalents. For example android:paddingLeft will become android paddingStart. As this is clear from the coordinate transformation part described above. For supporting older versions (earlier to 4.2 ) the code should have both android:paddingLeft and android:paddingStart properties defined.

 Android 4.2 includes set of new APIs to help manage View components for RTL and LTR support. 
·        android:layoutDirection —  direction of a component's layout.
·        android:textDirection —  direction of a component's text.
·        android:textAlignment — alignment of a component's text.
·        getLayoutDirectionFromLocale() — method for getting the Locale-specified direction


  HierarchyViewer now lets to see start/end properties, layout direction, text direction, and text alignment for all the Views in the hierarchy.

References :



Sunday, September 27, 2015

Android Networking & Libraries – A closer look



When it comes to networking, there are many libraries in android which makes the calls faster, smoother and easier. I was in a research of finding the best or the best combination for a variety of projects/requirements. Here is a summary of my observations.

Why third party libraries over available system APIs?
·         Parallel execution of api calls
·         Most libraries has an ability to cancel/revoke networks calls.
·         Async interface to avoid main/UI thread blocking.
·         Retry policies
·         Json serialization
·         support SPDY, HTTP/2
·         Reuse of existing socket connections ( connection pooling )
·         Local response caching
·         Large bitmap handling/loading/ transformation

Design Patterns
According to the presentation by Virgis in 2010 Google I/O here , the networking design patterns to implement a rest client is
·         Service API
·         Content Provider API
·         Content Provider API and SyncAdapter
The gist is, to do work on a worker thread in which the life cycle is managed by service class. In case of network request which are not related to activity a sync adapter can be used.

Inside Android HTTP -  HttpURLConnection vs Apache HTTP
According to the official blog post , “Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool.” But due to the large size of APIs google was not ready to work on improving ApacheHttp client. For Gingerbread and above versions HttpUrlConnection was recommended and due to annoying bugs prior to Froyo , Apache HTTP client was the perfect choose.
Most developers used a legacy work around for the android http connections based on the API versions.
if (Build.VERSION.SDK_INT >= 9) {
HttpUrlConnection
                 }  else {
        // Prior to Gingerbread, HttpUrlConnection was unreliable.
       Apache - AndroidHttpClient.
    }

Okhttp by Square.inc
Square implemented OkHttp using the popular HttpUrlConnection and Apache client interfaces. Okhttp Engine includes HttpUriConnection and okApacheclient. According to this tweet by Jake Wharton , Okhttp became the engine that powers HttpUrlConnection in android 4.4.

Volley by Google
In Google I/O 2013, Google introduced Volley.
Everything in Volley sits on a top of HttpUrlConnection. Volley has special abstractions ImageRequest and JsonObjectRequest, which helps to automatically convert HTTP payload.
In certain cases OkHttp will perform better by utilizing more threads as volley has a hardcoded thread pool size (reference  ).
It is possible to use okhttp with volley using HttpStack implementation which uses OkHttp's request/response API instead of HttpURLConnection. (Reference)

Retrofit by Square.inc
Retrofit is one of the most elegant libraries around for created REST clients. An API can be implemented as an interface class, which contains java annotations to describe how a default RestAdapter will communicate with the API.
Retrofit provides a natural bridge between Java code and REST interfaces. It quicky turns HTTP API into Java interface and generates a self-documenting implementation
In addition, Retrofit also supports conversion to JSON, XML, protocol buffers.

Picasso by Square,  Fresco by Facebook and Glide
Picasso, on the other hand, provides an HTTP library for image-specific tasks.
Both Picasso and Retrofit configurable to use OkHttpClient as default HTTP client. However, we can specify a HttpURLConnection-based client if we needs. Glide is somewhat similar to Picasso. It provides additional features, such as GIF animations, thumbnail generation, and still videos.
Facebook recently open-sourced it's own image library Fresco that it uses in its Android client. One of key features that stands out is that Fresco's custom memory allocation strategy for bitmaps to avoid costly garbage collector operations in JVM heap and JVM per-app memory limits.

The HTTP transport component is interchangeable for higher level libraries ( Retrofit/picasso/Fresco/Glide/Volley ). It is possible to choose between plain HttpUrlConnection or the latest OkHttpClient.






Monday, August 17, 2015

Background tasks : RoboSpice vs Volley – my choice of choosing RoboSpice


Robospice is an open source library that eases writing async network requests. It executes requests inside an android service. It is service based and more respectful of Android philosophy than Volley. Volley is thread based and this is not the way background processing should take place on Android. Ultimately, we can dig down both libs and find that they are quite similar, but our way to do background processing is more Android oriented, it allow us, for instance, to tell users that Robospice is actually doing something in background, which would be hard for volley ( actually it doesn't at all ).
RoboSpice and volley both offer nice features like prioritization, retry policies, request cancellation. But Robospice offers more : a more advanced caching, with cache management, request aggregation, more features like repluging to a pending request, dealing with cache expiry without relying on server headers, etc.
RoboSpice does more outside of UI Thread : volley will deserialize the POJOs on the main thread, which is horrible to my mind. With Robospice your app will be more responsive.
In terms of speed, we definitely need metrics. Robospice has gotten super fast now, but still we don't have figure to put here. Volley should theoretically be a bit faster, but Robospice  is now massively parallel.
RoboSpice offers a large compatibility range with extensions. You can use it with okhttp, retrofit, ormlite , jackson, jackson2, gson, xml serializer, google http client, spring android... Quite a lot. Volley can be only used with ok http and uses gson.
Volley offers more UI sugar. Volley provides NetworkImageView, Robospice does provide a spicelist adapter. In terms of feature it's not so far, but I believe Volley is more advanced on this topic.
More than 200 bugs have been solved in RoboSpice since its initial release. It's pretty robust and used heavily in production. Volley is less mature but its user base should be growing fast (of course because it’s a google product).

Volley roughly competes with Retrofit + RoboSpice. On the plus side, it is one library. On the minus side, it is one undocumented, unsupported.
Go for RS anytime, All others are a joke ;)
References :
  • http://wiki.neerad.com/wiki/Android/Using_Robospice_with_Retrofit
  • https://github.com/stephanenicolas/robospice/wiki/Retrofit-module
  • https://groups.google.com/forum/#!topic/robospice/QwVCfY_glOQ


Thursday, July 9, 2015

Stay Hungry. Stay Foolish - Steve Jobs' 2005 Stanford Commencement Address





I encourage many others to watch this, just takes this 15 minutes to change your life.
"Sometimes life hits you in the head with a brick. Don't lose faith. I'm convinced that the only thing that kept me going was that I loved what I did. You've got to find what you love...."
Stay stronger... cheerios!

prepared text [ from .stanford.edu ]

I am honored to be with you today at your commencement from one of the finest universities in the world. I never graduated from college. Truth be told, this is the closest I've ever gotten to a college graduation. Today I want to tell you three stories from my life. That's it. No big deal. Just three stories.
The first story is about connecting the dots.
I dropped out of Reed College after the first 6 months, but then stayed around as a drop-in for another 18 months or so before I really quit. So why did I drop out?
It started before I was born. My biological mother was a young, unwed college graduate student, and she decided to put me up for adoption. She felt very strongly that I should be adopted by college graduates, so everything was all set for me to be adopted at birth by a lawyer and his wife. Except that when I popped out they decided at the last minute that they really wanted a girl. So my parents, who were on a waiting list, got a call in the middle of the night asking: "We have an unexpected baby boy; do you want him?" They said: "Of course." My biological mother later found out that my mother had never graduated from college and that my father had never graduated from high school. She refused to sign the final adoption papers. She only relented a few months later when my parents promised that I would someday go to college.
And 17 years later I did go to college. But I naively chose a college that was almost as expensive as Stanford, and all of my working-class parents' savings were being spent on my college tuition. After six months, I couldn't see the value in it. I had no idea what I wanted to do with my life and no idea how college was going to help me figure it out. And here I was spending all of the money my parents had saved their entire life. So I decided to drop out and trust that it would all work out OK. It was pretty scary at the time, but looking back it was one of the best decisions I ever made. The minute I dropped out I could stop taking the required classes that didn't interest me, and begin dropping in on the ones that looked interesting.
It wasn't all romantic. I didn't have a dorm room, so I slept on the floor in friends' rooms, I returned Coke bottles for the 5¢ deposits to buy food with, and I would walk the 7 miles across town every Sunday night to get one good meal a week at the Hare Krishna temple. I loved it. And much of what I stumbled into by following my curiosity and intuition turned out to be priceless later on. Let me give you one example:
Reed College at that time offered perhaps the best calligraphy instruction in the country. Throughout the campus every poster, every label on every drawer, was beautifully hand calligraphed. Because I had dropped out and didn't have to take the normal classes, I decided to take a calligraphy class to learn how to do this. I learned about serif and sans serif typefaces, about varying the amount of space between different letter combinations, about what makes great typography great. It was beautiful, historical, artistically subtle in a way that science can't capture, and I found it fascinating.
None of this had even a hope of any practical application in my life. But 10 years later, when we were designing the first Macintosh computer, it all came back to me. And we designed it all into the Mac. It was the first computer with beautiful typography. If I had never dropped in on that single course in college, the Mac would have never had multiple typefaces or proportionally spaced fonts. And since Windows just copied the Mac, it's likely that no personal computer would have them. If I had never dropped out, I would have never dropped in on this calligraphy class, and personal computers might not have the wonderful typography that they do. Of course it was impossible to connect the dots looking forward when I was in college. But it was very, very clear looking backward 10 years later.
Again, you can't connect the dots looking forward; you can only connect them looking backward. So you have to trust that the dots will somehow connect in your future. You have to trust in something — your gut, destiny, life, karma, whatever. This approach has never let me down, and it has made all the difference in my life.
My second story is about love and loss.
I was lucky — I found what I loved to do early in life. Woz and I started Apple in my parents' garage when I was 20. We worked hard, and in 10 years Apple had grown from just the two of us in a garage into a $2 billion company with over 4,000 employees. We had just released our finest creation — the Macintosh — a year earlier, and I had just turned 30. And then I got fired. How can you get fired from a company you started? Well, as Apple grew we hired someone who I thought was very talented to run the company with me, and for the first year or so things went well. But then our visions of the future began to diverge and eventually we had a falling out. When we did, our Board of Directors sided with him. So at 30 I was out. And very publicly out. What had been the focus of my entire adult life was gone, and it was devastating.
I really didn't know what to do for a few months. I felt that I had let the previous generation of entrepreneurs down — that I had dropped the baton as it was being passed to me. I met with David Packard and Bob Noyce and tried to apologize for screwing up so badly. I was a very public failure, and I even thought about running away from the valley. But something slowly began to dawn on me — I still loved what I did. The turn of events at Apple had not changed that one bit. I had been rejected, but I was still in love. And so I decided to start over.
I didn't see it then, but it turned out that getting fired from Apple was the best thing that could have ever happened to me. The heaviness of being successful was replaced by the lightness of being a beginner again, less sure about everything. It freed me to enter one of the most creative periods of my life.
During the next five years, I started a company named NeXT, another company named Pixar, and fell in love with an amazing woman who would become my wife. Pixar went on to create the world's first computer animated feature film, Toy Story, and is now the most successful animation studio in the world. In a remarkable turn of events, Apple bought NeXT, I returned to Apple, and the technology we developed at NeXT is at the heart of Apple's current renaissance. And Laurene and I have a wonderful family together.
I'm pretty sure none of this would have happened if I hadn't been fired from Apple. It was awful tasting medicine, but I guess the patient needed it. Sometimes life hits you in the head with a brick. Don't lose faith. I'm convinced that the only thing that kept me going was that I loved what I did. You've got to find what you love. And that is as true for your work as it is for your lovers. Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it. And, like any great relationship, it just gets better and better as the years roll on. So keep looking until you find it. Don't settle.
My third story is about death.
When I was 17, I read a quote that went something like: "If you live each day as if it was your last, someday you'll most certainly be right." It made an impression on me, and since then, for the past 33 years, I have looked in the mirror every morning and asked myself: "If today were the last day of my life, would I want to do what I am about to do today?" And whenever the answer has been "No" for too many days in a row, I know I need to change something.
Remembering that I'll be dead soon is the most important tool I've ever encountered to help me make the big choices in life. Because almost everything — all external expectations, all pride, all fear of embarrassment or failure — these things just fall away in the face of death, leaving only what is truly important. Remembering that you are going to die is the best way I know to avoid the trap of thinking you have something to lose. You are already naked. There is no reason not to follow your heart.
About a year ago I was diagnosed with cancer. I had a scan at 7:30 in the morning, and it clearly showed a tumor on my pancreas. I didn't even know what a pancreas was. The doctors told me this was almost certainly a type of cancer that is incurable, and that I should expect to live no longer than three to six months. My doctor advised me to go home and get my affairs in order, which is doctor's code for prepare to die. It means to try to tell your kids everything you thought you'd have the next 10 years to tell them in just a few months. It means to make sure everything is buttoned up so that it will be as easy as possible for your family. It means to say your goodbyes.
I lived with that diagnosis all day. Later that evening I had a biopsy, where they stuck an endoscope down my throat, through my stomach and into my intestines, put a needle into my pancreas and got a few cells from the tumor. I was sedated, but my wife, who was there, told me that when they viewed the cells under a microscope the doctors started crying because it turned out to be a very rare form of pancreatic cancer that is curable with surgery. I had the surgery and I'm fine now.
This was the closest I've been to facing death, and I hope it's the closest I get for a few more decades. Having lived through it, I can now say this to you with a bit more certainty than when death was a useful but purely intellectual concept:
No one wants to die. Even people who want to go to heaven don't want to die to get there. And yet death is the destination we all share. No one has ever escaped it. And that is as it should be, because Death is very likely the single best invention of Life. It is Life's change agent. It clears out the old to make way for the new. Right now the new is you, but someday not too long from now, you will gradually become the old and be cleared away. Sorry to be so dramatic, but it is quite true.
Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma — which is living with the results of other people's thinking. Don't let the noise of others' opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.
When I was young, there was an amazing publication called The Whole Earth Catalog, which was one of the bibles of my generation. It was created by a fellow named Stewart Brand not far from here in Menlo Park, and he brought it to life with his poetic touch. This was in the late 1960s, before personal computers and desktop publishing, so it was all made with typewriters, scissors and Polaroid cameras. It was sort of like Google in paperback form, 35 years before Google came along: It was idealistic, and overflowing with neat tools and great notions.
Stewart and his team put out several issues of The Whole Earth Catalog, and then when it had run its course, they put out a final issue. It was the mid-1970s, and I was your age. On the back cover of their final issue was a photograph of an early morning country road, the kind you might find yourself hitchhiking on if you were so adventurous. Beneath it were the words: "Stay Hungry. Stay Foolish." It was their farewell message as they signed off. Stay Hungry. Stay Foolish. And I have always wished that for myself. And now, as you graduate to begin anew, I wish that for you.
Stay Hungry. Stay Foolish.
Thank you all very much.


Tuesday, April 7, 2015

Software Engineering process, Google way


Geeky Fairytales: Software Engineering process, Google way: By: Simon Wingrove ( http://www.simonwingrove.com )

We often get questions along the lines of “what is the development process at Google?” – meaning the secret sauce which allows project to magically happen and launch on time. There is an abundance of articles and blog posts which describe how Google does things, and probably some of them are right! The truth is, however, that a process that works for one group of smart people will not necessarily work for another. This is why there’s simply no such thing as “the” development process at Google.  Most teams will adopt the approach that suits them best.
Establishing the process for a team is usually not something that happens “because the manager said so” – frankly, engineers have far more say in the matter.  When our team (Google Play for work) realised it was growing to the point where it needed to formalise its practices, the engineers stepped up and self-organised to make it happen.
The cornerstone of any development process is the goal: what are we trying to achieve here? We want to be able to answer a few fundamental questions at any moment in time.
  • Are we on track to deliver?
  • What features are we currently working on?
  • Can we take on more work now and still meet our deadlines?
Engineers are best placed to estimate the complexity of engineering problems, so making sure we can always answer these questions is an engineer-driven process.
Objectives and Key Results – achievable and measurable goals
Across all of Google we use Objectives and Key Results (OKRs). Every team, product area and even the company as a whole has them. OKRs are defined quarterly by the product and engineering managers, with input from the wider team on specific technical questions.

OKRs must be well-defined and measurable – so “Improve UI latency” is not a good OKR while “Frontend latency must be below 500ms for 90th percentile” can be measured. OKRs are given a complexity estimation: in our team we use T-Shirt size. This estimation is rough, but allows managers to make a basic estimate of what can be achieved in a quarter.
User stories and backlog grooming
Our team uses a “sprint” based approach to development, with sprints of two weeks. We maintain a “backlog” of work to be done. We regularly meet as a team to groom the backlog.  In this process we take OKRs and split them into “user stories”: increments of product function that could be delivered in a single sprint and provide value to the end user. We estimate the size of the stories as best we can, and order the stories on the backlog into a strict priority order.
We often use planning poker to estimate the size of a user story - ideally every team member gives his estimate how long this story will take, and if there are significant disagreements they are discussed until common ground is reached. This approach helps clarify requirements, and means that everyone on the team has at least some degree of understanding of the problems the team are working on.
Sprint planning
At the beginning of every sprint we hold a sprint planning meeting.  The goal of sprint planning is to pull user stories from the prioritized backlog and commit as a team to delivering them in the sprint. This session is attended by all engineers as well as the product owner/manager. The end result of sprint planning is that we have committed to delivering a set of user stories, and stories are split into sub-tasks (each no longer than a day of work) assigned to owners. Usually engineers “claim” either whole user stories or specific subtasks.
The ideal outcome of a sprint is a potentially shippable increment of product function that provides additional value the end user.
Story tracking and daily stand-ups
To know where are we while the sprint is running it’s crucial for engineers to mark their progress on specific sub-tasks. When engineer starts working on something, they “accept” the sub-task, and when finished they mark it as fixed. To catch problems as early as possible we have a daily stand-up at 12:30. In the stand-up engineers give
  • a brief explanation of what they’ve done since yesterday’s stand-up, and what they will do before the next stand-up
  • whether they are on target for the sprint
  • whether they have any concerns or blocking problems.
If anything looks like it may slip, we arrange to take remedial action that day.  Ideally we reassign tasks so that the sprint goals can still be met.  If this isn’t possible, we punt the least critical item from the sprint and then rearrange tasks.
Sprint review and retrospective
We end the sprint with two short meetings, the review and the retrospective, which we usually hold together accompanied by drinks and pizza. (After all, what’s software engineering without pizza? :-)).
We tidy-up all our tasks and stories, and look at what we did and did not deliver in the sprint. We also demo to each other, and the product owner, the cool new features we developed in the sprint so that everyone knows where the product is.
Google famously has a “launch and iterate” approach to products, and we have the same approach to our development process.  It is really hard to get everything 100% perfect, and we constantly re-evaluate our progress. During the retrospective meeting, we discuss what went right and what didn’t. Sometimes features slip because of something outside of our control. Sometimes things take longer than we expected, and occasionally we decide to change direction entirely to improve the product.
The most important thing is to make our product high quality and useful to the user, and not to encourage the development team to “meet their target” by shipping a low quality product.  It is therefore important to keep this meeting focussed on constructive feedback, and ways to detect issues quickly, rather than pretending that we can see the future and never make any mistakes.

Wednesday, July 24, 2013

Android 4.3, updated developer tools, and backwards compatible Action Bar Available Now



I should say thank you ActionBar Sherlock for being a great tool while Google worked on this! :-) 
Let's all take this moment to shout out and thank Jake Wharton for supporting ABS for so long.

Android 4.3, a sweeter version of Jelly Bean, includes performance enhancements to keep your apps fast, smooth, and efficient; together with new APIs and capabilities including:

* OpenGL ES 3.0 Take advantage of OpenGL ES 3.0 and EGL extensions as standard features of Android, with access from either framework or native APIs.

* Bluetooth Smart Communicate with low-power Bluetooth Smart devices and sensors to provide new features for fitness, medical, location, proximity, and more.

* Restricted profiles Tablet owners can create restricted profiles to limit access to apps, for family, friends, kiosks, and more. Your app can offer various types of restrictions to let tablet owners control its capabilities in each profile.

* New media capabilities A modular DRM framework enables you to more easily integrate DRM into your streaming protocols, and apps can also access a built-in VP8 encoder from framework or native APIs for high-quality video capture.

* Notification access: Access and interact with  the stream of status bar notifications as they are posted — including routing them to nearby Bluetooth devices!

* Improved profiling tools New tags in Systrace, and on-screen GPU profiling, give you new ways to optimize performance.

We’re also releasing a new version of the Android NDK (r9), which provides native access to the OpenGL ES 3.0 APIs and other stable APIs in Android 4.3. 

The Support Package has also been updated with the long awaited Action Bar API that lets you include this Android design pattern in your app with compatibility back to Android 2.1. 

You can download the Android 4.3 Platform (API level 18), as well as the SDK Tools, Platform Tools, and Support Package from the Android SDK Manager.

Android 4.3 powers the new Nexus 7 tablet and is rolling out now as an update to Nexus 4, Nexus 7, Nexus 10, and Galaxy Nexus HSPA+ devices.


Links:
Android 4.3 APIs
http://android-developers.blogspot.in/2013/07/android-43-and-updated-developer-tools.html
http://officialandroid.blogspot.in/2013/07/introducing-android-43-sweeter-jelly.html

Sunday, May 5, 2013

JavaScript: The Good Parts - An awesome book by an extraordinary man

Couple of weeks ago I was looking for some book recommendations , videos etc on advanced JavaScript things. I've been programming for a decent period of time, so I didn't need a book that spends 4 pages on for loops. I was googling on this and everywhere I ended up with this man's name Douglas Crockford.

I ordered his "JavaScript : The Good Parts ", started reading it. And I felt, I'm late to read it. I would say, it is a must have JS book. Small one but dense.

This book is a compact form of only the most elegant, beautiful and good parts of JavaScript. Its quite unbelievably compact yet maintains the sense of usefulness. The topics covered would help an intermediate or an expect become a "Guru" of JavaScript. The "railroad" diagrams used in this book truly explain the concepts very well. This book also has the best reference for the "JSLint" tool. All in all "Douglas Crocford" has done an excellent job at helping improve the JavaScript programmer in me by emphasizing using the
"Good Parts" and avoiding the "Bad Ones".

The author, Douglas Crockford, has been continuously involved in the development of the JavaScript language. With an insider’s perspective, he reveals that JavaScript has more than its share of bad parts due to its premature, and therefore unrefined release. He goes on to stress that superseding all the unrefined, not-so-great features is a set of good, reliable ones that can be used to develop truly efficient code. He compares the unfortunate mix of good and bad ideas to a programming model that functions on global variables.

Crockford insists that by thoroughly understanding the positive, elegant aspects of JavaScript and forgetting the negative, inefficient methods, the readers can uncover a beautiful and expressive language for building great code.

The book is aimed at anyone and everyone who develops applications or sites for the Web. It is divided into ten chapters. It begins with an overview of the good features in JavaScript. Subsequent chapters cover concepts like grammar, functions, objects, inheritance, arrays, and regular expressions. The book ends with a set of five appendices that provide added information such as the negative features of Javascript, Syntax Diagrams, JSLint, and JSON.

Yes, beyond any questions the best books/ videos available on JavaScript are from Douglas Crockford. He is inspirational and extraordinarily rewarding to watch and listen to.

Monday, January 7, 2013