Tuesday 30 May 2017

Kotlin for Java Developers

From Java To Kotlin 

Java
System.out.print("Umer");
System.out.println("Umer");

Kotlin
print("Umer")
println("Umer")

Java
String name = "Umer";
final String name = "Umer";

Kotlin
var name = "Umer"
val name = "Umer"

Java
String otherName;
otherName = null;
Kotlin
var otherName : String?
otherName = null
Java

if (text != null) {
  int length = text.length();
}

Kotlin
text?.let {
    val length = text.length
}

Java
String firstName = "Umer";
String lastName = "farooq";
String message = "My name is: " + firstName + " " + lastName;
Kotlin
val firstName = "Umer"
val lastName = "farooq"
val message = "My name is: $firstName $lastName"
Java
String text = "First Line\n" +
              "Second Line\n" +
              "Third Line";

Kotlin
val text = """
        |First Line
        |Second Line
        |Third Line
        """.trimMargin()

Java
String text = x > 5 ? "x > 5" : "x <= 5";

Kotlin
val text = if (x > 5)
              "x > 5"
           else "x <= 5"

Java
if (object instanceof Car) {
}
Car car = (Car) object;

Kotlin
if (object is Car) {
}
var car = object as Car

Java
if (object instanceof Car) {
   Car car = (Car) object;
}

Kotlin
if (object is Car) {
   var car = object // smart casting
}

Java
if (score >= 0 && score <= 300) { }

Kotlin
if (score in 0..300) { }
Java
int score = // some score;
String grade;
switch (score) {
 case 10:
 case 9:
  grade = "Excellent";
  break;
 case 8:
 case 7:
 case 6:
  grade = "Good";
  break;
 case 5:
 case 4:
  grade = "Ok";
  break;
 case 3:
 case 2:
 case 1:
  grade = "Fail";
  break;
 default:
     grade = "Fail";  
}

Kotlin
var score = // some score
var grade = when (score) {
 9, 10 -> "Excellent"
 in 6..8 -> "Good"
 4, 5 -> "Ok"
 in 1..3 -> "Fail"
 else -> "Fail"
}

Java
for (int i = 1; i <= 10 ; i++) { }

for (int i = 1; i < 10 ; i++) { }

for (int i = 10; i >= 0 ; i--) { }

for (int i = 1; i <= 10 ; i+=2) { }

for (int i = 10; i >= 0 ; i-=2) { }

for (String item : collection) { }

for (Map.Entry<String, String> entry: map.entrySet()) { }

Kotlin
for (i in 1..10) { }

for (i in 1 until 10) { }

for (i in 10 downTo 0) { }

for (i in 1..10 step 2) { }

for (i in 10 downTo 1 step 2) { }

for (item in collection) { }

for ((key, value) in map) { }

Java
final List<Integer> listOfNumber = Arrays.asList(1, 2, 3, 4);

final Map<Integer, String> keyValue = new HashMap<Integer, String>();
map.put(1, "Umer");
map.put(2, "Ali");
map.put(3, "usman");

// Java 9
final List<Integer> listOfNumber = List.of(1, 2, 3, 4);

final Map<Integer, String> keyValue = Map.of(1, "Amit",
                                             2, "Ali",
                                             3, "Mindorks");

Kotlin
val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to "Umer",
                     2 to "Ali",
                     3 to "usman")

Java
// Java 7 and below
for (Car car : cars) {
  System.out.println(car.speed);
}

// Java 8+
cars.forEach(car -> System.out.println(car.speed));

// Java 7 and below
for (Car car : cars) {
  if (car.speed > 100) {
    System.out.println(car.speed);
  }
}

// Java 8+
cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));

Kotlin
cars.forEach {
    println(it.speed)
}

cars.filter { it.speed > 100 }
      .forEach { println(it.speed)}

Java
void doSomething() {
   // logic here
}

Kotlin
fun doSomething() {
   // logic here
}

Java
void doSomething(int... numbers) {
   // logic here
}

Kotlin
fun doSomething(vararg numbers: Int) {
   // logic here
}

Java
int getScore() {
   // logic here
   return score;
}

Kotlin
fun getScore(): Int {
   // logic here
   return score
}

// as a single-expression function

fun getScore(): Int = score

Java
int getScore(int value) {
    // logic here
    return 2 * value;
}

Kotlin
fun getScore(value: Int): Int {
   // logic here
   return 2 * value
}

// as a single-expression function

fun getScore(value: Int): Int = 2 * value

Java
public class Utils {

    private Utils() {
      // This utility class is not publicly instantiable
    }
   
    public static int getScore(int value) {
        return 2 * value;
    }
   
}

Kotlin
class Utils private constructor() {

    companion object {
   
        fun getScore(value: Int): Int {
            return 2 * value
        }
       
    }
}

// other way is also there

object Utils {

    fun getScore(value: Int): Int {
        return 2 * value
    }

}

Java
public class Developer {

    private String name;
    private int age;

    public Developer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Developer developer = (Developer) o;

        if (age != developer.age) return false;
        return name != null ? name.equals(developer.name) : developer.name == null;

    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "Developer{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Kotlin
data class Developer(var name: String, var age: Int)
Java
public class Utils {

    private Utils() {
      // This utility class is not publicly instantiable
    }
   
    public static int triple(int value) {
        return 3 * value;
    }
   
}

int result = Utils.triple(3);
Kotlin
fun Int.triple(): Int {
  return this * 3
}

var result = 3.triple()

Thursday 3 November 2016

Securing Android App with SSL certificate pinning

SSL Pinning is not a new concept, even then most mobile developers secure their apps by pinning their SSL certificates, only after they get a attack from unknown hacker.
What is certificate pinning?

By default, when making an SSL connection, the client checks that the server’s certificate:
  • has a verifiable chain of trust back to a trusted (root) certificate
  • matches the requested hostname
What it doesn't do is check if the certificate in question is a specific certificate, namely the one you know your server is using.
Relying on matching certificates between the device's trust store and the remote server opens up a security hole. The device’s trust store can easily be compromised - the user can install unsafe certificates, thus allowing potential man-in-the-middle attacks.
Certificate pinning is the solution to this problem. It means hard-coding the certificate known to be used by the server in the mobile application. The app can then ignore the device’s trust store and rely on its own, and allow only SSL connections to hosts signed with certificates stored inside the application.
This also gives a possibility of trusting a host with a self-signed certificate without the need to install additional certificates on the device.

Steps
There are three important steps in the process:
  • obtain a certificate for the desired host (preferably the whole certificate chain)
  • make sure the certificate is in .bks format - this step is crucial in order for pinning to work properly across all devices
  • use Apache HTTP client shipped with Android - initialize it to use the obtained .bks keystore for SSL connections
  • A fully functioning example that demonstrates the solution that we're using can be found here.

Friday 7 August 2015

How to Speed Up Android Studio

Google announced that they were working on Android Studio as the IDE to replace ADT. If you have just started using Android Studio or are new to Gradle, you may have noticed that any of the calls to Gradle perform very slow.  This is very noticeable while trying to build the project.  This is very discouraging. after some search over internet finally i got solutions to solve this problem and that is working for me :) Following are some ways for Android Studio and Gradle Build system to make them perform more faster. 


1. Android Studio 
-Launch: Notepad++ as administrator
-Open: C:\Program Files\Android\Android Studio\bin\studio64.exe.vmoptions
There are a lot of parameters, but we are interested in memory-related parameters:
-Xms: Specifies the initial size, in bytes, of the memory allocation pool.
-Xmx: Specifies the maximum size, in bytes, of the memory allocation pool.
-XX:MaxPermSize: Size of the Permanent Generation.
-XX:ReservedCodeCacheSize: Reserved code cache size
Now, I’m using the following values:
-Xms1024m
-Xmx2048m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=512m

2. Gradle
Gradle is the new build system used in Android Studio
Now, we will configure the global settings of Gradle:
  • Goto: C:\Users\<UserName>\.gradle
    make a new file called “gradle.properties”
  • Add the following lines to the file:
    org.gradle.parallel=true
    org.gradle.daemon=true
  • Launch Android Studio and goto File -> Settings -> Gradle then enable “Offline work”
  • Restart Android Studio and check if there is any Speed Improvement



Tuesday 9 June 2015

Send Email Via Gmail with Java Mail API in Android

To Android app that are capable of sending an automatic mail without prompting user for to address, from address, subject and body of mail. In a simple word, we need to create an Android app that sends from address of the user to a particular mail-ID.

For use of this you need to download the some jar file from Here.
1.  additional.jar
2. mail.jar
3. activation.jar

Download these jar file and make a java build path with your project. 

Below is sendEmail() method for sending email. use this method in your application and enjoy :)


public void sendEmail() throws AddressException, MessagingException {
String host = "smtp.gmail.com";
String address = "abc@gmail.com";
String from = "abc@gmail.com";
String pass = "123456789";
String to = "abc@live.com";
Multipart multiPart;
String finalString = "fsdfsdfdsfdsfdsf";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", address);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Log.i("Check", "done pops");
Session session = Session.getDefaultInstance(props, null);
DataHandler handler = new DataHandler(new ByteArrayDataSource(
finalString.getBytes(), "text/plain"));
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setDataHandler(handler);
Log.i("Check", "done sessions");
multiPart = new MimeMultipart();
InternetAddress toAddress;
toAddress = new InternetAddress(to);
message.addRecipient(Message.RecipientType.TO, toAddress);
Log.i("Check", "added recipient");
message.setSubject("Send Auto-Mail");
message.setContent(multiPart);
message.setText("Demo For Sending Mail in Android Automatically \n");
Log.i("check", "transport");
Transport transport = session.getTransport("smtp");
Log.i("check", "connecting");
transport.connect(host, address, pass);
Log.i("check", "wana send");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
Log.i("check", "sent");

}

Monday 16 February 2015

Android Volley or AsyncTask which approach is better?

A new framework was introduced for Android in Google I/O called Android Volley. This new framework was introduced to reduce the complexity involved in fetching data over network. Being Android developers we all know that fetching data over network is one of the most common task that one has to perform in any Android app. Therefore this new Android Volley library could be a game changer in Android app development. This library pitches in a lot of new features, but the question here is, do we need all these features? Here in this sum up, we would discuss the features of Android Volley vs AsyncTask.
Whenever some new component or library is released, being a developer, first thoughts that come into my mind are:
  1. Why should I use it in my current code base?
  2. Would it ease my development?
  3. Would it improve my app’s functionally?
In short, the answer to all these questions would be: Maybe. As its not always possible to adapt to something new in your current code base. Unless you are planning to refactor the code completely. Although if you see things from a different perspective, new is always better. Since android volley is just a framework on top of existing android framework. This framework is utilizing the power of android in best possible way. Therefore it may turn out to be very helpful for developers.

Android Volley or AsyncTask

To start of we will discuss both the approaches individually. First lets begin with AsyncTask as its the older one.

AsyncTask

Usually in android, simply when one need to access a web API, an AsyncTask is used. Its the standard way to do it in android. You may have also observed that AsyncTask is used in many official code samples. Like whenever a new login activity is inserted through theADT in eclipse, it gives you a stub AsyncTask where you are supposed to write the code for accessing the login API.
The basic code structure used to access data through the AsyncTask is:
Main methods used to access the data from network by AsyncTask are:
  1. onPreExecute() – Usually used to start the loading bar, as this method can interact with UI thread.
  2. doInBackground(Void... params) – Main method in AsyncTask implementation where all the network access code is written. This method has a limitation that it cannot interact with UI thread.
  3. onPostExecute(Void aVoid) – This is the method where result from doInBackground is passed as an argument. Since this method can interact with UI thread. It is used to update the screen with results.
A point to note here is that, in the implementation of doInBackground, one would have to write code to access network, and use classes like HttpURLConnection etc. Although if you are trying to access a completely custom implementation of web APIs this may serve your purpose better. Using AsyncTask to fetch data from network is not a bad approach at all, its just that you don’t get out of the box features like volley has.

Android Volley

Moving forward with this Android Volley vs AsyncTask sum up, let’s have an overview of Android volley.
As mentioned volley is a framework on top of android framework. It simply utilizes the power of android to access the network in best possible way. One of the many advantages of volley is that, you don’t need to write code for accessing network. All of this is managed by volley itself. Whenever a new network request is created, a background thread is spawned for network processing. Whose life-cycle is maintained by volley itself. In default implementation of volley, at a time 4 network threads can do processing simultaneously. To learn in detail about volley, please have a look at this Android Volley example.
With Volley you also get many more out of the box features like:
  1. Retry Mechanism
  2. Caching
  3. Multiple Request Types
    1. JsonObjectRequest
    2. JsonArrayRequest
    3. StringRequest
    4. ImageRequest

Difference between Android Volley and AsyncTask

Like I have been saying new is always better. Using AsyncTask has been a good approach, but consider Android Volley as a 2.0 version of it. It has many improvements over AsyncTask, as volley is designed for the purpose of network access. A major advantage of Android Volley over AsyncTask is that you can do multiple requests simultaneously without the overhead of thread management. Also I believe retry mechanism is a great feature of volley which gives it an edge over AsynTask. Another advantage of volley over AsyncTask is that it provides you with multiple request types, through which complex requests can be made easily. On the other hand while using AsyncTasks one would have to create this type of request manually.
Although best approach differs from application to application. Like if you have less no of requests to make, you can use AsyncTask. As for volley, one has to import a library projectwhich increases your project size. Hence pick wisely between volley and AsyncTask. Hope this Android Volley vs AsyncTask sum up helped you choose. Please like our Facebook and Google+ page for more updates.

Friday 17 October 2014

ART Android runtime

Introducing ART


ART is a new Android runtime being introduced experimentally in the 4.4 release. This is a preview of work in progress in KitKat that can be turned on in Settings > developer options. This is available for the purpose of obtaining early developer and partner feedback.
Important: Dalvik must remain the default runtime or you risk breaking your Android implementations and third-party applications.
Most existing apps should just work when running with ART. However, some techniques that work on Dalvik do not work on ART. For information about the most important issues, see Verifying App Behavior on the Android Runtime (ART).

ART Features


Here are some of the major new features implemented by ART.

Ahead-of-time (AOT) compilation

ART introduces ahead-of-time (AOT) compilation, which can improve app performance. ART also has tighter install-time verification than Dalvik.
At install time, ART compiles apps using the on-device dex2oat tool. This utility accepts DEX files as input and generates a compiled app executable for the target device. The utility should be able to compile all valid DEX files without difficulty. However, some post-processing tools produce invalid files that may be tolerated by Dalvik but cannot be compiled by ART. For more information, see Addressing Garbage Collection Issues.

Improved garbage collection

Garbage collection (GC) can impair an app's performance, resulting in choppy display, poor UI responsiveness, and other problems. ART improves garbage collection in several ways:
  • One GC pause instead of two
  • Parallelized processing during the remaining GC pause
  • Collector with lower pause time for the special case of cleaning up recently-allocated, short-lived objects
  • Improved garbage collection ergonomics, making concurrent garbage collections more timely, which makesGC_FOR_ALLOC events extremely rare in typical use cases
ART currently does not use compacting GC, but this feature is under development in the Android Open Source Project (AOSP). In the meantime, don't perform operations that are incompatible with compacting GC, such as storing pointers to object fields. For more information, see Addressing Garbage Collection Issues.

Development and debugging improvements

ART offers a number of features to improve app development and debugging.

Support for sampling profiler

Historically, developers have used the Traceview tool (designed for tracing application execution) as a profiler. While Traceview gives useful information, its results on Dalvik have been skewed by the per-method-call overhead, and use of the tool noticeably affects run time performance.
ART adds support for a dedicated sampling profiler that does not have these limitations. This gives a more accurate view of app execution without significant slowdown. Sampling support has also been added to Traceview for Dalvik.

Support for more debugging features

ART supports a number of new debugging options, particularly in monitor- and garbage collection-related functionality. For example, you can:
  • See what locks are held in stack traces, then jump to the thread that holds a lock.
  • Ask how many live instances there are of a given class, ask to see the instances, and see what references are keeping an object live.
  • Filter events (like breakpoint) for a specific instance.
  • See the value returned by a method when it exits (using “method-exit” events).
  • Set field watchpoint to suspend the execution of a program when a specific field is accessed and/or modified.

Improved diagnostic detail in exceptions and crash reports

ART gives you as much context and detail as possible when runtime exceptions occur. ART provides expanded exception detail for java.lang.ClassCastExceptionjava.lang.ClassNotFoundException, andjava.lang.NullPointerException. (Later versions of Dalvik provided expanded exception detail forjava.lang.ArrayIndexOutOfBoundsException and java.lang.ArrayStoreException, which now include the size of the array and the out-of-bounds offset, and ART does this as well.)
For example, java.lang.NullPointerException now shows information about what the app was trying to do with the null pointer, such as the field the app was trying to write to, or the method it was trying to call. Here are some typical examples:
java.lang.NullPointerException: Attempt to write to field 'int
android.accessibilityservice.AccessibilityServiceInfo.flags' on a null object
reference
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String java.lang.Object.toString()' on a null object reference
ART also provides improved context information in app native crash reports, by including both Java and native stack information.