Last Updated: April 09, 2018

Koltin Extension functions and Operator Overloading examples

Description: In this post I'm gonna explain you guys how 'Kotlin' gives us the power to play around with our code using 'Extension function' and 'Operator Overloading'.

Note: If you are new to Kotlin. I strongly recommend Switch from Java to Kotlin and Kotlinlang

So lets get started.



1. Kotlin Extension functions:

Why Extensions?
Extension empower as to extend the functionality of the existing classes without overriding the whole structure. Its fun !!!

Syntax:
fun <InheritingClassName>.<functionName>()

e.g : fun String.firstCharacterUpperCase(): String


Example 1:

Consider a requirement about making the first character 'CAPITAL' for logged in user in your app.

Using Extension:

fun String.firstCharacterUpperCase(): String {
    return if (this[0].isLowerCase())
        this[0].toUpperCase().plus(this.substring(1, this.length))
    else        this 
}

Explanation: This extension function return a String by making the first character in 'CAPITAL'

Note: 'this' means the inherited class. In our example its 'String'

So simply call:
fun printName(){
    val name = "nitesh tiwari".firstCharacterUpperCase()
    println("Name: $name")
}

//OutPut:
//Name: Nitesh tiwari


Example 2: 

Consider a requirement of getting a list on odd and even indexes respectively.

Using Extension:
fun <T> ArrayList<T>.oddEvenArrayItems(oddOrEven: Int): ArrayList<T> {
    val list = arrayListOf<T>()
    forEachIndexed { index, genericObject ->
        if (index % 2 == oddOrEven)
            list.add(genericObject)
    }
    return list
}

Explanation: This extension function returns generic ArrayList<T> whose index can we either odd or even based on input params.

So simply call:
fun printData(){
    val arrayList = arrayListOf<Int>(2,3,4,5,6,7,8,9,10, 11)
    val odd = arrayList.oddEvenArrayItems(1)
    val even = arrayList.oddEvenArrayItems(0)

    println("odd: $odd")
    println("even: $even")

    //OUTPUT
    //odd: [3, 5, 7, 9, 11]
    //even: [2, 4, 6, 8, 10]}

2. Operator Overloading:


Why Operator Overloading:
Operator overloading in Kotlin provide us the power to change the implementation of operators like plus(+),times(*),unaryplus(++),plusAssign(+=) and many many more on our 'Custom Objects'. Highly powerful !!!

Note: Operator names should be same.

Syntax:
operator fun <operatorName>()
e.g: operator fun plus()

Example 1: Consider a requirement where you want to add the price of the shopping cartItem together.

class CartItem(val price: Double, val name: String) {

    val itemName: String? = null
    operator fun plus(other: CartItem): Double =
        price + other.price
    
}

fun addPrice() {
    val cartItem1 = CartItem(10.6, "Bag")
    val cartItem2 = CartItem(20.4, "Shoes")

    val total: Double = cartItem1 + cartItem2
    println("Total Cost: $total")

    //OUTPUT:    //Total Cost: 31.0
}
Explanation: We have created a class 'CartItem' which contains the price of the shopping item and overridden the plus(+) operator for adding the prices together and returning the result. Looks simple right?.

Let's checkout one more example to understand operator overloading in combination of extension function


Example 2: Finding the item by productId in the List<CartItem>

class CartItem(val productId: Int, val price: Double, val name: String)

class Cart(val mList: List<CartItem>) {

    operator fun contains(id: Int): Boolean =
        mList.hasProductId(id)

    fun List<CartItem>.hasProductId(productId: Int): Boolean {
        forEachIndexed { _, cartItem ->
            if (productId == cartItem.productId)
                return true
        }
        return false
    }
}

fun checkProductId(){

    //Preparing CartItems
    val cartItem1 = CartItem(1001, 10.6, "Bag")
    val cartItem2 = CartItem(1002, 20.4, "Shoes")

    //Creating CartList
    val cartList = arrayListOf<CartItem>()
    cartList.add(cartItem1)
    cartList.add(cartItem2)

    //Creating Cart

   val cart = Cart(cartList)

    //Finding product
    println("Is 1001 present: " + cart.contains(1001))
    println("Is 1006 present: " + cart.contains(1006))
    
    //OUTPUT
    //Is 1001 present: true 
   //Is 1006 present: false
}

Explanation:
1. We have created a class 'Cart' which will be contain our listOf  'CartItem'.

2. Within our 'Cart' class we have overridden the 'contains' operator which will find whether the productId is within the 'Cart'

3. Finally, we have extension function(hasProductId) on List<CartItem> which returns a Boolean if the productId is present.

Example 3: Comparing two games together.

class GameItem(val scores: Double) {
    operator fun compareTo(item: GameItem): Int = this.scores.compareTo(item.scores)
}

fun compareGame() {

    val gameItem1 = GameItem(100.0)
    val gameItem2 = GameItem(2000.0)

    val result = gameItem1 > gameItem2

    println("Is game1 > game2 ? $result")
    
    //OUTPUT:    //Is game1 > game2 ? false}

Bingo we are done !!!

Let me know if you have any questions in comment box :-)

For more updates follow us on -  Twitter

#codingIsAnArt :-)

Last Updated: December 27, 2017

Things every android developer should know - part 4

Description: In this post, I will show you some interesting tools from Android Studio that developers use.

Also check out Part 1,Part 2  and  Part 3.


So let's get started.


1. Layout Inspector: Layout Inspector is an interesting tool to help track view and their respective properties. It contains-

    •    View Tree - contains the hierarchy of the Android widgets displaying the full nesting of views.
    •    Properties Table - contains the properties attached to the respective view. e.g.: layouts/methods/padding and many more.
 a) How to enable it?
        Goto Tools -> Android -> Layout Inspector fig.1 
     
fig.1 Layout Inspector
 Note: Make sure you have an Android process running for your app and you have an active window present to take the screenshot.

 b) How to understand it?(fig.2)

    Left
       - 'View Tree' showing the full hierarchy of the screen.
   Center
     - Screenshot of the active window       
   Right
      - 'Properties Table' for each view.
  View Click
    - Properties of the widgets get updated on the right pane i.e. 'Properties Table.' and get highlighted on the screenshot screen.


fig.2 Layout Inspector

fig.3 Layout Inspector with Properties

RecyclerView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/percentList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>
RecyclerView Item:

<android.support.percent.PercentRelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/fifty_huntv"
        android:background="#ff7acfff"
        android:text="20% - 50%"
        android:textColor="@android:color/white"
        style="@style/STYLE_PERCENT_TV"
        app:layout_heightPercent="20%"
        app:layout_widthPercent="50%" />
    <TextView
        android:layout_toRightOf="@id/fifty_huntv"
        android:background="#ffff5566"
        android:text="80%-50%"
        style="@style/STYLE_PERCENT_TV"
        app:layout_heightPercent="80%"
        app:layout_widthPercent="50%" />


</android.support.percent.PercentRelativeLayout>


Its an amazing tool to analyse the screen UI for the developers with all the information available on single click. Simply great.



2. How to change the DPI of the Phone using ADB?

Many times in our development phase we want to check the look of Android UI on low/high-end devices. Changing the DPI could come in handy in such cases.

So let get started.

Step 1: Find out your phone's dpi using the below command of adb shell. Search for 'mBaseDisplayInfo='. And then search for density within it. Save it for the future to revert our DPI
adb shell dumpsys display

Step 2: Search for 'mBaseDisplayInfo' and 'density' as shown in fig.4


fig.4 Display Density
Step 3: Finally enter below adb command to change the dpi. (fig.5) with 200dpi,420dpi and 600dpi respectively

adb shell wm density 150



 


Note: If the changes do not reflect you can also try:
adb shell wm density 150 && adb reboot

That it, the screen will be reloaded and icon sizes will change to withstand the density specified in the command.


For more updates follow us on -  
Twitter

Last Updated: August 18, 2017

Switch from Java to Kotlin


Description: In this post I'm gonna show some of the basic syntax and semantics difference while we use "KOTLIN" in your android application w.r.t JAVA(Java v/s KOTLIN).


So let's get started.



1. Variable Declaration
Java:
String name="coderconsole";

Kotlin:
val  name:String="coderconsole"

2. Casting

Java:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);

Kotlin:
val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager

3. Function Declaration

Java:

void methodDeclaration(){
    methodDeclaration("First Method ");
}

void methodDeclaration(String firstParam) {
    methodDeclaration(firstParam, "Second Method ");
}

void methodDeclaration(String firstParam, String secondParams) {
    System.out.println(firstParam + secondParams);
}


Kotlin:


fun methodDeclaration(){
    methodDeclaration("First Method ")
}

fun methodDeclaration(name : String){
    methodDeclaration(name, "Second Method ")
}

fun methodDeclaration(first : String, second: String){
    println(first + second)
}


4. Static Functions and Variable

Java:

class DeviceUtils{
    static final String name = "coderconsole";

    public static String getAndroidId(Context context){
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }
}



Kotlin:


class DeviceUtils {

    companion object {
        val name: String = "coderconsole"
        @JvmStatic fun getAndroidId(context: Context): String = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
   }

}



5. Ternary


Java:
String ternary(String name) {
    return name.equalsIgnoreCase("coderconsole") ? " Ternary success" : " Ternary failed";
}

Kotlin:
fun ternary(name: String): String {
    return if (name.equals("coderconsole"))"Ternary success" else "Ternary failed"
}

6. Operators(this operators are only useful in kotlin)

a) Null Type(?)- variable can be made null only using null type operator

   val array: String = null /** Null cannot be the value of not null type**/ 
   val array: String? = null  /** Bingo! Will work now **/

b) Safe Type:(?.) - Helpful when we donot know when the variable be null.So instead of throwing NPE it return the value as null.

//The below code will return "customerId" if present else return null even if the "customerObject" is null.
fun safeTypeDemo(customerObject: JSONObject?): String?{
         return customerObject?.optString("customerId")     
}

c) Elvis Operator(?:) - Helpful when we want to return some not-null values, if the first result is null.
Java:
int elvisDemo(JSONObject result){
      if (result != null)
        return result.optInt("marks");
     else  return -1;
   }

Kotlin: 
fun elvisDemo(marksObject: JSONObject?): Int {
         return marksObject?.optInt("marks")?:-1      
}
                                 (or)
fun elvisDemo(marksObject: JSONObject?): Int = marksObject?.optInt("marks")?:-1


d) !! operator - throws Null Pointer when asked explicitly
//The below code will throw NullPointerException if customerObject is null.
fun npeTypeDemoDemo(customerObject: JSONObject?): String{
         return customerObject!!.optString("customerId")     
}


7. Loops
a) for loop:
Java
void forLoopDemo(List mList) {
        for (String item : mList)Log.d("Loop", item);
    }

Kotlin
fun forLoopDemo(mList: List) {
       for (item in mList) Log.d("Loop", item)
    }

b) while/do-while: - there is no syntactical difference from Java.

8. Switch Case
Java
void switchCaseDemo(int type) {
    switch (type){
        case 0:
            Log.d("switch", "value - " + type);
            break;
        case 1:
            Log.d("switch", "value - " + type);
            break;
        default:
            Log.d("switch", "value default");
            break;

    }
}

Kotlin
fun switchCaseDemo(type: Int) {
    when (type) {
        0 -> Log.d("switch", "value - " + type)
        1 -> Log.d("switch", "value - " + type)
        else -> Log.d("switch", "value default")
    }
}


9. Extends/Implements

//This sample contains abstract class and an interface to printData.
public abstract class AbstractA {
    public void printAbstractData(String data){
        System.out.println(data);
    }
}
public interface InterfaceA {
    public void printData(String data);
}


public class ExtendsImpDemo extends AbstractA implements InterfaceA {
    @Override    public void printData(String data) {
        printAbstractData(data);
    }
}


Kotlin

abstract class AbstractA{
    public fun printAbstractData(data: String){
        println(data)
    }
}

interface InterfaceA{
    fun printData(data: String)
}

class ExtendsImpDemo : AbstractA(), InterfaceA {
    override fun printData(data: String) {
        printAbstractData(data)
    }
}


10. Iterating JSONArray

Java:
void arrayTest(JSONArray jsonArray) {
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.optJSONObject(i);
        Log.d("ArrayTest", jsonObject.optString("name"));
    }
}

Kotlin:
fun arrayTest(jsonArray: JSONArray){
    jsonArray.items<JSONObject>().forEachIndexed { i, jsonObject ->
        Log.d("ArrayTest", jsonObject.optString("name"))
    }
}

Kotlin is an awesome language and very fun to write code in it.
For further reference you can try https://try.kotlinlang.org

For more updates follow us on -  Twitter

Last Updated: January 11, 2017

Introduction to Internet of things platform Octoblu

Description: 

In this post I'm gonna describe very helpful platform for building some stuff that involves 'Internet of thing'/ Internet of apis.
 
So lets get started.




Octoblu - It's an platform to build an amazing iot/iota projects that involve connection of  'things' with variety of tools involved in it. The 'things' could be sensors/led lights/apis from social networks like G+ or twitter etc.


Few key terms
  1. Things - Entity that you need to integrate. E.g: Twitter, G+, Http Api,Sensors etc.
  2. Tools - Connectors to connect the things. E,g: Less than, Greater than operators, Timer.
  3. Flow - Actual Work space which contains THINGS and TOOLS
  4. Bluprints - Final Shared FLOW is Bluprint.
Note: 1. For the sake simplicity we're gonna build a Flow which triggers Twitter post after 5 mins.
          2. DONOT spam your timeline. This may result about your account may get blocked.

Step 1: Create flow

 After successful signup create an Flow and enter name and description as per your choice from  "Flow Inspector" as shown  in fig.1

Flow Inspector
fig.1


Step 2: Add things.

After creating dummy flow its time to add "Things". For our demo we're gonna add "Twitter" as our thing from the Things tab.

Select the endpoint as "Post Tweet" and add a message for post.
Add status as "Hello world"

 As shown in the fig.2.

Note: You can also search through the things and simply drag and drop. You have to add your twitter account for testing.
Coderconsole
fig.2

Step 3: Add trigger.

After adding "Things" its time to add trigger to initiate our twitter post. You can find triggers within the "Tool" tabs as shown in the fig.3

Trigger
fig.3

Step 4: Connection


Now comes the best part "Connections" .Octoblu connections are seamless. We have two points for each "trigger" and "things" simple drag from one point to another as shown in fig4.

Connections
fig.4

Step 5: Lets wrap everything up.


Now simply run the flow created above as shown in fig.5 this will make sure your flow is ready to get triggered

Note: You have to run the flow every time whenever you have made any changes

fig.5




Step 6: Trigger the flow 

Simple click the play icon on the trigger. fig.3. This is trigger your twitter post with the text as "Hello world" on your twitter profile page.

Thats It !!!

How to debug?

This will help to figureout whats happening whenever the trigger  is initiated.

To debug the flow

  1. You have to enabled "DEBUG" mode from "Thing Inspectors" by  first clicking the things on the flow first.

How To Automate?

1. To automate you can use a tool called as "INTERVAL" and can assign the triggering time as 5 minutes


So finally we have automated our twitter post using "Octoblu". It has got immense power and can come handy for demo projects involving 'Internet of things/Internet of APIS'.

For more updates follow us on -  Twitter


Last Updated: October 20, 2016

Things every android developer should know - part 3

Description: In this post I'm gonna demonstrate some useful tips which we could come handy in our app development life cycle

Also check out Part 1 and Part 2.

So let 's get started.


1. Grant all permissions at once in Marshmallow and above.  

As we know marshmallow compatible apps require permissions. So we normally show permission dialog to the user asking to grant us. That's fine. But every time clicking that 'allow' feels annoying for developers.

So the idea is to allow all the permissions at once without every time clicking the allow button.

Below  shell script will help to make it happen flawlessly.
#!/bin/sh

#add your package_name
PACKAGE=com.app.code2concept

#create array with all the permission you need to enabled    
PKG_ARRAY='android.permission.CALL_PHONE
        android.permission.GET_ACCOUNTS
        android.permission.READ_SMS
        android.permission.READ_CONTACTS
        android.permission.ACCESS_FINE_LOCATION
        android.permission.CAMERA
        android.permission.WRITE_EXTERNAL_STORAGE'

#lets exceute our command
for permissions in $PKG_ARRAY; 
do
 echo $permissions + ' granted'
 adb shell pm grant $PACKAGE $permissions
done

echo 'Bingo its done'
OUTPUT:
$ sh grant_all_permissions.sh
android.permission.CALL_PHONE +  granted
android.permission.GET_ACCOUNTS +  granted
android.permission.READ_SMS +  granted
android.permission.READ_CONTACTS +  granted
android.permission.ACCESS_FINE_LOCATION +  granted
android.permission.CAMERA +  granted
android.permission.WRITE_EXTERNAL_STORAGE +  granted
Bingo its done'

Before


After





2. Battery Historian

Battery historian translate the battery stats into visualization form thereby helping us to figure out whats the cause and how we can optimized our battery usage.

Pre-requisite:
1. 'adb' is configured
2. Devices is detectable using 'adb devices' command
3. Python(2.7)  is install and path is set.

Step 1: Reset the battery stats to fetch fresh info using below
adb shell dumpsys batterystats --reset

Note: Disconnect phone and explore the app for few minutes and connect again

Step 2: Capture 'batterystats' using below command
adb shell dumpsys batterystats > batterystats.txt

Note: The command creates a file name 'batterystats.txt' into the current directory

Step 3: Clone or download the Github repo of 'Battery Historian' from Here. You will find a python script at path '../battery-historian/scripts/historian.py'

Note: You can keep both 'historian.py' and 'batterystats.txt' in the same folder for ease

Step 4: Finally let execute the python script against our 'batterstats.txt' as input as show below
python historian.py batterystats.txt > batterystats.html
This will create 'battertstats.html' fig.1 which we can use to analyse the battery usage as shown HERE.

Historian
fig.1

Last Updated: July 30, 2016

Android Data binding

Description: In this post I'm gonna illustrate concept of 'Data Binding' in android. So straight away.

Let's get started.



'DataBinding' in android was introduced as an effort to coupled the model i.e data directly into the view, thereby eliminating findViewById()  at much larger extend. Although its not limited to this and can help to remove lots of boilerplate code thereby. Its the direct roadway to implement MVVM pattern in our apps.

Prerequisite:

1. Add below snippets into your 'Modulebuild.gradle within 'android' section
    dataBinding {
        enabled true
       }

2. Now just add below line within the your 'Project'  build.gradle within 'dependencies' section.
Note: The gradle plugin should be greater or equals v1.5 +
 classpath 'com.android.tools.build:gradle:1.5.0 

Let's start with simple example of how to eliminate findViewById in activity.

1. Eliminate findViewById();

Step 1: Simply create a model with a field name as 'title' and also the POJO for the same.

public class SingleModel {

    private String title;

    public SingleModel() {
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

Step 2: In our activity_main.xml wrap your parent layout within '<layout> ...< /layout>' . As shown below. Create a <data> ...</data> tag with <variable>...</variable> to access its model variables

   <layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <variable
            name="single"
            type="com.code2concept.databinding.models.SingleModel"/>
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@{single.getTitle()}"/>
    </RelativeLayout>
</layout>

Note: 1. Once you have created a variable into <layout> apt builds the binding file name BR.java(similar concept what R.java doeswhich and other binding functions.

Step 3: Lets integrate in our MainActivity. 

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding mainActivity = DataBindingUtil.setContentView(this, R.layout.activity_main);

        SingleModel singleModel = new SingleModel();
        singleModel.setTitle("Wow ! Data binding is awesome");
        mainActivity.setVariable(BR.single, singleModel);

    }
}

Bingo ! we have integrated databinding in our app







2. Handle click.

Step 1: Create a <variable> ... </variable> tag with name and type as shown below.

Note: Type can be created from separate class as well. We're gonna implement onClick in Activity.

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="single"
            type="com.code2concept.databinding.models.SingleModel"/>

        <variable
            name="singleClick"
            type="com.code2concept.databinding.MainActivity"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:onClick="@{singleClick.onClick}"
            android:text="@{single.getTitle()}"/>
    </RelativeLayout>
</layout>

    

Step 2: Finally bind the singleClick to the activity as shown below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding mainActivity = DataBindingUtil.setContentView(this, R.layout.activity_main);

        SingleModel singleModel = new SingleModel();
        singleModel.setTitle("Wow ! Data binding is awesome");
        mainActivity.setVariable(com.code2concept.databinding.BR.single, singleModel);

        //bind click to the  activity
        mainActivity.setSingleClick(this);
    }

    @Override
    public void onClick(View view) {
        Toast.makeText(this, "Single Model view is clicked", Toast.LENGTH_SHORT).show();
    }
}

Great, we have handled onClick event as well

Question: what happens when the content of the view need to be changed in the runtime?.
No need to worry 'DataBinding' helps us effortlessly.






3. NotifyChangeProperty

Step1: Add @Bindable annotation to the getters and notifyPropertyChanged() to the setters as shown below.

public class SingleModel extends BaseObservable {

    private String title;


    @Bindable
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
        notifyPropertyChanged(BR.title);
    }
}

Step 2: Finally lets change our title on onClick. fig.1

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private SingleModel singleModel;
    private ActivityMainBinding mainActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = DataBindingUtil.setContentView(this, R.layout.activity_main);

        singleModel = new SingleModel();
        singleModel.setTitle("Wow ! Data binding is awesome");
        mainActivity.setVariable(BR.singleModel, singleModel);

        //bind click to the  activity
        mainActivity.setSingleClick(this);
    }

    @Override
    public void onClick(View view) {
        singleModel.setTitle("Title is changes successfully");
    }
}

databinding
fig.1

Awesome, finally we have integrated databinding in our project ;-). Part 2 coming soon


Last Updated: April 17, 2016

Things every android developer should know - part 2

Description: In the post, we'll continue the legacy of  Part 1 :-). Below are some tools provided by Google Android which is helpful for Android developers during the development and debugging session of the Production app issues

So let's get started :-)





Note: If you have missed part 1. Please refer here

1. Capture or record screen without any external app.

Often we are required to take snapshots of the app's screen or even record a video to show some features to colleagues QA or Clients. It comes in handy very often.

Step 1: Simply connect your device. Open the Android Monitor from Android Studio you'll see as fig.1.
http://code2concept.blogspot.in/
fig.1
Step 2: Now, you can open your app and click on the camera icon from the Android monitor located in the extreme top-left corner to capture any screen you want. Bingo !!!

For video: Click the video icon below the camera icon. Enter the resolution with multiples of 16x. fig.2. That's it. It'll start recording your actions on the app.

http://code2concept.blogspot.in/
fig.2



2. How to find layout boundaries?

Layout boundaries are very useful when we develop our UI components. It gives a real sense of layout, thereby letting us study the arrangement of different widgets in the layout.

Step 1: Open Settings - Developer Options - Show layout boundaries. From drawing section

https://www.linkedin.com/in/nitesh-tiwari-b5032a74
fig.3.LinkedIn app

fig.3. A Simple analysis of pencil icon. (without opening our layout)

1. The Edit pencil icon has some padding to it. 
2. It's aligned to the top-right corner of its parent layout.

Really awesome.





3. How to debug obfuscated code using proguard tool?

Note: This tool is inbuild provided by Google Android Sdk for developers and is helpful during debugging for live issues 

As we know, code is obfuscated when we build our app with Proguard enabled. We often come in contact with obfuscated code in our app while debugging the stack trace of the crashes.

So decoding is very much needed to study the stack trace. Android builds a file called "mapping.txt" which serves as the key ingredient to decode, in a combination with "retrace".

In Windows

Step 1: Go to  (android-studio-install-dir-path)\tools\proguard\bin  open "proguardgui.bat"  fig.4

fig.4
Step 2: Click on "ReTrace" fig.5. and upload your "mapping.txt" file from app/build/outputs/mapping/.../mapping.txt   and the obfuscated code file (e.g: crash.txt). You can also simply paste the stack trace in the box provided.

http://code2concept.blogspot.in/
fig.5
You can also use command line code to do that.

\tool\proguard\bin> retrace.bat -verbose   (path_to_mapping.txt)\mapping.txt  (path_to_stacktrace)\crash.txt


For more updates follow us on -  Twitter

#codingIsAnArt
#coderconsole

Last Updated: February 16, 2016

How to create google chrome extension in 3 simple steps?

Description: In this post I'm gonna show you 3 simple steps to create your own google chrome extension.You can simply follow the steps with tips and note listed in between the post.

So lets get started.




Step 1: Create a folder namely('chrome_extension_demo') with 4 files in it index.html, main.js, manifest.json & extension.css.

Step 2: Lets add code into above files.
Tip: you can simply open the folder in any editor like(Sublime or Notepad++ for ease to write code)

  • index.html(contains our basic html code with few buttons on it)

<html>
<head>
 <title>Code2Concept extension demo</title>
 <script src="main.js"></script>
 <link rel="stylesheet" type="text/css" href="extension.css">
</head>
<body background="bg.png">
 <h1 align="center" id="code2concept"><a href=""><font color="white">Code2Concept</font></a></h1>
 <center>
  <div class="buttonContainer">
   <div>
    <button id="home" class="button">Home</button>
    <br/>
    <br/>
   </div>
   <div >
    <button id="twitter" class="button">Twitter</button>
    <br/>
    <br/>
   </div>
   <div>
    <button id="my_linkedin" class="button">My LinkedIn</button>
    <br/>
    <br/>
   </div>
   <div>
    <button id="stackoverflow" class="button">Stackoverflow</button>
    <br/>
   </div>
  </div>
  <hr/>
  <h5> <font color="white">This is the demo to create google chrome extension.</font></h5>
 </center>
</body>
</html>



  • manifest.json(simple json file which is needed by chrome to add extension)
{
  "manifest_version": 2,

  "name": "Code2Concept extension demo",
  "description": "This is the Code2Concept extension to demostrate chrome extension",
  "version": "1.0",

  "background":{
  "scripts": ["main.js"]
  },
  
  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "index.html"
  },
  "permissions": [
   "activeTab"
   ]
}

  • main.js(javascript code to add listener to our buttons)
document.addEventListener('DOMContentLoaded', function() {

 //home
  var home = document.getElementById('home');
  home.addEventListener('click', function() { 
    openUrl('http://bit.ly/1LqS9ku');
  }, false);

   //twitter
  var twitter = document.getElementById('twitter');
  twitter.addEventListener('click', function(){
    openUrl('http://bit.ly/20XuV1K');
  }, false)

  //stackoverflow.
  var stackoverflow = document.getElementById('stackoverflow');
  stackoverflow.addEventListener('click', function(){
   openUrl('http://bit.ly/1olt4D5');
  }, false)

//my linkedIn public dir.
  var my_linkedin = document.getElementById('my_linkedin');
  my_linkedin.addEventListener('click', function(){
   openUrl('http://bit.ly/1Tn6BBJ');
  }, false)


  //open url function in new tab
  function openUrl(newURL) {
    chrome.tabs.create({ url: newURL});
  }

}, false);



  • extension.css(css for buttons)
.button {
 border: 1px solid #13cbbb;
    border-radius: 3px;
    color: #FFFFFF;
    display: inline-block;
    float: center;
    font-size: 12px;
    margin-right: 3.2%;
    background-color: #13cbbb;
    padding: 7px 4.0%;
    width: 100px;
    min-width: 100px;
    max-width: 100px;
}
.button:hover {
 background-color:#13cbbb;
 opacity: 0.7;
}
.button:active {
 position:relative;
 top:1px;
}

.buttonContainer{
    width: 160px;
}

Note: You can download bg.png from here  and  icon.png  from here and place in the folder created in step 1:




Step 3: The most important step is how to add our code in chrome browser. Open chrome settings from hamburger icon on the right of  browser. Settings --> extensions --> load unpacked extension(select your folder created instep 1) --> fig.1


Chrome extension code2concept

Finally you'll see the your extension add to the chrome as shown in fig.2.
Chrome extension
fig.2

  • If you find some issue implementing simply download and follow step 3.

  • To upload on chrome web store go here since we have developed this into developer mode.

Bingo!!! you have created your first chrome extension successfully.

Last Updated: February 09, 2016

Things every android developer should know - part 1



Description: In this post, I'm gonna demonstrate tools that help solve some common problems while app development & help increase the speed as well.

So let's get started :-)


1. How to run app on phone without USB cord.(need USB initially to make connection

Note: Android Studio has provided a more sophisticated option to connect without USP using wireless debugging. Do check out the blog


Step 1: Connect the device with the cord to your system. Ensure that USB debugging is enabled from Developer options. Open cmd(windows) or Terminal(Linux) run the command. You'll find the connected device.
adb kill-server && adb devices
Step 2: Run the next command to restart in tcp mode on port 5555
adb tcpip 5555
Step 3: Now disconnect your device from the system and note down your ip address of the phone from Setting > About Phone > Status

E.g It could be something like 192.168.0.3(IP address) Now run the final command by replacing it with your IP address
adb connect 192.168.0.3:5555
Bingo we're done now your device is connected and you can run it wirelessly :-)

2. How to find SHA1 key from android studio?

SHA1 key is needed in many different apps containing maps or social sites authentication or using any Google apps and services. It's super useful. So the simplest way to get that is using Android Studio.

Step 1: Select the Gradle projects from the right pane and expand Tasks > Android> signingReport. (fig.1).

Note: If you do not find your project in Gradle Projects sync the project from Android Studio.

Gradle Project
fig.1


3. Best way to create icons for android app using vector asset.

Many times in our development we need icons for small things with varied colors or shape. Using Vector Asset in Android Studio we can create our icons with super ease.

Step 1: Right-click on app > New > Vector Asset you'll see Fig. 3. You can choose Material Icons which contains a whole lot of icons in different categories. This will create <vector> for the icon you have selected. (fig.4) in drawable folder

Vector Asset
fig.3
Vector Asset for the icon
Vector xml

fig.4
Step 2: Awesome now just we can simply set it to background or src of ImageView and other widgets.


For more updates follow us on -  Twitter

#codingIsAnArt
#coderconsole

Last Updated: January 12, 2016

How to schedule script in windows Vista 7,8 or 10 ?

Description: In this post I'm gonna show how we can schedule a script using windows task scheduler for Windows vista, 7 ,8 or 10 ?



So lets get started:



Step 1: Create a file with .vbs extension with below line of code in it.

window = msgbox("Code2Concept demo for script scheduling", 39, "Info")

This is to display our message box when our trigger get fired as per our schedule


Step 2: Open Task Scheduler (fig.1) by searching in windows search or from control panel
fig.1















Step 3: Create new Task (fig.2)with name and description.

fig.2















Step 4: Lets browse and add our script created in Step 1:  from Action tab. Also add Triggers as time to schedule the script to run. (fig.3 & fig.4 respectively).

fig.4


fig.5

Output:

Bingo !!! We are done. You can now view your dialog at specific schedule interval