Sunday, 9 July 2017

Android Launch Mode

Activity is one of the most brilliant concept on Android from its well-design architecture on memory management which lets Multitasking works perfectly on this most popular mobile operating system. Anyway, Activity is not just to be launched on the screen. The way it is launched is also concerned. There are so many details in this topic. One of those that is really important is launchMode, which is the one that we are going to talk about in this blog.


There are 4 types of launchMode available. Let's see it one by one.
1. Standard
2. SingleTop
3. SingleTask
4. SingleInstance

1. Standard:  This is the default mode.  We are adding launchMode=”standard” in B.

Assume Activity Stack
D
C
B
A

Start Activity B again, Now the activity stack will be
B -new instance of B
D
C
B
A

2. SingleTop:  We are adding launchMode=”singleTop” in D.

Eg:1
Assume Activity Stack
D - is on top of Activity Stack
C
B
A

Start D from any service or other application or from somewhere.
Output:
D -old instance gets extras data through onNewIntent(Intent intent);
C
B
A

Note: if the activity available in the top of stack, it will update the same instance with new intent data or else it will create a new activity instance.

Eg: 2
Assume Activity Stack
D
C
B
A

Start C from D
Output:
C -As the last C was not on the top of task, so new instance will be created.
D
C
B
A

3. SingleTask: We are adding launchMode=”singleTask” in C.

Assume Activity Stack
D
C
B
A

Start C from any activity or service
Output:
C -old instance gets extras data through onNewIntent(Intent intent);
B
A

Note: it checks whether Activity C is available in the Stack, if yes, update the instance with new data and destroy the other activity at the top. Hence here Activity D gets destroyed.  if activity is unavailable in the stack it create a new instance as usual.

4. SingleInstance: We are adding launchMode=”singleInstance” in E.

Eg 1:
Assume Activity Stack
D
C
B
A

Start E
Output:
E
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
D
C
B
A

Note: A , B , C , D will be in one task and E will be in another task.
and if we continue this,  start F from E,then

Output:
F
D
C
B
A
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
E

Note: A , B , C , D , F will be in one task and E will be in another task.

Eg 2:
Assume Activity Stack
A
B
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
E

Start E from A
Output:
E -old instance gets extras data through onNewIntent(Intent intent);
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
A
B

Courtesy: Link1 & Link2

Android Flags Launch Mode

These flags has been setted programmatically, it can be used depends upon to the situation and it does overrides the behaviour which has defined in the AndroidManifest.xml file.

The following are the list of launch mode flags

FLAG_NEW_TASK
FLAG_CLEAR_TASK
FLAG_SINGLE_TOP
FLAG_CLEAR_TOP



FLAG_NEW_TASK:

Eg 1:
Assume Activity Stack
D
C
B
A

We are starting E from D with flag
Output:
E
-------
D
C
B
A
Note:  A , B , C , D will be in one task and E will be in another task

Eg 2:
Assume Activity Stack
D
C
B
A

We are starting B from D with flag
Output:
B
-------
D
C
B
A
Note:  A , B , C , D will be in one task and and another B will be in another task

FLAG_CLEAR_TASK: It works in conjugation with FLAG_NEW_TASK

Assume Activity Stack
D
C
B
A

We are starting E from D with flag
Output:
E

Note: All other activities will be get destroyed, every time it creates the new instance of the activity. Importantly, even if the activity already exist in the stack, it won't encourage the updating of the same activity with onNewIntent(...)

FLAG_SINGLE_TOP:
This works same as launch mode="singleTop" (Refer this link)

FLAG_CLEAR_TOP: It works similar to the SingleTop Flag, but it has one unique feature of destroying the activities on the top of the stack

Assume Activity Stack
D
C
B
A

We are starting B from D with flag
Output:
B -old instance gets extras data through onNewIntent(Intent intent);
A
Note: All the other activities on top of the B will be destroyed.

Courtesy: Link

Sunday, 2 July 2017

Kotlin: tailrec - Permanent fix for Painful StackOverflowError



Parameters and local variables are allocated on the stack (with reference types the object lives on the heap and a variable references that object). The stack typically lives at the upper end of your address space and as it is used up it heads towards the bottom of the address space (i.e. towards zero).

Your process also has a heap, which lives at the bottom end of your process. As you allocate memory, this heap can grow towards the upper end of your address space. As you can see, there is a potential for the heap to "collide" with the stack (a bit like tectonic plates!!!).

The common cause for a stack overflow is a bad recursive call. Typically, this is caused when your recursive functions doesn't have the correct termination condition, so it ends up calling itself forever. However, with GUI programming, it's possible to generate indirect recursion. For example, your app may be handling paint messages, and, whilst processing them, it may call a function that causes the system to send another paint message. Here you've not explicitly called yourself, but the OS/VM has done it for you.

To deal with them you'll need to examine your code. If you've got functions that call themselves then check that you've got a terminating condition. If you have then check than when calling the function you have at least modified one of the arguments, otherwise there'll be no visible change for the recursively called function and the terminating condition is useless.

If you've got no obvious recursive functions then check to see if you're calling any library functions that indirectly will cause your function to be called (like the implicit case above).

Courtesy: Link1

Example:  This is a demo example which i have used to get the StackOverflowError
Wrote a long run recursive method to sum up-to n numbers.

// Recursive function to find sum of numbers
fun sumOfNumbers(aVal:Int):Int {
    sum+=aVal;
    if (aVal == 0)
        return sum  
    else      
        return sumOfNumbers(aVal-1)
}
print(sumOfNumbers(3)) // 3+2+1=6  - This won't cause StackOverflowError
Output: 6

See, here we have used the smaller number, assume i trying to give a larger number (it may differ based on the system memory), While I'm testing with the below scenario got caught with the StackOverflowError at 1023...1050 (randomly).

print(sumOfNumbers(9000))  // 9000+8999+8998...  - This cause StackOverflowError

Hence, In order to avoid this kind of issue, kotlin provides an option called tailrec, we need to add this keyword before to the recursive method, the rest will taken care by the kotlin internally do the looping kind of approach and facilitates to provide us the solid & valid output with out any crash or error.

// Same Recursive function to find sum of numbers using tailrec 
tailrec fun sumOfNumbers(aVal:Int):Int {
    sum+=aVal;  
    if (aVal == 0)
        return sum  
    else      
        return sumOfNumbers(aVal-1)
}

print(sumOfNumbers(9000))   // The tailrec keyword take care of the app crash or SOF error.
Output: 040504500

Kotlin - Extension Vs Infix

Extension:
Kotlin, similar to Objective C (Categories) & C# Extension methods, here kotlin provides the ability to extend a class with new functionality without inheriting the class i.e. by using the Decorator design pattern. This is done via special declarations called extensions. Kotlin supports both extension functions and extension properties.

Infix Function:
In Simple, All Extension functions are not Infix, but every Infix method must to be extension function.

Criteria: 
0. Mandatory to have a params to the function,
1. Function does not accept more than one params.

// Definition: Extension function, here we have extending the checkCastMyVote from the String Class (In-Built Class).
// Here the function is used as an expression.

fun String.checkCastMyVote(name: String, age: Int) =
        if (age >= ELIGIBLE_YEAR) {
            "$this $name your age is $age, you are eligible to cast your vote"
        } else if (age in 0..17) {
            "$this $name you need to wait for ${ELIGIBLE_YEAR.minus(age)} more year(s)"
        } else {
            "$this $name, please provide the valid birth year (Given: $age)"
        }

// Calling a Extension Function: 
println("Mr.".checkCastMyVote("Ragavan", 23))  // Passing a params
println("Mr.".checkCastMyVote(age = 42, name = "Rajeevan"))  // Named functions


// Infix function definition
infix fun Int.getAge(yob: Int) =
        if (yob > 0) {
            this.minus(yob)
        } else {
            yob
        }

// Infix function call (no need to use dot or typical function calling syntax)
val CURRENT_YEAR=2017
var YEAR_OF_BIRTH=1988
var age = CURRENT_YEAR getAge YEAR_OF_BIRTH

Also, we can also apply & access this both extension and infix function to the user defined classes as well.

// Defining the class
class Guru {
    var name: String = ""
    fun isPassed(totalMark: Int) = if (totalMark > 35) "Passed" else "Failed"
}

// Defining the infix function.
infix fun Guru.isScholarshipEligibleMessage(totalMark: Int) =
        when (totalMark) {
            in 0..34 -> "No scholarship available for ${this.name} "
            in 35..50 ->
                "${this.name} Avail 50% Scholarship of amount"
            in 51..80 -> "${this.name} Avail 70% of Scholarship amount"
            in 81..100 -> "${this.name} Avail 85% of Scholarship amount"
            else -> "${this.name} Total Mark is invalid"
        }


// Calling the method
 var guru = Guru()
    guru.name = "Rajeev Menon"
    var totalMarks = 0 //38 //79 //85
    println("${guru.name} is ${guru.isPassed(totalMarks)}")
    println(guru isScholarshipEligibleMessage totalMarks)

Sunday, 18 June 2017

Android Resource Layout Sub-folder

Right now, we are probably storing every xml layout file inside the layout/ folder. It is feasible and simple to manage in small projects, but when i'm developing a large and heavy projects/products i.e. more .xml files, we feel difficult in search and finding the files and the things will get messy.

So, is there any way to solve this problem?

Yes, after a long search i found the plugin called "Android File Grouping Plugin" but this not gives me the expected solution, this virtually group the layout files into folder and this can visualized only in the android studio which need to be enabled with the plugin, as like as we have it in the XCode for iOS Projects.

Solution:
Hence after the deep dive into the gradle's ground and found the solution for the same without using any third-party plugins and therefore it also directly reflects on the code and folder hierarchy.

here its go like this, please keenly follow the steps

1. Prepare the folder structure in the below way,  inside the res folder, create your own directory and
inside those folders keep the root folder named as "layout" and then keep on adding your .xml files as to your convenient. For EG: In the below example, i have made the designed the Boarding and Dashboard, under to that created the layout as root directory, then added my .xml files.

res/
  layout/
    boarding/
      layout/
        onboarding_activity.xml
        onboarding_fragment_guest.xml
        onboarding_fragment_user.xml
    dashboard/
      layout/
        dashboard_activity.xml
        dashboard_details.xml

2. The trick is to use gradle’s ability to merge multiple resource folders and set the res/ folder as well as the nested subfolders in the sourceSets block.  The quirk is that you can’t declare a container resource folder before you declare that folder’s child resource folders. Below is the sourceSets block from the build.gradle file. Notice that the subfolders are declared first.

sourceSets {
        main {
            res.srcDirs = [
                    'src/main/res/layout/boarding',
                    'src/main/res/layout/dashboard',
                    'src/main/res/layout',
                    'src/main/res'
            ]
        }
    }

Wednesday, 14 June 2017

Guard Statement in Swift Programming

Correction: Instead of where replace with , (comma) 

The guard statement is a Swift language feature introduced as part of Swift 2. A guard statement contains a Boolean expression which must evaluate to true in order for the code located after the guard statement to be executed. The guard statement must include an else clause to be executed in the event that the expression evaluates to false. The code in the else clause must contain a statement to exit the current code flow (i.e. a return, break, continue or throw statement). Alternatively the else block may call any other function or method that does not itself return.

Syntax:
func function_name (paramsname: paramType…) -> <ReturnType>
{
guard <boolean expressions> , <condition check> else {
    // code to be executed if expression is false
    <exit statement here>

// code here is executed if expression is true
}

Limitations:
*This statement used inside the functions
*This occupies the complete method and to do the check and process.

Code Snippet:
var value:String! = "Tessa"
print(value)
testFun(v:value)

func testFun(v: String?)  {
    guard let vu = v, vu == nil else {
    print ("Value is nil")
    return
    }
    print("Value is not nil")  // Output
}

Without Guard Statement: #Rust Coding:
func nonguardSubmit() {
    if let name = nameField.text {
        if let address = addressField.text {
            if let phone = phoneField.text {
                sendToServer(name, address: address, phone: phone)
            } else {
                show("no phone to submit")
            }
        } else {
            show("no address to submit")
        }
    } else {
        show("no name to submit")
    }
}
With Guard Statement:
func submit() {
    guard let name = nameField.text else {
        show("No name to submit")
        return
    }

    guard let address = addressField.text else {
        show("No address to submit")
        return
    }

    guard let phone = phoneField.text else {
        show("No phone to submit")
        return
    }

    sendToServer(name, address: address, phone: phone)
}

func sendToServer(name: String, address: String, phone: String) {
  ...
}
Guard Statement Improvised Code 1:
guard let name = nameField.text where name.characters.count > 3 && name.characters.count <= 16, let range = name.rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) where range.startIndex == range.endIndex else {
    show("name failed validation")
    return
}

sendToServer(name)
Guard Statement Improvised Code 2:
func tappedSubmitButton() {
    guard let name = nameField.text where isValid(name) else {
        show("name failed validation")
        return
    }

    sendToServer(name)
}

func isValid(name: String) -> Bool {
    // check the name is between 4 and 16 characters
    if !(4...16 ~= name.characters.count) {
        return false
    }

    // check that name doesn't contain whitespace or newline characters
    let range = name.rangeOfCharacterFromSet(.whitespaceAndNewlineCharacterSet())
    if let range = range where range.startIndex != range.endIndex {
        return false
    }

    return true
}
Courtesy: Link1, Link2

Sunday, 11 June 2017

Optionals in Swift Programming




What is optional? When declaring variables in Swift, they are designated as non-optional by default. In other words, you have to assign a non-nil value to the variable. If you try to set a nil value to a non-optional, the compiler will say, “hey you can’t set a nil value!”.

var message: String = "Swift is awesome!" // OK
message = nil // compile-time error

An optional declaration doesn’t say “this is an String, which is optional”. It says, “this is an Optional, which may or may not hold an String”

Have you ever struggled with the various “?” and “!” symbols here and there in a Swift code? Or ever found yourself confused about the phrases like 
  • “Forced unwrapping”, 
  • “Optional unwrapping” or “Optional binding”,
  • “Automatic unwrapping” or “Implicit unwrapping”,  
  • “Nil coalescing”, 
  • “Implicit binding” or “Optional chaining”  (will see this later point of time)
You’re in the right place!

Optionals are a powerful feature in Swift language which come to solve the problem of non-existing values. Coming from Java and being passed through the hell of NPEs (Null Pointer Exception), I’m truly excited with this feature of Swift.

Forced Unwrapping:
We use this way in order to get the value of age we put an exclamation mark at the end of the variable.

var age: Int?
age = 23
print(age!) // outputs 23

This option is not a safe one because if age were a nil, it would crash the app, so we need to use a safest way to unwrap the optional Int value.

Optional unwrapping / Binding:
So this is the safest and preferred way to unwrap an optional, we say if age variable really contains a Int value meaning it is not a nil value then unwrap and assign it to myAge variable and that by the way myAge variable will hold an Int type and not an Int? type thus we can use it as it were a normal variable.
But if age contains a nil value then the execution flow won’t get to the if body which is great since we wouldn’t want to use nil.

var age: Int?
age = 23
if let myAge = age {
  print(myAge) // outputs 23
}

Automatic / Implicit unwrapping:
It is rare to use this way of unwrapping an optional but it is good to know when you encounter some code using it so it is simply putting the exclamation mark at the end of the type declaration, and then whenever we try to get the value of age, Swift will automatically will unwrap the optional for us giving us the value.

var age: Int! // here goes the exclamation mark
age = 23
print(age) // outputs 23

Nil coalescing:
Sometimes we want to use a default value when the optional is nil. Let’s take a look at this example:

let optionalInt: Int? = nil
var result: Int
if optionalInt != nil {
    result = optionalInt!
} else {
    result = 0
}
print("The result is \(result)")    // prints "The result is 0"

This could be reduced to a one line by using a ternary operator (the “?” below represents the ternary operator).

let optionalInt: Int? = nil
let result = optionalInt != nil ? optionalInt! : 0
print("The result is \(result)") // prints "The result is 0"

Nil coalescing allows us to shorten this even more, this just means (??) “If optionalInt is nil then use zero, otherwise use its unwrapped value”.

let optionalInt: Int? = nil
let result = optionalInt ?? 0

print("The result is \(result)")  // prints "The result is 0"

Sunday, 4 June 2017

Tuples In Swift Programming

A tuple in Swift is a construct that groups multiple values together into a single compound value. Tuples can be useful when more than one value type can provide more useful information about the outcome of a behavior or action than simply returning a single value. They are meant to be temporary and are not suited for more complex data structures that will probably persist beyond a temporary scope

var person = ("Sachin", "Ramesh")

Named elements:
You can name the elements from a tuple and use those names to refer to them. An element name is an identifier followed by a colon(:).

var person = (firstName: "Sachin", lastName: "Ramesh")

var firstName = person.firstName // Sacin
var lastName = person.lastName // Ramesh

Accessing a Tuple:

let (firstName, lastName) = person
print(firstName) => "Sachin"
print(lastName) => "Ramesh"

let (onlyFirstName, _) = person
print(onlyFirstName)=> "Sachin"

Indexing a Tuple:
let firstName = person.0
let lastName = person.1
print(firstName) => "Sachin"
print(lastName) => "Ramesh"

Accessing it's Named Values:
let person = (firstName: "Sachin", lastName: "Ramesh")
print(person.firstName) => "Sachin"
print(person.lastName) => "Ramesh"

Functions and Tuples:
Tuples can also be useful as a return type for a function to return multiple values as part of a single compound value. Continuing with our code example, let's build out the function that's responsible for returning this tuple.

// Function Definition
func getFullName() -> (firstName: String, lastName: String) {
  let person = (firstName: "Sachin", lastName: "Ramesh")     //Assume getting from HTTP.get(url)
  return (person.firstName, person.lastName)
}

// Calling the Function
let person = getFullName()
print(person.firstName) => "Sachin"
print(person.lastName) => "Ramesh"

Thursday, 18 May 2017

Visual Studio Mobile Center - Android, iOS, Windows & React Native

Visual Studio Mobile Center, a set of cloud services for building and managing your mobile apps. Mobile Center is designed for all apps targeting iOS, Android, Windows including apps written in Swift, Objective-C, Java, Xamarin, and React Native.


Delivering excellent mobile experiences requires going beyond frameworks and IDEs—developers also need services to continuously build, test, distribute, and monitor their apps so that they can quickly iterate and improve. Many teams cobble together a workflow using some of these services from different tools and products. But this is time-consuming and distracts you from your actual mission of delivering a great app.

This is why we built Mobile Center: a mission control for mobile apps that brings together all the cloud and life cycle services that help developers deliver high quality apps faster. You can build, test, distribute, and monitor your apps and easily add backend cloud services to scale your app to millions of users on demand.

There are many great features included in the Preview, with even more to come. Here’s what you can do today:

  1. Build your apps automatically with every pull request via connecting it to the Repositories like Github, Bitbucket etc.
  2. Test apps on thousands of real-world devices
  3. Distribute passing builds to beta testers or user groups or organisation
  4. Monitor apps for crashes and bugs 
  5. Learn about real world usage with mobile analytics
  6. Connect to a mobile backend for automatic scaling and to add important cloud services like offline data sync, tabular data storage, and end-user authentication services

Mobile Center is the next generation of our existing mobile developers services, including HockeyApp and Xamarin Test Cloud. Later next year, Mobile Center will show all of your new and existing HockeyApp and Test Cloud apps to ensure a seamless transition for those customers.

It’s easy to get started. Request an invitation and once approved, sign in with your existing HockeyApp credentials, GitHub account, or Microsoft Account. Then, connect your apps and kick off some builds. The preview is free, with some metering to ensure everyone has a chance to use the services and provide feedback.

Courtesy: #MobileCenter #Reference

Friday, 12 May 2017

Mac Machine not necessary anymore for Xamarin.iOS degub, run, test and deploy

If you’re an iOS developer, then Microsoft’s Xamarin already allowed you to develop your iOS applications in C# with the help of tools like Xamarin.iOS for Visual Studio. Until now, though, you still needed a Mac to build and test your apps. As the company announced today, that’s not necessary anymore. With the new Xamarin Live Player, you can deploy, run, test and debug iOS apps directly from a Windows PC that runs Visual Studio.

With this, Microsoft is closing the loop for most developers and is getting a step closer to its goal of positioning Windows 10 as the preferred operating system for cross-platform development.   To enable this new functionality, developers have to install the Xamarin Live Player app on their iOS device and then pair it to their PC by scanning a QR code on their screen. Because this is fully baked into Virtual Studio, you also get access to all of the usual functionality you would expect in your IDE. You can, for example, make live edits to your code while it is running and immediately see the result of a color change, for example, on your phone.



Microsoft tells us that it talked to Apple about this functionality and that it has its rival’s blessing and that the Live Player application complies with all of Apple’s usual rules.
Courtesy: techcrunch

Google’s new Mobile OS Fuchsia, gonna completely replace Android in sometimes


Google’s Android platform is the most widely used mobile operating system in the world. In fact, it’s so popular right now that it’s beyond difficult to imagine a future without Android. Of course, people at one point felt the same way about early smartphone platforms like Symbian and BlackBerry OS, which have been almost completely wiped from the face of the Earth at this point. Some day, iOS and Android will be distant memories as well.

If there’s one thing companies like Nokia and BlackBerry taught us, it’s that companies at the top can only stay at the top if they’re constantly preparing for the future. So, rather than rest on its laurels and sit pretty while Android continues to dominate the smartphone market, Google is already hard at work on a fresh new mobile platform called Fuchsia, which may some day completely replace Android.

Dig Through:

I decided to dig through open source to examine the state of Google’s upcoming Fuchsia OS. For anyone unfamiliar, Fuchsia seems to be the replacement for both Android and Chrome OS. Fuchsia is the actual name of the operating system, while Magenta is the name of the kernel, or more correctly, the microkernel. Many of the architectural design decisions appear to have unsurprisingly been focused on creating a highly scalable platform. Google is unsurprisingly bringing up Fuchsia on a number of platforms, including the humble Intel NUC. ARM, x86, and MIPS bring-up is exactly what you would expect for an Android successor, and it also seems clear that this platform will run on Intel laptops. More on this later.

My best guess is that Android as an API and runtime will live on as a legacy environment within Fuchsia. That’s not to say that all development of Android would immediately stop, which seems extremely unlikely. But Google can’t push two UI APIs as equal app frameworks over the long term: Mojo is clearly the future.  Ah, but what is Mojo? Well it’s the new API for writing Fuchsia apps, and it comes from Chromium. Mojo was originally created to “extract a common platform out of Chrome's renderer and plugin processes that can support multiple types of sandboxed content.” It seems to have enabled Android apps in Chrome OS, and now it will serve an even more extensive role as the developer API for Fuchsia.

Programming Languages in role!

Mojo in Fuchsia features intriguingly extensive language support. C/C++, Dart, Go, Java, Python, and Rust all have bindings to Mojo. I am guessing that C/C++ is for native development, Go is for networking, Java is for Android(?), Python is for scripting, and Rust is for writing portions of the kernel. (Or perhaps Rust's usage is minimal, suggests a commenter on Hacker News.) Mixing and matching languages aside, the main UI API is based on, yes, Dart.  Flutter is an existing Google widget framework for apps written in Dart, and it has been repurposed to become the UI framework for Andromeda. Flutter includes a series of Material Design widgets and was engineered to render apps up to 120fps.* I imagine Andromeda’s standard UI components will look similar if not identical to those of Android. A physically based renderer, Escher, is apparently being used to render, well, material elements and shadows in a high quality manner.

I have very strong reservations about Dart as the language of the primary platform API, but it’s best to wait for the fully revealed details before forming an opinion. The reason for Dart is obvious, however: to enable a cross-platform app framework. The pitch will clearly be that developers can write a Flutter app once and have it run on Fuchsia (Google's Flutter SDK), Android, and iOS with minimal extra work, in theory. (Flutter does not target the web.) Even if Fuchsia is its full replacement, Android will be a separate developer target for many years given its gigantic installed base.

Fuchsia's actual app run-time is called Modular, “a post-API programming model that allows applications to cooperate in a shared context without the need to call each other's APIs directly." To do this it uses Mojo inter-process communication (IPC) messages, which are exchanged via low-level primitives in the form of message pipes (small amounts of data), data pipes (large amounts of data), and shared buffers.

I'm may not technically correct to explain, how the various languages interface over these IPC calls, and what exactly that enables. The IDL used is the Fuchsia Interface Description Language (FIDL), “an encoding format used to describe [Mojo] interfaces to be used on top of Magenta message pipes. They are the standard way applications talk to each other in Fuchsia.” Right now at least, only C/C++, Dart, and Go have supported bindings. Dart is thus the main platform language. (My understanding is that Go is not exactly ideal for writing UI apps.)

Courtesy: techspecs, bgr, flutter

Friday, 5 May 2017

Code Practice: Library Vs Framework

Most of the tyro programmers are every time wants to impress their leads/superiors, also want to show-up their code practices among their teammates, they use few terminologies to explain about their codes, tells they wrote a generic code and some of the dev's tells they have did a code and it is kinda libraries, frameworks and reusable components etc...  but they are not sure about those terminologies.  

In reality, the code which they have written is really a good and consider to be copy and paste into the other projects, and reuse those in other projects, by sure it reduce efforts.  But it is not a library or frameworks. 

Then what is Library and Framework?  Both smells like a same nuts, but it is not right?  It is a nut but the shells were different.


The key difference between a library and a framework is "Inversion of Control". When you call a method from a library, you are in control. But with a framework, the control is inverted: the framework calls you.

Library:
A library is just a collection of class definitions. The reason behind is simply code reuse, i.e. get the code that has already been written by other developers. The classes and methods normally define specific operations in a domain specific area. For example, there are some libraries of mathematics which can let developer just call the function without redo the implementation of how an algorithm works.

Framework:
In framework, all the control flow is already there, and there's a bunch of predefined white spots that you should fill out with your code. A framework is normally more complex. It defines a skeleton where the application defines its own features to fill out the skeleton. In this way, your code will be called by the framework when appropriately. The benefit is that developers do not need to worry about if a design is good or not, but just about implementing domain specific functions.


Courtesy: Programcreek

Sunday, 23 April 2017

Easy Code Tricks Android Development - Part - II


Click to review the Part I 

Here we go through the ten easy tricks to reduce our code time.  Android Studio IDE's facilitates our work to get done in a quick time.


Ctrl+N, type the class name to reach out the files directly from any where in the IDE and Ctrl+Shift+N, this pulls down all the classes, interfaces and .xml files as well



Choose from the last copy/pastes (manage your clipboard):  Mac: cmd + shift + v (Windows / Linux: ctrl + shift + v). By default there are 5 last copy/paste items.


Live Code Template: Mac: cmd + j (Windows / Linux: ctrl + j)


Enable multicursor feature: Mac: cmd + g (alt + j for Windows/Linux). press the shortcut to choose the similar text and get the cursor to the texts, while editing will update those values simultaneously.


Goto super class: Mac: cmd + u (Windows / Linux: ctrl + u). For instance, you override some method. When your caret in on the method’s name and press the shortcut, you will be redirected to the parent method.

Goto Declaration: Mac: cmd + b (Windows / Linux: ctrl + b). Place cursor on the word and use the shortcut, It allows you to quickly check and go to a declaration of a class, method or a variable.

Goto type declaration: Mac: cmd + shift + b (Windows / Linux: ctrl + shift + b).  Place cursor on the word and use the shortcut,  It allows you to quickly navigate to its type declaration.

Move and navigate between opened tabs:
Mac: cmd + shift + [ (move left) or cmd + shift + ] (move right)
Windows/Linux: alt + ← or →

Close a current tab:  Mac: cmd + w | Windows/Linux: ctrl + F4

Move hardcoded strings to resources: option + return (Windows / Linux: alt + enter). The shortcut must be used when a caret is on a text.


Sunday, 2 April 2017

7 Easy Code Tricks Android Development - Part - I


Here we go through the six easy tricks to reduce our code time.  This IDE's facilitates our work to get done in a quick time.

  1. Auto-Generate the parameterized constructor
  2. Auto-Generate the Getter and Setter Method
  3. Quick Walk-through on the documentation of android classes and methods
  4. Play around the bookmarks
  5. Generate documentation comments to the user defined methods. 
  6. Rename the text and reflect them to all places.
  7. Shortcut to set comments.
1. Auto-Generate the parameterized constructor:  We can simply presses the shift key twice in the code area it will brings you the popover search, there we need to key a search term as "constru....".  Select the constructor and then it will put you to the choose fields section, here select your necessary fields which you want to make as a parameters to the constructor.  After selecting click "ok" to generate the constructor, if you want an empty constructor just select an option "Select none". 














2. Auto-Generate the Getter and Setter Method:  Same as above, press the shift key twice on the code area and key the search term as "Getter and Set...", there you can find an option "Getter and Setter" also we can select either Getter or Setter  to generate those methods.  once selecting that option we need to choose the fields to which we required the set and get methods.

  

3. Quick Walk-through on the documentation of android classes and methods:  Select or keep cursor on the classes or methods and press the shortcut key "Ctrl+Q".


4. Play around the bookmarks: This is good feature on the coding part help us to switch immediately to the line of code, no need to worry about where we are in the project or files.  Once we presses the bookmark id. it will immediately takes you to the line of code.   In order to set the Bookmark, place the cursor to the line of code and press Ctrl+Shift+<ID which sounds the number between 1 to 9>.  Same the way we need to use the same shortcut id to remove the bookmark. Importantly if you use the same bookmark Id on the other places, the previous one will be get deleted.
  • Set - Ctrl+Shift+<ID 1 to 9>
  • Goto Bookmark - Ctrl+<ID>
  • Remove - Ctrl+Shift+<ID 1 to 9>

5. Generate documentation comments to the user defined methods: The documentation for the user defined is more important, it helps the other to review our code and finds the usage details of the params and returning values and it is a adds value to the business logic as well.   Simply place the cursor above the method and put /** <Press Enter>  This will gives you the documentation template where we can fill-up with the description details. 


6. Rename the text and reflect them to all places: Normally most of the developer faces this problem they have created a variable or method or class names, they intended to change i.e. rename that and this needs to be impact on all part of the project without any glitches. 



7. Shortcut to set comments: It is a general things we can use the below key shortcuts to comment the line of codes. 
  • Single - Ctrl+/
  • Select Multiple line - Ctrl+Shift+/





Sunday, 26 March 2017

Git Commands Part 2 - Simple Commit, Pull and Push - Master/Branches

     With continuation to the post


6.     Commit the Changes to the local repository -m indicates the message content on the “message” which is used for the future references & Push the same to the remote branch

git commit -m "employee model class and method added"
git push origin branch0 

7.     Every time we need to keep our branch Ahead of master not behind, because it might have conflicts with other branch code, so we need to resolve and keep it has updated one. (This conflicts and resolve feature will be explained in the next post)

If the remote branch seems to be behind, we need to update the local
repository equivalent to that code.

Go to your local repository first we see how to take an update to the master.

git checkout master
git pull

The master branch will be updated.

Checkout the other branch, get the updated code if anything is need to be get it from the remote branch.

git checkout branch0
git pull
git push origin branch0

Get the updated code from the remote master and push the code to remote branch

git checkout branch0
git pull origin master
git push origin branch0

Same the we can get the updated code from another branch as well

git checkout branch0
git pull origin branch1
git push origin branch0

Git Commands Part 1 - Create, Rename and Delete Branches

This post will help you to play around the Git Commands for creating a branch in both local and remote repository, also guides to rename and deleting the branches.

1.      Create a Branch: Creating a branch in local machine and push that to the remote repository.

Initiate to create a branch & checkout i.e. switches to make use of the branch, the branch has been available in the local 

git branch branch1    
git checkout branch1  
(or)
git checkout -b branch1  

To push this in to the remote use the below command.
git push origin branch1

In case the branch is already created in remote either on Bitbucket or GitHub Portal or any, so now we are need to fetch that & checkout the same into our local.

git fetch origin branch2  
git checkout branch2   
(or)
git fetch && git checkout branch2

2.      Renaming a Branch: We are in the branch2, but want to rename the branch1 as branch0, the below command will reflect on local only, not impact on the remote

git checkout branch1
git branch -m branch0
   
The below command will rename the branch and not necessary the user to
be in the branch which is intended to rename. $git branch -m
<Old Name> to <New Name>

git branch -m branch1 branch0

To reflect the above changes to the remote. 
$git push origin :<old_name> <new_name>

git push origin :branch1 branch0

3.      View the list of branches:
git branch

4.      To-do a self-check, which branch is currently we are working on
git status

5.      Delete a Branch: The below command will help to delete the branch from local.
git branch -d branch0

To delete the same from remote.
git push origin --delete branch0

*To delete the branch, we need not to be in that deleting branch.

          Continue to read Part-2