Sunday, 15 September 2019

Kotlin Code to break forEach inline loops

In General we are unable to break the forEach inline loops.  Please check the below tries and see the proper way to do so.

1
2
3
4
5
6
7
8
9
 var data = listOf<String>("Dev", "Prd", "Test", "Sbx", "demo")
    data.forEach {
        if (it.equals("Prd")) {
            println("I'm Selected $it")
            return
        }
        println("I'm in the list $it")
    }
    println("Done")

the above code produces the below output, if we use "return" on the line 5 we will be getting the below output, because that will abundantly break and come out of the method.  You can see the "Done" is not printed.

I'm in the list Dev
I'm Selected Prd

Hence to resolve we can try out with the label concept available in kotlin,  Since our programming language says there is no explicit label needed for the inline function. we can directly use it as "return@forEach".  But this will also lead to be failed, this produces the below output.

I'm in the list Dev
I'm Selected Prd
I'm in the list Test
I'm in the list Sbx
I'm in the list demo
Done

The highlighted text are unnecessary to this case.  In the below code snippet run block with label is used to break the loop as soon as we get the expected result and breaks the blocks and proceeds the normal flow function flow.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var data = listOf<String>("Dev", "Prd", "Test", "Sbx", "demo")
    run envBlock@{
        data.forEach {
            if (it.equals("Prd")) {
                println("I'm Selected $it")
                return@envBlock
            }
            println("I'm in the list $it")
        }
    }
    println("Done")

And will get the expected output.


I'm in the list Dev
I'm Selected Prd
Done

Happy Coding :-)

Saturday, 20 July 2019

Kotlin Code - Get IPV4 & IPV6 Address

The below code helps to get the IPv4 and IPv6 Address using Kotlin.

import java.net.NetworkInterface
import java.util.*

/*
* Author: Rajendhiran E
* Date: 21-Jan-2018
* */

object IPHelper {
    val IPV4Address: String
        get() = getIPAddress(true)

    val IPV6Address: String
        get() = getIPAddress(false)

    /**
     * Get IP address from first non-localhost interface
     * @param userIPV4 true=return ipv4, false=return ipv6
     * @return address or empty string
     */
    private fun getIPAddress(userIPV4: Boolean): String {
        try {
            Collections.list(NetworkInterface.getNetworkInterfaces()).forEach {
                Collections.list(it.inetAddresses).forEach {
                    if (!it.isLoopbackAddress) {
                        val sAddr = it.hostAddress
                        val isIPv4 = sAddr.indexOf(':') < 0
                        if (userIPV4) {
                            if (isIPv4) {
                                return sAddr
                            }
                        } else {
                            if (!isIPv4) {
                                val delim = sAddr.indexOf('%')
                                return if (delim < 0) sAddr.toUpperCase() else sAddr.substring(0, delim).toUpperCase()
                            }
                        }
                    }
                }
            }
        } catch (ignored: Exception) {
        }
        return ""
    }
}


println("IP Address V4 - ${IPHelper.IPV4Address}")
println("IP Address V6 - ${IPHelper.IPV6Address}")


Output  Console
IP Address v4 - 192.168.240.2
IP Address v6 - FE80:0:0:0:4D9:5C92:3433:8A6B

Happy Coding :-)

Sunday, 17 December 2017

ExpandableListView - notifyDataSetChanged() - Tricky

In general, we use to call the notifyDataSetChanged() method for updating the list view with our new data sets i.e. objects with either array list or any collections. This data set updations made in course of load more or pull to refresh etc.

While using the listview we can simply update the data-set object and call the notifyDataSetChanged() method from the adapter. It will take care the necessary action of updating the listview.  But this will not been happens in the case of ExpandableListView, hence it requires few thread based handling and again need to set the updated adapter to the ExpandableListView.  Please find below the code snippet for the same.


if (dataList.size() > 0) {
 if (!isShowMore) {
  dataListGlobal = dataList;
  dataListExpandableAdapter = new DataListExpandableAdapter(getActivity(), dataListGlobal);
  expandabaleDataListView.setAdapter(dataListExpandableAdapter);
 } else {
  dataListGlobal.addAll(dataList);
  getActivity().runOnUiThread(new Runnable() {
   public void run() {
    if (dataListExpandableAdapter != null) {
     dataListExpandableAdapter.notifyDataSetChanged();
     expandabaleDataListView.setAdapter(dataListExpandableAdapter);
    }
   }
  });
 }
}

Happy Coding :-)

Tuesday, 12 December 2017

Add/Remove View on the Top of Activity or Fragment Android


Add view on to the top of your activity or fragment i.e. in simple to add custom view above the AppCompact/Support Toolbar.

FrameLayout rootLayout = (FrameLayout) findViewById (android.R.id.content);
View v = View.inflate(this, R.layout.overlay_layout, rootLayout);

Then when you want to remove it, below use the below code snippet

FrameLayout rootLayout = (FrameLayout)findViewById(android.R.id.content);
rootLayout.removeViewAt(rootLayout.getChildCount()-1);


Happy Coding :-)

Sunday, 26 November 2017

Sunday, 22 October 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

Monday, 2 October 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'
            ]
        }
    }