Tuesday, June 26, 2012

Phonegap plugin. Fixed an issue of not getting a callback in Js after this.success() called from Plugin class

I was facing a weird problem on developing a plugin for Phonegap on Android. After the the execution of native Java function, i was not able to give back the success or failure message to JS file.

The following is how my Plugin class looks like.
public class MyPlugin extends Plugin {
  @Override
  public PluginResult execute(String action, JSONArray data, String callbackId) {
        
        this.callbackId = callbackId;
        
        /* .. some code ... */

        StartMyAsyncThread();
        
        PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
        return pr;
    }
        
    
    public void resultOfAsyncThread(String message){
        
        PluginResult pr = new PluginResult(PluginResult.Status.OK, message);
        this.success(pr, this.callbackId)
    }
    
}


From the execute class, if I returned Status.OK instead of Status.NO_RESULT, I was able to get the call to success_callback function in javascript file. But, from the asynchronous thread, if I called this.success(), I was not getting the call to success_callback function in javascript.

This was crucial as it is the only way i can get the result of native calls to the javascript.

After hours of trial and error and googling, I got the fix. I added the call  pr.setKeepCallback(true); after creating the PluginResult object. And everything seems to be going fine.

This is how my modified code looks now.

public class MyPlugin extends Plugin {

  @Override
  public PluginResult execute(String action, JSONArray data, String callbackId) {
        
        this.callbackId = callbackId;
        
        /* .. some code ... */

        StartMyAsyncThread();
        
        PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
        pr.setKeepCallback(true);
        return pr;
    }
        
    
    public void resultOfAsyncThread(String message){
        
        PluginResult pr = new PluginResult(PluginResult.Status.OK, message);
        pr.setKeepCallback(true);
        this.success(pr, this.callbackId)
    }
    
}


I got the fix from this stackoverflow post.

Saturday, June 23, 2012

Dot operator in Objective C

In Objective-C, dot operator can be used to access the member function of a class. The syntax makes you feel that you are directly accessing the instance variable of a class, but you are not.

You can can use dot operator to.
  1. to access the member function with zero argument and 
  2. to access the member function with one argument with no return value. Provided the name of the function starts with word 'set' and the character just after 'set' is an uppercase ascii or an underscore.
Lets see this with example

File: TestVariableAccess.m
#import "TestVariableAccess.h"

@implementation TestVariableAccess

-(int)function{
    NSLog(@"function_ret");
    return 100;
};


-(int)setFunctionWithArg:(int)arg{
    NSLog(@"function_ret withArg %d", arg);
    return 101;
};


@end


These functions can be called with the dot operator as follows.

The below code will call the method named function and the return value is assigned to the variable a.

TestVariableAccess *obj = [[TestVariableAccess alloc]init];
int a = obj.function;

The below code will call the method named setFunctionWithArg. Note that the compiler adds the word 'set' to the method name and makes the first character in the method name to uppercase before calling the method.

TestVariableAccess *obj = [[TestVariableAccess alloc]init];
obj.functionWithArg = 10;


Setters and getters

Though the dot operators can be used to call any method abiding to the above mentioned rule, it is meant to be used for setters and getters.
Consider the below declared variable value

TestVariableAccess.h
@interface TestVariableAccess : NSObject{
    int value;
}

-(int)value;
-(void)setValue:(int)v;

@end

TestVariableAccess.m
#import "TestVariableAccess.h"

@implementation TestVariableAccess

-(int)value{
    return value;
};


-(void)setValue:(int)v{
    value = v;
};


@end

Here the getter is value and the setter is setValue. In Objective-C the name of the getter is same as that on the name of the variable and the name of the setter is variable name prefixed with 'set' word with the first character in the variable (if it is not underscore) is made to upper case.

With the dot operator, the getter is called by
TestVariableAccess *aa = [[TestVariableAccess alloc]init];  
int v = aa.value;

and the setter is called by
TestVariableAccess *aa = [[TestVariableAccess alloc]init];  
aa.value = 12;

This way we can access the instance variable with dot operator through setters and getters. Though the code seems like we are accessing the instance variable directly, we are not. Instead we are accessing the variable through setters and getters.

If there is not setters and getters defined, the compiler will throw error. 

Accessing public variable directly

You can declare a public instance variable in Objective-C class as shown below.

@interface TestVariableAccess : NSObject{
@public
    int pubValue;
}
@end

Public variables can be accessed without declaring setters and getters. Since the dot operator is reserved for setters and getters, the Objective C  uses -> operator to access the public variable.

TestVariableAccess *aa = [[TestVariableAccess alloc]init]; 
        
// Setting value
aa->pubValue = 12;
        
// Getting value
int v = aa->pubValue;
        

Thursday, June 21, 2012

interface keyword in Java and ObjectiveC

There is an interface keyword in both ObjectiveC and Java (in Objective-C it is @interface). Are they used for the same purposes ?

Answer: No.

We will see this in detail.

interface keyword in Objective-C


In C, a function (that is accessed by a different file) is usually written in two files. In .c and .h files. We write the function prototype in .h file and the function body in the .c file. 
The .c files, of course with the help of .h files, is compiled to form the libraries (.a, .o, .so etc. ) and executable where as the .h files are used by the code that uses these libraries. 
The .h files thus act as a document for anybody who is using this library. By checking the .h file one can understand what APIs this library offers. The .h files also help the compiler to understand the symbols (function name, variable names etc ) of the external libraries that you are using in the code. 

Objective-C also adopts the same philosophy. 

A class in Objective-C is , usually, is a combination of a .m and a .h file. 

Here, the .m file is used to write the function body in a class, where as the .h file is used to write the function prototype (or interface), variable declaration, mention class inheritance etc.  

In .h file the function declaration are mentioned between the keywords @interface and @end and in .m file the function bodies are mentioned between the keywords @implementation and @end

Example


.h file

//SampleClass inherits from NSObject
@interface SampleClass : NSObject

// Variables are declered between these curly braces. 
{
    int value1;
}

// Setter for value1
-(void)setValue1:(int)v;


//Getter for value1. Note that there is no 'get' word in the getter. By convention, in 
// Objective-C the getter function name is same as the variable name. 
-(int)value1;

@end

.m file

#import "SampleClass.h"

//Implemetation of the prototype defined in SampleClass.h
@implementation SampleClass


//Implementation of setter
-(void)setValue1:(int)v{
    value1 = v;
}


//Implementation of getter
-(int)value1{
    return value1;
}

@end


interface keyword in Java


interface in Java is used to enable dynamic binding and thereby polymorphism. interface is just an agreement that defines some function prototype. A class using this interface can take any object who is adhering to this agreement. Any class can adhere to the agreement by just implementing the function prototype of the interface.

Example

Interface (Agreement)
// This interface is a agreement. Any class can adhere to this agreement by 
//implementing this interface. 

public interface SampleInterface{
// You can have more function in this interface. 
    void printValue();

}


Implementation (A Class adhering to the above agreement)
public class SampleImplementationOne implements SampleInterface{
    
    void printValue(){
        System.out.println("This is SampleImplementationOne");
    }
}


User - This class uses the interface SampleInterface. Note:- Nowhere in the class there will be mention of any of the implementation of this interface (such as  SampleImplementationOne). There is only reference of SampleInterface. The function printLogValue can take any class that implements the interface SampleInterface.
public class UserClass{

    void printLogValue(SampleInterface sample){
        sample.printValue();
    }
}
If we pass SampleImplementationOne to the function printLogValue, it will print "This is SampleImplemetationOne".
public static void main(String[] args){

    UserClass uc = new UserClass();
    uc.printLogValue(new SampleImplementationOne());
    return;

}
The class UserClass decides which implementation of SampleInterface is passed at the run time. This is a powerful feature and you can decide which implementation class to use at the run time.

Consider the following case.

Suppose you are implementing a network communication module. It helps if you define an interface (NetworkAdapter) that will declare prototypes for send and receive functions. This way you can choose your implementation of NetworkAdapter for Bluetooth, Wifi or any other interface at runtime.

The interface also help in development. Suppose the code of both Bluetooth or WiFi is not ready when you start development of your communication module. You can write your own DummyAdapter (implementing NetworkAdapter) for testing. When the Bluetooth or WiFi is ready, you can change the DummyAdapter to the corresponding implementation.

Dynamic binding in Objective-C

Now you see that the Java make use of the powerful dynamic binding with the use of interface keyword. How does Objective-C make use of dynamic binding? With the use of @protocol keyword. The detail of which is out of the scope of this article. See here for more details on protocol.


Wednesday, June 13, 2012

Target in Xcode explained

In many development platform, a target is the configuration required to build the source code to make it run on the selected hardware platform.

You may have to configure different parameters like the compiler, the optimization level, whether its for debug or not etc.

In Xcode, there is no much different from this normal definition of Target, but XCode also includes source files in to this definition.

A target in Xcode is a build configuration for a platform in which the code will be executing plus the the software that goes in to it.  Because the software is also included in the Target, this is the reason why you specify a target for each of the file you add in to a project (If you have not noticed it, check carefully next time while you are adding a file)

In Xcode, you can create multiple target for a project, each may have different build configuration, different target and also different set of source files.

Ok, lets explain this with one example,

Create a Max OSX command line project. 

  1. On Xcode, create click File->New->Project
  2. Under the Mac Ox X section on the left side, click Application and on the right side select Command Line Tool and click Next
  3. Give a ProductName (say LearningTarget) and a Company Identifier (say com.avantaj.sample
  4.  On Type select Foundation and for this example it docent matters whether you checked the Use Automatic Reference Counting or not
  5. Click Next
  6. Choose a folder where you need to save the project and click Create

Figure 1: Project Navigator
On the Project navigator, on the left hand side of the Xcode window, you will see something like this.

Under the Products folder you can see the Target created for this Project, LearningTarget.



Build Configurations 

Click on the LearningTarget project, on the top of the list.

On the right side you can see two columns. The first one showing the PROJECT and TARGETS and one on the right hand side showing the build configuration for the selected  PROJECT or TARGETS.

Figure 2: Build settings


Click the project LearningTarget, from the PROJECT section. There you can see the build configuration for the project.

Click the target LearningTarget from the TARGETS section. Here you can see the build configuration for the selected target.

If you see carefully, in this case you will not see any difference between the build configuration of the Project and build configuration of the Target. By default, the build configuration of the target is same as build configuration for the project. You can change the configuration for the particular Target.

Association between a file and a Target

In the window (shown in the above image) click the Target LearningTarget in the section TARGETS. Click Build Phases tab and under that click the section Compile Sources. There you can see all the source files associated with the target LearningTarget.

Figure 3: Build Phases



Try unlinking the main.m from the target LearningTarget. For that click on main.m on the Build Phases tab and click '-' icon shown at the bottom of Compile Source section.

Now clean (Product->clean from the Xcode menu), build and run again. Since now you don't have a main function on the Target, the Xcode will give you the error SBTarget is invalid

Add back the main.m to the target by clicking '+' icon shown at the bottom of Compile Source section.
Clean, build and run again. Everything should be fine now.  


Figure 4:File Inspector


Alternatively, you can also click on a file to see the which all target the file is associated with. 

Click the file main.m at the Project navigator, on the File inspector (right side first tab) select the section Target Memberships. Here you will see in which all target this file is associated with. 

The checkbox can be used to associate and disassociate the file with the targets. 

Adding a target

From the Project Navigator, select the project LearnTarget. You will see a screen shown in Figure 2. At the bottom, you can see Add Target link with a + icon. 

Click it an choose Mac OSX Application->CommandTool and click Next. 
Give a name for the target in the Product Name, say MyNewTarget. Choose Foundation as Type and and click Finish. 

Notice that under the Products group in Project Navigator, you can see the target MyNewTarget.

Also notice that a new group MyNewTarget is created in the Project Navigator. This group has a new main.m file for the newly created target. 

Selecting a Target to execute. 

You can choose the target for execration from the Scheme button at the top of the Xcode window. 


The scheme button has two part. On the left side you can chose any of the targets you have created and on the right side you can chose the run destination. 

Select an target and a run destination and click Run to execute the code. 

You can also edit the properties of the scheme by selecting Product->Edit Scheme from the Xcode menu. 


Monday, June 11, 2012

Misc Post: To create a text file without formats in Mac:TextEdit


In TextEdit, from menu got to Format and click 'Make Plain Text'.

This will be useful if you need to copy and save only text (not formats) from different sources like word, web etc.

Note : All the formats including styles, images etc will be lost. 

Sunday, June 10, 2012

UIViewController in iOS vs Activity in Android

There is an empty container that acts parent to all the views on a screen. This container is invisible, but this is where you add the root View. This container act as a controllers, where you can receive the events from its Views and and also control the lifecycle of a View.
Usually each of these controllers use to perform independent functionality. Thus to invoke a functionality, for example to take a picture, a controller is invoked.

In Android, this is known as Activity, whereas in iPhone it is called UIViewController.

Following are few similarities between Activity and UIViewController

Feature in iOS in Android
Setting root View calls function 
[UIViewController setView:View]
calls function
Activity.setContentView(View)
Setting root View from xml The function initWithNibName:bundle: automatically takes the xib file matching the same name of the controller to load the View. If we want to mention a file with different name it can be mentioned as an argument in this function.   Inside the function onCreate() uses function Activity.setContentView(int) to set the view form xml. The View are defined in xml in ''Resource" folder
Callbacks to handling Lifecycle. (Different stages in the controller lifecycle is handled by deferent callbacks)
viewDidLoad:
viewWillUnload:
viewDidUnload:

viewWillAppear:
viewDidAppear:
viewWillDisappear:
viewDidDisappear:

onStart();
onRestart();
onResume();
onPause();
onStop()l
onDestroy();
Invoking counterpart using presentViewController:animated:completion: Using Intent

This docent mean that UIViewController and Activities are similar in all respect, but I just pointed out some similarity. To mention a difference, here is one.

An Activity in Android cannot hold an sub Activity. Where as in iOS, a UIViewController can hold another UIViewController.

That is, a parent-child relationship exist for UIViewController in iOS. UITabViewController and UINavigationViewController  are the example of a parent View Controllers. On a parent child relationship, the View of a child controller is usually shown inside the parent controllers view.

There is also another type of relationship, the presenter-presentee relationship. Here a UIViewController invoke a different UIViewController that is not its child. Usually, the View of the invoked UIViewController   covers the view of the UIViewController that invoked it.  Also in the presenter-presentee relationship, the controllers docent shares any common data.

Activity in Android support only presenter-presentee relationship. An activity can invoke another activity using an Intent.

Thursday, June 7, 2012

Method name in objective C


One thing that keeps you a bit puzzled at the start of learning objective C is its function(method) declaration inside a class. Most of the developers who migrated from other languages like C , java, python, javascript etc may never have encountered with such use of function names.

Lets see an example

- (float) divideNumerator:(int)numerator withDenominator:(int)denominator{
    /* Calculate and return result */
}

'-' tells that it is a instance method. To declare a class method, we will use '+' sign

(float) is the return type.

Now if you see the method name and argument, you will see a repetition of patterns like this. The pattern is repeated for all the arguments,

key:(return_type)value

For example:

divideNumerator:(int)numerator and
withDenominator:(int)denominator

Here the keys are divideNumerator and  withDenominator whereas the values are numerator and denominator.

The method name is nothing but the combination of keys ending with colon, that is in this case, the method name is

divideNumerator:withDenominator:

In method with no argument, there is only one key with no values,  for example

-(float)getResult{
    /*Return result*/
}

In this case, the method name is

getResult:

Passing messages to a method. 

In Objective C, an instance method called is termed as Passing message to the object. For example

float value = [obj divideNumerator:20 withDenominator:10];

Here the method divideNumerator:withDenominator: is called with arguments 20 and 10. The argument passed also have a key:value pattern, where keys are the same as mentioned in the method declaration.