Sunday 16 December 2018

Http and Https request from Android Pie onwards

Recently I faced a weird situation where my app was working fine in all Android versions except Android Pie.

java.io.IOException: Cleartext HTTP traffic to * not permitted

After lots of debugging I came to know it was because my server was not secure ie it was using HTTP (not HTTPS). Android P uses HTTPS by default. What this means is that if you are using unencrypted HTTP requests in your app, the app will work fine in all versions of Android except Android P.

Let’s consider two situations where your app won’t work properly in Android P. 

1. If your server is on HTTP obviously it won’t work in Android P. 

2. When your server is on HTTPS but it is returning something like an image URL which is HTTP, you won’t be able to load the image in Android P.

From Android 9 Pie now, requests without encryption will never work. The System will expect you to use TLS by default.

The easy way to implement this is to use this attribute to your AndroidManifest.xml where you allow all http for all the requests.

android:usesCleartextTraffic=”true”

We have to add these lines to the application tag like below.

<application android:usesCleartextTraffic="true" />

Cleartext is any transmitted or stored information that is not encrypted or meant to be encrypted.

When an app communicates with servers using a cleartext network traffic, such as HTTP, it could raise a risk of eavesdropping and tampering of content. Third parties can inject unauthorized data or leak information about the users. That is why developers are encouraged to a secure traffic only, such as HTTPS.  Hence the cleartext is inevitable, but we can fix the error at the application end

Going with general fix is not the good solution, We have to fix it on our backend by making the request to support for https, but there is some exceptional cases i.e. If we are allowing http for some domains but not other domains, then we have to do some configurations to make this to work.

We have to create a new file inside our XML folder network_security_config.xml now paste the below code snippet inside the file.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">abc.com</domain>
	<domain includeSubdomains="true">pqr.com</domain>
    </domain-config>
</network-security-config>

You can add the domain of your choice in place of abc.com / pqr.com

To make this work, we have to define a networkSecurityConfig in the application of our Manifest file tag like this:

<application android:networkSecurityConfig="@xml/network_security_config" />

Thatz It... Happy Coding :-)

Sunday 23 September 2018

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

Tuesday 3 July 2018

File path too long on windows, keep below 240 characters?



Generally our tyro's might get this kinda of issues because of having a deep || hard folder linking like in a tree hierarchy. For Example: 

D:\user\rajendhiran\personal\training\projects\android_projects\application\........

Code Fix to this issue:
Just do a below code change in your root build directory, since that is where most of the path issues will arise.


1
2
3
4
5
6
allprojects {
    buildDir = "C:/tmp/${rootProject.name}/${project.name}"
    repositories {
       ...
    }
}

Reference Link: http://goo.gl/E6BNoU

Sunday 18 March 2018

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

Sunday 28 January 2018

Android Top 10 Important libraries, keep code you with the best practices


Android Top 10 Important libraries which helps us to maintain the good code practices in general.
Gson: Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. 

Retrofit, OkHTTP, Loopj: Retrofit is a type-safe REST client for Android (or just Java) developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp.  OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with call-backs.  Loopj is an Android library for making asynchronous HTTP requests. I like it for its ease of use and simplicity. Created by James Smith, it's also known as "Android Asynchronous HTTP Client", and it's used by companies like Instagram, Pinterest, and many others. It's a good entry point to the world of HTTP libraries, and will help you understand important concepts very easily.

Otto:  Otto is an event bus designed to decouple different parts of your application while still allowing them to communicate efficiently.  Forked from Guava, Otto adds unique functionality to an already refined event bus as well as specializing it to the Android platform.

Realm: Realm is a mobile database and a replacement for SQLite. Although is an OO database it has some differences with other databases. Realm is not using SQLite as its engine. Instead it has own C++ core and aims to provide a mobile-first alternative to SQLite. Realm store data in a universal, table-based format by a C++ core. This is what allows Realm to allow data access from multiple languages as well as a range of ad hoc queries.

Universal Image Loader, Picasso, Glide & Fresco:  These libraries are powerful, flexible and highly customizable instrument for image loading, caching and displaying. It provides a lot of configuration options and good control over the image loading and caching process.

Dagger2, Butterknife: Dagger 2 analyses these dependencies for you and generates code to help wire them together. While there are other Java dependency injection frameworks, many of them suffered limitations in relying on XML, required validating dependency issues at run-time, or incurred performance penalties during start-up. Dagger 2 relies purely on using Java annotation processors and compile-time checks to analyse and verify dependencies. It is one of the most efficient dependency injection frameworks built to date.   Butterknife, Field and method binding for Android views which uses annotation processing to generate boilerplate code for you.

LeakCanary:  The memory leak can be a headache to detect and to resolve, small memory leaks can be hidden and may be seen after a long usage of the application and hunting memory leaks is not a simple task. 

Databinding MVVM: Android offers support to write declarative layouts using data binding. This minimizes the necessary code in your application logic to connect to the user interface elements.

RxJava & RxAndroid: This module adds the minimum classes to RxJava that make writing reactive components in Android applications easy and hassle-free. More specifically, it provides a Scheduler that schedules on the main thread or any given Looper.

MPAndroidChart: Using these libraries, drawing charts on Android could never be simpler. MPAndroidChart library works on Android API 8 and above, but if you are using animations, it works on API 11 and above. Animations is one of the greatest features apart from easy data input, this library could have. Somehow I feel animations give good user experience to an application. Through MPAndroidChart library, we can use more than 25 inbuilt animations, also can define custom animations.

Tuesday 16 January 2018

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 :-)