Thread-safe array in Java

Here is the template class to demonstrate the Thread-safe Array which can store any Java Object Type

Tools to Reverse Engineer Android APK

Here is the list of compiled tools that may be used to reverse engineer an Android APK. None of them are discovered by me. Rather I found these through stack overflow and other blogs while trying reverse engineer an Android APK, where I had to find out an issue with no source code available.

 The credits have been added in comments.

Hope this Helps.

 

Credits:

http://blog.shvetsov.com/2013/02/access-android-app-data-without-root.html

 http://stackoverflow.com/a/11133263/623569

http://stackoverflow.com/a/18132934/623569

Android: Turning Flash ON/OFF

After playing with Android OS and messing with different IDE like Eclipse, IntelliJ, I finally settled down with Android Studio for Android App development. I definitely found it useful for the beginners who had no exposure of Java or Eclipse world.

With the newly found Euphoria, I thought I should start of with Simple Android program, Playing with Flash Light on Android Devices. But, It turned out to be not so straight forward, after following the developer documents. It once again proved that, the fragmentation issue Android was facing, where the solutions on stack overflow when you quickly search “Flash Light API in Android” look so obvious, but does not work on most of the devices

Here I am sharing the one which I got to work on Google Nexus 5, Android Lollipop. The Key here is to use setPreviewTexture() method on Camera object. 

Hope you find it useful.

 

Distributing iOS Static Library via CocoaPods

I was new to cocoa pods and looked at their documentation on how to create a pod and distribute. They mainly focused on examples that involved distributing source files rather than a pre-built iOS static library. Hence I want to make a short post on how the pod spec looks like if you are shipping an iOS static library via Cocoapods.

This post does not list steps on creating pod spec and uploading it to the master repo. I will rather provide links which helped me doing that. Please read through if you already know what is cocoa pods and you have an iOS static library which you need to distribute through Cocoa pods.

If you ended up this page as a newbie to cocoa pods, don’t worry.  Refer the following links and come back.

For information on how to consume cocoa pods as well as how to create one, I found this blog very helpful – http://nshipster.com/cocoapods/

I strongly recommend to test your pods locally before pushing things to master cocoa pods repo: here is how you do that http://www.cocoanetics.com/2013/05/8130/

Assuming you are all setup with your pod specs, below are the attributes of pod spec which is vital in distributing iOS Static library

s.source_files : Specify which files need to be copied. In our case, we need to copy the the Calculator.h header file. The value of the source_file attribute is the relative path of the location of header file from the Podspec location.

s.public_header_files = Specifies the header files to include and search for. Value is the relative path of the header files and the path will be added to User Header file search path in the Xcode build settings.

s.library = the Libraries to link with in order for the static library to compile successfully. In our example, the library requires the stdc++ library. The value is the library name without appending lib as prefix. For e.g., stdc++. If you have multiple libraries as dependency, provide them as a comma separated values.

s.framework = List of frameworks that the library is dependent upon. As every project by default is linked with UIKit, Foundation, You can specify any other frameworks as a comma separated values.

s.preserve_paths = We need to specify the files to be copied during the installation. In our example we need to explicitly copy our libCalculator.a file after installation onto the clients system. The value of this attribute would be the relative path ( from the PodSpec)  of the files to be copied.

s.requires_arc = The value is either true or false. Since our example project supports ARC, we set it as true

s.ios.vendored_library = Specify the library, libCalculator.a to be copied while installing the pod

Additional attributes that might come in handy

s.dependency = Reference to another pods, where the library is dependent upon. For the simplicity of the example, I have not included any libraries as dependents.

s.xcconfig = There would be other build settings, for which there are no corresponding  attributes in Podspec. In such cases, you can use xcconfig to specify the build settings directly.

For example, to set the HEADER_SEARCH_PATH build settings you can specify them in a json style like

{ “HEADER_SEARCH_PATH” => “$(SDKROOT)/usr/include/libxml2“}

Here is the final PodSpec

Pod::Spec.new do |s|

s.name = “CalcLib”
s.version = “1.0”
s.summary = “Example iOS Static Library – Calculator. ”

s.description = <<-DESC
This iOS Static library is used to explain how to distribute iOS Static library via cocoapods
DESC

s.homepage = “https://github.com/bharath2020/CalcLibrary/blob/master/README.md”
s.license = { :type => “BSD”, :file => “LICENSE” }

s.author = { “Bharath Booshan” => “bharath2020@gmail.com” }
s.social_media_url = “http://twitter.com/bharath2020″

s.platform = :ios, “6.0”
s.source = { :git => “https://github.com/bharath2020/CalcLibrary.git”, :tag => s.version.to_s}
s.source_files = “include/*.h”
s.public_header_files = “include/*.h”

s.preserve_paths = “libCalculator.a”
s.ios.vendored_library = “libCalculator.a”

s.libraries = “stdc++”, “Calculator”
s.requires_arc = true
end

Test this Sample

I have created a test library named Calculator which calculates a^2 + b^2 + 2ab for a given values a and b. For demonstration purposes, i have internally used c++ class to perform addition and multiplication. This is to demonstrate how to supply additional dependent libraries in the pod spec file.

Here is the github link : https://github.com/bharath2020/CalcLibrary

To test the library with an example project, add below line to your pod file

 

pod ‘CalcLib’

and execute pod install or pod update

 

You can insert the following code in your example project for verification

Calculator *calci = [[Calculator alloc] init]

int result = [calci APlusBWholeSquare:2 andB:3]

 

Here are few references who distributes iOS Static library via cocoa pods:

https://developers.helpshift.com/ios/cocoapods/

https://github.com/Ancestry/CocoaPod-Specs/blob/master/AdamSDK/2.1.0.1/AdamSDK.podspec

 

Hope this Helps.

longLongValue issue in NSDecimalNumber

Problem: A legacy module in current project involved JSON parsing where SBJSONParser was being used. While doing performance analysis, we found out that SBJSONParser was contributing to 50% to the load time of the module. The benchmarks done here ( https://github.com/bontoJR/iOS-JSON-Performance  )  convinced us to use NSJSONSerialization, a native JSON parse in iOS 5.0 and above. Things went smooth except with the change except for the below issue

 

We were using 64bit number to represent primary key.  NSJSonSerialization used NSDecimalNumber for representing numbers, while SBJSONParser used NSNumber to represent numbers. 

 

With NSDecimalNumber, a number returned from its description or stringValue method found to be different from the value returned by longLongValue  method implementation by NSDecimalNumber.

 

For eg: 3924849704573025603 = 3924849704573025792

 

The reason is well explained here  http://stackoverflow.com/a/12421451/623569

 

The problem is that an exact value of an NSDecimalValue is only representable as … anNSDecimalValue.

You can get an approximate 64 bits IEE754 value with method doubleValue. When you try to use longLongValue you effectively get the result of casting to a long long int the approximate IEE754 value.

 

Many of the modules in our project were using longLongValue, means that we had no choice to do a Find and Replace in the source as application using this module was out in market used by many clients and the value was stored in the database.

 

 

How do I make sure the longLongValue of NSDecimalNumber be consistent with its stringValue method?

 

Solution: 

Categories in our Objective-C comes to our rescue.

By creating a Category of NSDecimalNumber and re-implementing longLongValue. this new implementation will convert the number to string using stringValue and return number of type long long using longLongValue method. Since, NSString uses NSNumber to make the conversion, the final value returned by longLongValue is equal to value obtained through stringValue method in NSDecimalNumber.

 

@implementation NSDecimalNumber (unsignedLongLongBug)

- (long long)longLongValue

{

    return [[selfstringValue] longLongValue];

}

@end

 

A point to note here is that we are not interested in the correctness of the value in our case, rather we are trying to make the results consistent as I am only looking for the number to be unique and not using the result for any calculation. 

 

 

A word of CAUTION: Using a method in category to replace Primary class’s implementation may have unknown impact in case if there is a second category which implements the same method. In real word it depends on order in which the category is loaded and always the the method is replaced by the last category to be loaded.

 

 

Git – Basic Terminal Commands Checklist

I was observing a lot of traction from the developer community about the Git and Github and last year I got a chance to use the Git, majorly because of the woes we had using SVN ( subversion ) as our source control  in our team where most of the members are working remotely. I was amazed to see the power of Git but the learning curve was very steep, especially if you are a long time SVN user. I chose to use terminal commands to operate Git instead of a GUI tool so that it would help me know how Git operates behind the scenes which is masked by many GUI tools out in the space.

I started preparing an Appendix of commands of myself which I would use on a daily basis and most of my usage of commands are recorded in this list. Since, Its been close to year where I have made this checklist and updated as I found new usage scenarios, I thought i would share this back to community and to the newcomers who are entering into Git world, to make their Git transition smoother.

IMPORTANT NOTE:

  • I assume that the readers / users of this checklist  have the conceptual details on how who Git operates.
  • I always referred remote repository as origin ( as most of the time I used only single repository and git names it as ‘origin’ by default ).
  • I have most of the times tested these commands in Mac OS X 10.8, however I would assume you know why you are using these commands and I would not be responsible for any data loss resulting from usage of these commands.

I have organized the following commands based on the usage scenarios:

1. Basic Update and Commit 

   a. Check the status of git  

git status

   b. Adding Files

git add <filename>

OR

git add <regular expression>

    c. Commit – only updates the Local repository and does not push to the cloud

git commit -am “Commit Message”

git commit -m “Commit message” <filename> 

    d.  Update to remote repository

git push <remote name> <branch>

By Default <remote name> would be origin, if no branch is specified, then it will be pushed to master.

 

2. Remove from staging == remove from svn tracking

git rm -r –cached <file path>

 

3. Git Branch 

 a. Creating a branch

git branch <branch_name>

OR

git checkout -b  <branch_name>

 

b. List all branches

git branch 

c. List all branches in remote repository

git branch -r

OR

git fetch && git branch -r

 

d. Merging a branch

 

1. To commit and push all the changes made in this branch to remote

//Commit all the modified files


 git commit -am “<Commit message>”   

git push origin <branch name>

   

2. Switch to destination branch where u need to merge your changes. 

For eg. If you want to merge in Feature 1 in master branch, then switch to master by ‘git checkout master

 

git merge <branch_name>

git merge –no-ff <branch_name>

 

c. Deleting a branch in local repository

git branch -d <branch name>

 

d. Deleing a branch forcefully on local repository

git branch -D <branch_name>

e. Deleting a branch on remote repository

git push <remote> :<branch _name>

f. Download a branch from the repository 

 (sometimes you need to execute ‘git fetch’ command before executing this command )

git checkout -t origin/<branch-name> 

4. Ignore New Files or Never track

- Place .gitignorefile in Git root directory

- Add the file path or wilde cards for e.g.,  *.xcodeuserstate entry for example using vi editor or any text editor. You can add each file to be ignored in a new line

- save the .gitignore file

- this will take effect only to the new files. if you want to ignore an existing file. do a git rm –cached <filename> and follow the above steps.

Please let me know through comments in this blog if there are any faulty usage of these commands, so that I could rectify it.

I will try to update this post as and when I find some new commands. Please let me know if you find this useful.

Happy Coding :)

Why I like Blocks?

In my last post here , I wrote about the syntactical difference between the Blocks and the C Funtion pointers. In this post I share my first hand experience on Blocks and how it changed my programming style and thinking, especially if you are not from Java / Javascript world.

 

In simple terms, Blocks are tiny independent code blocks that could be executed on its own. How did Blocks saved me? Lets take below code snippet as an example:

 

[imageDownloader downloadHUGEImage: ^(UIImage* newImage){

    [self createThumbNailForImage:(UIImage * newImage)];

}]

 

v/s

 

[imageDownloader setDownloadDelegate: self ];

[imageDownloader downloadHUGEImage];

..

..

.

 

- (void)imageDownloader:(BBImageDownloader*)downloader didDownloadImage:(UIImage*)image

{

    [self createThumbNailForImage:(UIImage * newImage)];

}

 

Advantage #1: It added more readability to my code:

Everyone would know what we are exactly doing after downloading an image, where as with delegate pattern, one has to jump to definition of the delegate methods, which sometimes resides in multiple files, by then you would lose the trace of the initial method.

 

Advantage #2: Eliminates Delegate Pattern

The same reason as above, With Blocks, you will no more have to spend your time in retain cycle which is more common mistake made by programmer when using delegate pattern in Objective-C, (although blocks do produce retain cycles, but they are easy to detect   )

 

 

Advantage #3: Save more context info variables.

Lets take an example of usage of beginAnimation: method on UIView in Pre-Block Era.

int state_before_animation = 0

[UIView beginAnimations:@” ” contextInfo:& state_before_animation]

 

..

 

..

 

- (void)animations:(NSString*)animation didFinish:(BOOL)finish contextInfo:(void*)contextInfo

{

    //do some

int *state_before_animation = (int*)contextInfo

//change state depending upon state_before_animation

}

 

 

- During the execution time between start of animation  and completion of animation, we lose the scope of local variables that were available at the start. This made the necessity of carrying these variables in the form of contextInfo

 

- It increases the burden of maintaining the integrity of the contextInfo variable during this time, it travels between different modules and sometimes b/w the third party libraries. 

 

With blocks, it makes much more simpler to write:

 

int state_before_animation =0

[UIView animateWithDuration:0.9 beforeAnimation:^{

 

}

afterAnimation:^{

   //do something depending upon state_before_animation

}

];

 

 Isn’t it decreases your development time?

 

Happy Coding :)

UITableView Tricks – Part 2 – Infinite Scrolling

Last time I posted about the UITableView Tricks to lay the cells of the tablview in Circular fashion. It was well received by the community and thank you all for your feedback and compliments. 

I received many requests for making this circular list scroll infinitely as with UIPickerView, which means that the list repeats forever. It really makes sense just because the list itself is in circular fashion and user expect the content to repeat, without him/her having to scroll back to top.

I came across the 2011 WWDC video – Advanced Scrollview Techniques which provides the best feasible solution to support infinite scrolling. Many attempts have been made before to find a solution by having the height of the scrollview’s content size to a large number so that it takes days, if not AGES for a user to get to the end point. But it was never a complete solution.

 

I went a bit closer to the perfect solution and here it is. The goal here is to provide a generic solution to a UITableView while having the user/ developer to do minimum or ZERO changes. This lead me to create a subclass of UITableView, and named as BBTableView

 

By using BBTableView,  a developer has to do ZERO changes ( some minor changes for additional functionality, explained later ) to enable infinite scrolling. 

 

Behind the scenes:

 

 The core logic of this solution is

 

1. To increase the tableview content by a factor of 3, so that we make the 3 copies of the content laid one after another vertically. 

2. Whenever the top end of the scroll is reached, move the the scroll offset back to start of the 2nd copy

3. When the bottom end of the scroll is reached, we move the scroll offset back to the start of the 2nd copy minus the height of the tableview, so that we end up showing the same content as we are now.

Infinite Scrolling

This solution did bring an obstacle to my goal of making this component as a Drag-n-Drop component. i.e. Making 2 additional copies of rows provided by datasource also changes the index paths used in datasource or delegate methods that are propagated to the component user, a developer who would use this component.

This can be avoided by intercepting the delegate or datasource methods to morph the index paths exchanged between the UITableView and the its datasource or delegate methods.

Thanks Evadne Wu , for allowing me to use the interceptor component written by her.

Two  properties have been added to BBTableView,

a. contentAlignment

Allows the change the direction of the semi-circle. It supports two directions


ClockWiseScreen Shot 2012 12 07 at 9 25 33 PM

eBBTableViewContentAlignmentRight - Layouts the circle Clockwise

eBBTableViewContentAlignmentRight – Layouts the circle Anti-Clockwise

b. enableInfiniteScrolling

    set YES to enable infinite scrolling. NO to reset to default scrolling behavior of UITableView

 

As every software, this component too have its Cons:

1. Since the issue with Index Paths resolved by intercepting delegate / datasource methods, Any additions or modifications to UITableView datasource/ delegate methods involving index path, requires a change to counterpart datasource / delegate methods implemented in BBTableView. However, on a good note, this change includes only getting the morphed index path and calling appropriate method on the receiver of Datasource interceptor.

A  sample intercepted Datasource method would look like:

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [_dataSourceInterceptor.receiver tableView:tableView cellForRowAtIndexPath:MORPHED_INDEX_PATH(indexPath)];

}

 

Check the source code updated in github here https://github.com/bharath2020/UITableViewTricks

Happy Coding :)

Blocks Syntax and its Variants

This post is specifically to me. I am not sure why I am not able to remember this simple syntax of the passing blocks as parameter.

 

So here it is.. Its very similar to C function pointers

<return type> (* [<function pointer name>])( [parameter1, parameter2….])

The only difference is to replace * to ^.  <function pointer name> is name of the block, Lets call its as as <block name>.  if you are using this directly to pass a block as  a parameter to a method, then the <block name> is not needed.

 

For Example, You declare a method which accepts a block as a parameter like this:

-(void)performLongOperation:( void (^)(NSError *error, id result))completionBlock;


Variants of Creating and Defining a Block


a. Block definition as part of method invocation:

 

One would invoke the block within the performLongOperation method definition as:

NSError * error = nil;

id result = nil;

..

..

..

completionBlock(error, result );

The caller would look like:

  [self performLongOperation: ^(NSError *error, id result){

        //what you want to do after performLongOperation?

    }];

This is one of the way where the whole body of the block is written as part of method invocation.

 

 

b. Block as a variable OR a named Block:

 

If the above code snippet looks complicated (esp. if the callback is very lengthy) or if there is a need to separate the callback from the caller, then you can give a name to a block like this:

  void (^ myblock )(NSError *, id result)  = ^(NSError *error, id result){

        //what you want to do after performLongOperation?

    };

where myblock is the name of the block. The method invocation would look like:

    [self performLongOperation: myblock];


c. Block as a custom data type


In some cases, we might want to pass a different callback functions based on certain conditions and in order to do that we can create our own custom data type using typedef.

typedef void (^my_block_type)(NSError *, id );

and create a block variable of type my_block_type which accepts two parameters of type NSError and id and returns nothing.

my_block_type validate_long_operation_result = ^(NSError *error, id result){

        //validate result

    };

 

my_block_type divert_to_second_operation = ^(NSError *error, id result){

        //do second operation

    };

Caller would look like this:

[self performLongOperation: ( should_chose_second_operation ? divert_to_second_operation :  validate_long_operation_result)];

 

Click Me for More Info on Basics of Blocks


Happy Coding :)


WWDC: Steve Jobs v/s Tim Cook

The Wait is over, but the excitement is still there. Yes, Its about the WWDC 2012 and surely its may not be the best of 23 WWDC conferences, but it did not disappoint either. Am sure you can find a lot of info on it here at Engadget WWDC 2012 Live Blog.

 

So, We can never leave the habit of comparing stuff with others, because you the know the value of the product only when you have competition, Right?. So we are going to see in this post certain aspects between this WWDC 2012 and the previous ones run by the Apple’s past Show man – The Steve Jobs.

 

To make it simple, we will focus on following aspects: 

 

1. Secrecy:

 

Tim Cook did mention about doubling down the secrecy @ All Things D Conference, but still Apple could not prevent the features list being spilled out before Today’s WWDC 2012 event.

Here is the question. Did anyone knew about the First iPhone before the WWDC at that time? But on the other hand, Steve jobs was at its best in creating the Pirate teams, except in case of iPhone 4 leak in a bar. 

 

Having said that, the media right now has grown HUGE (with the arrival of Twitter and establishment of Facbeook) than what it was in 2007 and add to the fact that there is immense spotlight on what Apple is doing virtually each day. With that, we should say Tim Cook & Co. did a good job

 

2. Presentation:

 

Tactically, it looks like Tim Cook did not want to come up with his own style and make the show a huge disappointment, Instead he picked the best of the steve jobs slides and wrapped up in a neat show.

 

Check out this slide.

 Screen Shot 2012 06 11 at 10 04 11 PM

 

Add to that the opening of the Keynote with Siri. Starting the Keynote with the a Product or an Ad is not new. The Famous 1984 Keynote ( http://youtu.be/RcRQWGFJ5YY?t=3m8s ) where Steve jobs led Macintosh speak for the first time, and then the Famous Ad ( http://youtu.be/w6SXMtmUsX0?t=7s ) where the PC Guy asks developer to go on Off for a year, are few examples of its kind. 

 

But, If everyone else can copy Apple, then it is absolutely fine for Apple to copy Apple. What do you say?

 

3. WOW Factor

 

You just check back the Keynote video and you see there is that Steve Jobs WOW factor missing. There was some great stuff with retina display, Maps, Next Generation Macbook Pro hardware, and so on.

The WOW factor I am speaking is something like these

 

iPod Nano taken a Smallest Pocket showing its usage. 

 

[youtube=http://youtu.be/7GRv-kv5XEg?t=1m30s]

 

They got a Best Macbook Pro, But there was no sense of excitement created around it. Or Let me say they did not exaggerate it. These are kind of additional things which without its existence may not cause harm on Product sales, but would definitely have a positive effect in its presence.

 

Here’s another piece of Job’s Salesmanship

 

Introducing Macbook Air kept within a US Post Envelope showing its thinness:

 

[youtube=http://youtu.be/jDQmvAPYjms?t=2m31s]

 

Comparing all the best in the industry is one of the key aspect of Steve Jobs Keynote. As said earlier, the product value is known only when it has a competition and Apple today missed the key thing to compare Macbook Pro with its Competitiors.

 

Another example, is that they have taken a dig at Window in the past, but this time with the whole new maps, they demonstrated without a word on Google. I wonder if steve could resisted to do that!!

 

But Having said this, there is no harm done as their products introduced today speaks for themselves.

 

4. The Naming:

 

Something has gone wrong with Tim Cook and Co in naming their products. They do the best products but could not come up with best names for it. The ‘The New iPad’ (see the second ‘the’ in my sentence, I hate it) is really awkward. Definitely makes it much more confusing when the next iPad comes out.

 

And the worse is they did not name or did they really name the Macbook Pro as “Macbook Book Pro with Retina Display’ ?

Even worser, they don’t have the name on the Physical Device. Atleast, I don’t see them on the one displayed in Ads.

 

Screen Shot 2012 06 11 at 10 55 01 PMPro name

 

This is such a delicate thing, it acts as an Advertisement and plays a role in word of mouth advertisements for Apple. I always get excited to spot a Apple product in Bollywood and other regional language movies adopted to show the richness of the Character and that moment we feel proud to see the Apple Logo and the name, in case only the display is shown.

 

 

Summary:

 

There are other minute things like the way Tim Cook slowed down his pace than compared to his iPhone 4S keynote, the humors created by Phil Schiller and Scott on Android, and all these things show that the effort is being made to make the Conference a success.

 

To complement Tim Cook, He has made One major improvement from his Previous iPhone 4S event where he did not stay on his statistics for too long.

 

Overall, A decent Job by Tim Cook and Co where they took no risk in experimenting new ideas in Keynote and were pretty happy in demonstrating the tested and successful methods of presentations. Having said, it is hard on them to expect a new stuff in such a short time, and the fact that Steve Jobs Legacy has created a Halo effect in our minds. In that regards, Its a Job Well Done.

 

In Simple words, Their amazing products drove the show for themselves.

 

I wish Tim Cook & Co, and Apple All the very best :)