Search

Saturday, October 31, 2015

Appium Android Test Using Different Element Locators

Earlier in THIS POST, We learnt different element locators of android app like XPath, ID, Name And className to use in appium automation test script. We also learnt android application's element locating strategy using findElements method of webdriver. I have prepared very simple appium android app test of real android mobile device's calculator application where I have used all above element locating strategies so that you can understand android app element locators better.

PREREQUISITES : Appium android tutorial articles 1 TO 15 and 16 TO 17 should be completed.

After reading all previous appium tutorials, I hope you have enough knowledge on how to run appium test on real android device or emulator. Now let's Implement appium android test and understand how to use different element locators in android appium automation test. Follow steps given bellow.

1. Connect your android device with PC and start USB debugging mode. View THIS POST.
2. Launch and start appium server. View THIS POST.
3. Install TestNG in eclipse if it is not installed. View THIS POST.
4. Create bellow given appium android test script under Android package of your project in eclipse.

ElementLocatorTest.java
package Android;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class ElementLocatorTest {

WebDriver driver;

@BeforeTest
public void setUp() throws MalformedURLException {
// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set android deviceName desired capability. Set your device name.
capabilities.setCapability("deviceName", "ZX1B32FFXF");

// Set BROWSER_NAME desired capability. It's Android in our case here.
capabilities.setCapability("browserName", "Android");

// Set android VERSION desired capability. Set your mobile device's OS version.
capabilities.setCapability("platformVersion", "4.4.2");

// Set android platformName desired capability. It's Android in our case here.
capabilities.setCapability("platformName", "Android");

// Set android appPackage desired capability. It is com.android.calculator2 for calculator application.
// Set your application's appPackage if you are using any other app.
capabilities.setCapability("appPackage", "com.android.calculator2");

// Set android appActivity desired capability. It is com.android.calculator2.Calculator for calculator application.
// Set your application's appPackage if you are using any other app.
capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

// Created object of RemoteWebDriver will all set capabilities.
// Set appium server address and port number in URL string.
// It will launch calculator app in android device.

driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}

@Test
public void Sum() {
// Using findElements.
// Locate DELETE/CLR button using findElements and get() method and click on it.
driver.findElements(By.xpath("//android.widget.Button")).get(0).click();

// By xpath.
// Locate number button 2 by XPATH element locator and click on it.
driver.findElement(By.xpath("//android.widget.Button[@text='2']")).click();

// Using findElements.
// Locate number button + using findElements and get() method and click on it.
driver.findElements(By.xpath("//android.widget.Button")).get(16).click();

// By id.
// Locate number button 5 by ID element locator and click on it.
driver.findElement(By.id("com.android.calculator2:id/digit5")).click();

// By name.
// Locate number button = by name element locator and click on it.
driver.findElement(By.name("=")).click();

// By className.
// Locate result textbox by CLASSNAME element locator and get result from it.
String result = driver.findElement(By.className("android.widget.EditText")).getText();
System.out.println("Number sum result is : " + result);

}

@AfterTest
public void End() {
//Quit
driver.quit();
}
}

Each and every element locator is already explained in comment with test script's each statement. You can see in above script, I have used all different element locators to locate different elements of android calculator app.
  • findElements with get() method : findElements with get() method element locating strategy is used to locate DELETE and + buttons of calc app. Here "android.widget.Button" is common class name of all buttons. So It will find all elements which contains class name = "android.widget.Button" and then get() method will locate given Indexed element from list. DELETE button has index = 0 and + button has index = 16.
  • xpath : xpath element locator is used to locate number button 2. Here "android.widget.Button" is class name and then it will look for element where text value = "2".
  • id : id element locator is used to locate number button 5. Here it will directly look for element where resource-id="com.android.calculator2:id/digit5".
  • name : name element locator is used to locate = button. In this case, It will look for element where text value = "=".
  • className : className element locator is used to locate result text area. It will find element where class value = "android.widget.EditText".
I hope, this is enough to understand android app element locators. You can use all above described element locators for any application.

Now you can run above appium android test script using testng(Right click on test case -> Run As -> TestNG Test) in eclipse. It will print result two number's sum result in console.

2 Ways to find duplicate elements in an Array - Java

Problem: You have given an array of objects, which could be array of integers and or array of Strings or any object which implements Comparable interface. How would you find duplicate elements from array? Can you solve this problem in O(n) complexity? This is actually one of the frequently asked coding problems from Java interviews. There are multiple ways to solve this problem and you will learn two popular ways here, first the brute force way, which involves comparing each element with every other element and other which uses a hash table like data structure to reduce the time complexity of problem from quadratic to liner, of course by trading off some space complexity. This also shows that how by using a suitable data structure you can come up with better algorithm to solve a problem. If you are preparing for programming job interviews, then I also suggest you to take a look at Cracking the Coding Interview book, which contains 150 programming questions and solutions, good enough to do well on any programming job interviews e.g. Java, C++, Python or Ruby.
Read more »

Friday, October 30, 2015

How to Sort List into Ascending and Descending Order in Java

ArrayList, Set Sorting in Ascending – Descending Order Java
Sorting List, Set and ArrayList in Java on ascending and descending order is very easy, You just need to know correct API method to do that. Collections.sort()  method will sort the collection passed to it,  doesn't return anything just sort the collection itself.  Sort() method of Collections class in Java is overloaded where another version takes a Comparator and sort all the elements of Collection on order defined by Comparator.If we  don't pass any Comparator than object will be sorted based upon there natural orderlike String will be sorted alphabetically or lexicographically. Integer will be sorted numerically etc. Default sorting order for an object is ascending order like Integer will be sorted  from low to high while descending order is just opposite. Collections.reverseOrder() returns a Comparator which will be used for sorting Object in descending order.
Read more »

Top 10 Tricky Java interview questions and Answers

What is a tricky question? Well, tricky Java interview questions are those questions which have some surprise element on it. If you try to answer a tricky question with common sense, you will most likely fail because they require some specific knowledge. Most of the tricky Java questions comes from confusing concepts like function overloading and overriding,  Multi-threading which is really tricky to master, character encoding, checked vs unchecked exceptions and subtle Java programming details like Integer overflow. Most important thing to answer a tricky Java question is attitude and analytical thinking, which helps even if you don't know the answer. Anyway in this Java article we will see 10 Java questions which is real tricky and requires more than average knowledge of Java programming language to answer them correctly. As per my experience there is always one or two tricky or tough Java interview question on any core Java or J2EE interviews, so it's good to prepare tricky questions from Java in advance.
Read more »

Wednesday, October 28, 2015

Appium Tutorials

This appium automation tutorials will take you from beginning level to advanced level in android software app automation testing. Appium software testing tool is freeware mobile automation testing tool using which you can automate native, hybrid and mobile web software apps of android and IOS. If you wants to make career in mobile automation software testing then appium is best tools for you. Now a days, many software companies has started using appium as a mobile automation testing tool so it is very important for mobile test engineers to learn appium for better future and growth.

As per my view, Nearest 40 to 50% websites will be converted in mobile app in next 5 to 10 years as usage of mobile apps is increasing day by day. At present, It is great opportunity for each mobile tester to learn appium very quickly so that he/she can work on appium in upcoming days.

I have prepared bunch of appium tutorials for those beginners who wants to build their career in mobile automation testing industry. Go though bellow given appium tutorials steps by step to learn appium automation very quickly.

How to Print Pyramid Pattern in Java? Program Example

Pattern based exercises are a good way to learn nested loops in Java. There are many pattern based exercises and one of them is printing Pyramid structure as shown below:


* * 
* * * 
* * * * 
* * * * * 

You need to write a Java program to print above pyramid pattern. How many levels the pyramid triangle would have will be decided by the user input. You can print this kind of pattern by using print() and println() method from System.out object. System.out.print() just prints the String or character you passed to it, without adding a new line, useful to print stars in the same line. While, System.out.println() print characters followed by a newline character, which is useful to move to next line. You can also use Scanner class to get input from the user and draw pyramid up to that level only. For example in above diagram, the pyramid has 5 levels.
Read more »

Tuesday, October 27, 2015

Run Appium Android Automation Test In Emulator

Earlier we learnt how to run android automation test in real android device using appium as described in THIS POST. So I am suggesting you to read It before running appium test in AVD. Also you can run appium test on android emulators (Android virtual device). We will learn how to run first appium test in android emulator in this appium tutorial post. We will use android emulator's build in installed calculator app to create and run appium automation test. Let's start it.

PREREQUISITES :
  1. All previous 16 steps of appium tutorial given on this LINK and this LINK should be completed without any error.
  2. Android emulator should be created.
  3. TestNG should be installed in eclipse. View THIS POST.
1. Start Appium Node Server
Start appium node server as described in THIS POST.

2. Start Android Virtual Device (Emulator)
Once appium starts properly, You need to launch android virtual device as described in THIS POST.

3. Get Emulator Platform Version
Also you need to provide android emulator platform version. You can get it as described bellow.
  • Unlock Android emulator screen.
  • Go to Settings. You will find About Phone under settings.
  • Go to About Phone.

  • It will show you Android version as shown in bellow image. For me it is 5.1


Note down android version for your emulator.

4. Verify calculator App Is Available In Emulator 
We are going to run appium test for calculator application so it should be there in emulator. Generally calculator app will be already installed in emulator. To check if it is installed or not,
  • Unlock emulator.
  • Verify if there is any application with name Calculator as shown in bellow image. You can download Android Calculator App from THIS PAGE if it is not available with you.

5. Get app Activity and Package Name
We need launcher activity and package name of calculator app. You can use any of the method from THIS PAGE or THIS PAGE to get activity and package name of calculator app.

Activity and package name of calculator app for me is as bellow.
Package name : com.android.calculator2
Activity name : com.android.calculator2.Calculator

6. Create Appium Test Script In Eclipse
Now we are ready to create and run our first appium test on android emulator for calculator application. I have prepared appium test script as bellow. I have used RemoteWebDriver of selenium webdriver to launch app with required capabilities.

Create new class file under Android package in eclipse with name SimpleEmulatorCalcTest and paste bellow given test script in it.

SimpleEmulatorCalcTest.java
package Android;

import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;

public class SimpleEmulatorCalcTest {

WebDriver driver;

@Test
public void setUp() throws Exception {

// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set android deviceName desired capability. Set it Android Emulator.
capabilities.setCapability("deviceName", "Android Emulator");

// Set browserName desired capability. It's Android in our case here.
capabilities.setCapability("browserName", "Android");

// Set android platformVersion desired capability. Set your emulator's android version.
capabilities.setCapability("platformVersion", "5.1");

// Set android platformName desired capability. It's Android in our case here.
capabilities.setCapability("platformName", "Android");

// Set android appPackage desired capability. It is com.android.calculator2 for calculator application.
// Set your application's appPackage if you are using any other app.

capabilities.setCapability("appPackage", "com.android.calculator2");

// Set android appActivity desired capability. It is com.android.calculator2.Calculator for calculator application.
// Set your application's appPackage if you are using any other app.

capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

// Created object of RemoteWebDriver will all set capabilities.
// Set appium server address and port number in URL string.
// It will launch calculator app in emulator.

driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

// Click on CLR button.
driver.findElement(By.name("del")).click();

//OR you can use bellow given syntax to click on CLR/DEL button.
//driver.findElements(By.className("android.view.View")).get(1).findElements(By.className("android.widget.Button")).get(0).click();


// Click on number 2 button.
driver.findElement(By.name("2")).click();

// Click on + button.
driver.findElement(By.name("+")).click();

// Click on number 5 button.
driver.findElement(By.name("5")).click();

// Click on = button.
driver.findElement(By.name("=")).click();

// Get result from result text box of calc app.
String result = driver.findElement(By.className("android.widget.EditText")).getText();
System.out.println("Number sum result is : " + result);
driver.quit();
}
}

Running First Appium Test In Emulator
Now we are ready to run appium test for calculator app in emulator. 

Note : Please make sure appium node server and emulator are launched and appium server is started by pressing start button.

Run test using testng and observe test execution in android emulator. It will 
  • Open calc app in emulator.
  • Tap on calc app's buttons in this sequence -> CLR, 2, +, 5 and =.
  • Get result from text area of calculator app.
  • Print result in eclipse console.
This way you can run appium test in android emulator.

Sunday, October 25, 2015

Appium Tutorial For Android

Native android app Automation appium Tutorial step by step. Appium configuration tutorials for android app In windows are described in PART 1. Appium is free software automation testing tools which enables us to automate android and IOS software application's testing process. We can automate Native, Hybrid and Mobile software web applications of android and IOS using appium software automation testing tool and that's what i am going to explain you using bellow given appium tutorials .

Here, I am trying my best to guide you on how to automate android software app testing process through this appium tutorials. Bellow given appium tutorials will help you to learn how to automate mobile software apps using appium. This appium tutorial will help you to learn appium if you are beginner and helps you to increase your knowledge if you know appium. Go through bellow given appium tutorials links step by step to learn how to automate android app using appium.

Note All bellow given appium tutorials articles are depends on PREVIOUS 15 TUTORIALS. So I recommend you to finish them first.

Apps To Use In Bellow Given Appium Test Examples

STEPS
16 : Appium : Find Launcher Activity And Package Name Of Android App
17 : Appium : Run Appium Android Automation Test In Emulator
18 : Appium : Android Test Using Different Element Locators
19 : Appium : Perform Drag And Drop In Android App
20 : Appium : How To Swipe Vertical And Horizontal In Android
21 : Appium : Swipe Element Using TouchAction Class In Android
22 : Appium Android Example On How To Scroll Down To Text
23 : Appium - How To Scroll Horizontal Tabs
24 : Pefrorm MultiTouch Action Using Appium In Android App
25 : Appium - How To Handle Alert Dialog Of Android App
26 : Appium - Android App Spinner Value Selection Example
27 : Appium - Set Date And Time In Android App
28 : Appium - Capture Screenshot Android App
29 : Appium - Capture Screenshot On Test Failure Or Pass
30 : Appium - Start Appium Server From Command Prompt


STAY TUNED.. MORE TUTORIALS ARE COMING SOON...

Which Java Collection to Use [Infographic]

One of the most common problem among Java Developers is to select which java collection to use in the  software development. According to oracle docs ,  we will cover the general purpose collection classes. I have already shared java collections interview questions and answers for beginners .


Read Also :   How LinkedHashSet Works Internally in Java 



Java Hungry Infographics
Solution : Which Java Collection to Use




How to Choose Appropriate Java Collection/Map

General Purpose Collection
Java Collection Cheatsheet

Share Java Infographics











Share this Image On Your Site




Please mention in the comments in case you have any question regarding which collection to use in java .

Saturday, October 24, 2015

Find Launcher Activity And Package Name Of Android App

Previously we learnt different three methods of finding any android application's launcher activity name and package name. Still if you are unable to find launcher activity and package name of any android application then you can use any of bellow given two methods. It will helps you to find any .apk file's package and launcher activity name.

Earlier we already learnt different 3 methods to find android app's package and launcher activity name in THIS POST

Bellow given 2 methods will show you how to get package and launcher activity name of APK Info app. You can download APKInfo App from THIS PAGE if it is not available with you.

PREREQUISITE : PREVIOUS 15 STEPS of appium tutorials should be completed without any error.

Method 4 : Using AndroidManifest.xml
Every .apk file contains AndroidManifest.xml file which contains android app's package and activity name. Bellow given steps will tell you how to open AndroidManifest.xml file and read package and activity name. 

Prerequisites :  1. .apk file for which you wants to get package and activity name. 2. WinRAR should be installed in your PC.
  • Right click on .apk file of APK Info app(or any other .apk file for which you wants to know package and activity name).
  • Select Open with -> WinRAR archiver option from right click context menu.

  • It will open .apk file in WinRAR window and you can see AndroidManifest.xml there as shown in bellow image.
  • Open AndroidManifest.xml file in notepad.
  • Now find keyword "p a c k a g e" In notepad. It will show you package name of your app as shown in bellow image. 
  • Package name for my APK Info app is : com.intelloware.apkinfo
  • Find keyword "a c t i v i t y" In notepad. It will show you activity name of your app as shown in bellow image. 
  • Activity name for my APK Info app is display: .MainActivity. Here you need to append package name ahead of activity name so full activity name is : com.intelloware.apkinfo.MainActivity
Method 5 : Using hierarchyviewer of SDK
Prerequisites :  
  1. Android SDK should be installed and configured as described HERE.
  2. Android emulator should be created as described HERE.
  3. .apk should be installed in emulator as described HERE. I will use APK Info app in this example so i have installed it in my emulator.
hierarchyviewer is a tool provided by android SDK. You will find it(hierarchyviewer.bat) inside tools folder of SDK. Here we will use it to get package and launcher activity name of APK Info app. Follow bellow given steps.

Note : hierarchyviewer is works well with emulators only for me. So try to use it will emulators only.
  • Launch android emulator and open APK Info app in emulator.
  • Open hierarchyviewer.bat file from tools folder of SDK.
  • It will show hierarchyviewer interface. It will show you package and activity name of you app as shown in bellow image.

This way, You can get Android App's Launcher Activity And Package Name.

Friday, October 23, 2015

Java ArrayList Tutorial - The MEGA List

I have written several ArrayList tutorials, touching different ArrayList concepts and many how to do examples with ArrayList. In this tutorial, I am giving a summary of each of them. Why? So that any Java beginner who wants to learn ArrayList in detail, can go through the relevant tutorial and learn. It's also on request of many of my readers, who asked in past to share all the relevant tutorials in one place. Why should you learn ArrayList? Because, it's the most important Collection class in Java. You will often find yourself using ArrayList and HashMap in tandem. It's your dynamic array which can resize itself as it grows. In another word, ArrayList is as much important as an array. When I started learning Java, my quest to ArrayList starts as a dynamic array, because there were many scenario where we don't know the size of the array in advance. We end up either allocating less space or more space, both are not ideal. Btw, you should also check out Head First Java 2nd Edition if you are newbie and Effective Java 2nd Edition, if you know Java but wants to become a Java expert.
Read more »

Tuesday, October 20, 2015

Install/Uninstall App In Emulator (AVD) Of Android From Command Prompt

I hope, All of you aready know how to install or uninstall app in real android device. But If you wants to work with android emulators for manual or automation testing, You must be aware about how to install or uninstall android applications in android emulators. Here I am present steps of how to install android app or uninstall any android app from android virtual device(Emulator).

PREREQUISITES :
  • All PREVIOUS 14 STEPS of appium tutorial should be executed without any error.
  • Android emulator should be created as described in THIS POST.
  • .apk file should be available in your PC which you wants to install in emulator. Here I am installing APK Info android application. So have it's source file com.intelloware.apkinfo.apk in my PC to install it in emulator. You can download it from Google Play Store or THIS PAGE.
Steps to Install APK in Android Emulator
  • Launch android emulator. Wait till it starts properly as shown bellow

  • Open platform-tools folder of SDK. For me It is located at E:\SDK\platform-tools. View THIS POST to know more about SDK folder.
  • Copy-paste com.intelloware.apkinfo.apk (Which you wants to install in emulator) file in platform-tools folder.
  • Navigate to platform-tools folder in command prompt. In platform-tools folder, Press keyboard's CTRL+Shift+Mouse Right Click. It will open right click context menu as shown in bellow image. Select Open command window here option from context menu.
  • It will open command prompt with navigation to platform-tools folder.
  • Run adb install com.intelloware.apkinfo.apk in command prompt. 
  • Note : Here, com.intelloware.apkinfo.apk Is APK file name. You need to replace it with your APK file name if you are installing any other app.
  • It will start installing app in emulator. It will show message Success after installation of app.
  • Now you can verify app is installed or not in your android emulator. Navigate to main menu in emulator screen. New installed app APK Info will display there on emulator screen as shown bellow.

Steps to Uninstall APK From Android Emulator
App uninstall process from emulator is similar to installation process from command prompt. There are two ways to uninstall app from android emulator.

1. Uninstall App Manually From Emulator Interface : 
It is same as you uninstall app from your android device.
  • Go to Settings of Emulator.
  • Tap on Apps.
  • Tap on App which you wants to uninstall.
  • Click on Uninstall button. It will uninstall app from emulator.

Verify your app will be uninstalled from emulator.

2. Uninstall App Using Command Prompt

To uninstall app using command prompt,
  • Open command prompt and navigate to platform-tools folder in it.
  • Run command adb uninstall com.intelloware.apkinfo in command prompt.
  • When app get uninstalled, It will show you message Success. That means app is uninstalled from your emulator. You can verify it in your emulator.

This way you can install and uninstall any app in your emulator.

How to solve FizzBuzz in Java?

FizzBuzz is one of the most frequently asked question on programming interviews and used to filter programmers who can't program. It looks extremely simple but its tricky for those programmer or coder who struggle to structure their code. Fizzbuzz problem statement is very simple, write a program which return "fizz" if number is multiplier of 3, return "buzz" if its multiplier of 5 and return "fizzbuzz" if number is divisible by both 3 and 5. If number is not divisible by either 3 or 5 then it should just return the number itself. You can see nothing is fancy when it comes to think about solution, but when you start coding, you will see problem with structuring your code, particularly if else blocks.
Read more »

Sunday, October 18, 2015

8 Difference between IdentityHashMap and HashMap with Example

HashMap is one of the most frequently used class in java collections framework. In this post we will learn about the difference between IdentityHashMap and HashMap with example. We will also look at the similarities between these two classes. I have already discussed the interview questions on collections .

Read Also :  How Remove method works Internally in HashMap with Example


Difference between IdentityHashMap and HashMap in Java

1. Equality used(Reference Equality instead of Object Equality) : IdentityHashMap uses reference equality to compare keys and values while HashMap uses object equality to compare keys and values .
for example :

Suppose we have two keys k1 and k2


In HashMap :
two keys are considered equal   if and only if (k1==null ? k2==null  : k1.equals(k2))

// object equality i.e using equals() method to compare objects


In IdentityHashMap :
two keys are considered equal  if and only if (k1 == k2)   

//reference equality  i.e  using == operator  to compare objects



2. Map's contract violation :  IdentityHashMap implements the Map interface,  it intentionally violates the Map general contract , which mandates the use of equals method when comparing objects.


HashMap also implements Map interface but it does not violate the Map general contract  as it uses equals method  to compare objects .

3. Hashcode method :   IdentityHashMap does not use hashCode() method instead it uses System.identityHashCode() to find bucket location.
HashMap uses hashCode() method to find bucket location. Find the detailed explanation  here
how hashmap works in java.

4. Immutable keys : IdentityHashMap does not require keys to be immutable as it does not relies on equals() and hashCode() method.
To safely store the object in HashMap keys must be immutable.

5. Performance : According to IdentityHashMap Oracle docs,
IdentityHashMap will yield better performance than HashMap(which uses chaining rather than linear probing Hashtable)  for many jre implementations and operation mixes

6. Implementation : Both IdentityHashMap and HashMap are  Hashtable based implementation of Map interface. IdentityHashMap is a simple linear probe hashtable  while HashMap uses chaining instead of linear probe in hashtable.

7. Initial capacity of default constructor : Initial capacity of HashMap is 16 by default .  Initial capacity of IdentityHashMap is 21 by default.

8. Added to jdk : IdentityHashMap is added to jdk in java version  1.4 . HashMap class is introduced to the java development kit in java version 1.2 .



Example of IdentityHashMap and HashMap 



import java.util.Map;
import java.util.HashMap;
import java.util.IdentityHashMap;
public class IdentityHashMapExample { public static void main(String[] args) { 
 
           
       // Created HashMap and IdentityHashMap objects

        Map hashmapObject = new HashMap();
        Map identityObject = new IdentityHashMap();
        
       
       // Putting  keys and values in HashMap and IdentityHashMap Object

        hashmapObject.put(new String("key") ,"Google"); 
        hashmapObject.put(new String("key") ,"Facebook"); 
       
        identityObject.put(new String("identityKey") ,"Google"); 
        identityObject.put(new String("identityKey") ,"Facebook"); 

        // Print HashMap and IdentityHashMap Size : After adding  keys
       
        System.out.println("HashMap after adding key :"+ hashmapObject);
        System.out.println("IdentityHashMap after adding key :"+ identityObject); 
                            
 }
}




Output :


HashMap after adding key :{key=Facebook}
IdentityHashMap after adding key :{identityKey=Facebook, identityKey=Google}

 

Similarities between IdentityHashMap and HashMap

1. Permit null key and null values : Both HashMap and IdentityHashMap class permit null key and null values.

2. Not synchronized : Both classes are not synchronized. Both classes must be synchronized externally.
For IdentityHashMap :
Map m  = Collections.synchronizedMap(new IdentityHashMap( ... ));
For HashMap :
Map m  = Collections.synchronizedMap(new HashMap( ... ));

3. Iterators returned by the iterator method : Both classes iterator method return the fail-fast iterator . Check out in detail about the difference between fail-fast iterator and fail-safe iterator .

4. Implementation : Both are Hashtable based implementation of Map interface.

When to prefer IdentityHashMap over HashMap

According to Oracle docs , IdentityHashMap  class is not a general purpose Map implementation , while WeakHashMap class implements the Map interface , it intentionally violates Map's general contract , which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.


Difference between IdentityHashMap and HashMap in Java with example
A typical use of this class is topology-preserving object graph transformations , such as serialization and deep copying . To perform such a transformation , a program must maintain a "node table" that keeps track of all the object references that have already been processed.The node table must not equate distinct objects even if they happen to be equal.

Another typical use of this class is to maintain proxy objects. For example , a debugging facility might wish to maintain a  proxy object for each object in the program being debugged.



Recap: Difference between IdentityHashMap and HashMap in Java


IdentityHashMapHashMap
Equality usedReference(==)Object(equals method)
Maps contract violationYesNo
HashCode method usedSystem.identityHashCode()Object class hashCode() method
Immutable keysNo requirementYes
PerformanceFastSlow in comparision
Implementationlinear-probechaining
Initial capacity of Default constructor 1621
Added to jdkjdk 1.4jdk 1.2


Please mention in the comments in case you have any questions regarding the difference between IdentityHashMap and HashMap in java .

Saturday, October 17, 2015

How To Create And Start An Android Virtual Device(Emulator) To Run Appium Test

In previous post, We executed first appium test successfully in android mobile device. Also you can use Android Virtual Device(Emulators) to run automation tests on nadroid app using appium. So let's learnt how to create android emulator in windows system to rum appium test on it. This post will describe you how to create (AVD) In Windows.

What Is An Android Virtual Device(Emulators)?
In general term, an emulator is software or hardware that enables one computer system (Example : Windows) to behave like another computer system(Example : Android). It provides virtual environment of another system.

So here we can create emulator of android device in windows system to run appium test on it.

Creating Emulators(AVD) In Windows
If you remember, Earlier we have installed Android SDK in windows. Android SDK allows you to create emulators in windows. So let's try to create android emulator in windows.

PREREQUISITES :
  1. Java should be installed as described in THIS POST.
  2. Android SDK, it's all required packages and Intel Hardware Accelerated Execution Manager must be installed as described in THIS POST.
  3. Android environment variables should be set. View THIS POST.
Launch AVD Manager
SDK provides interface called AVD Manager to create android virtual devices. So first of all you need to start AVD Manager.
  • Open SDK folder. For me it is located at E:\SDK as described in SDK installation steps.
  • There will be "AVD Manager.exe" file.
  • Double click on "AVD Manager.exe". it will launch AVD manager dialog as shown bellow.

Create Android Virtual Device
Using AVD Manager interface, We can create emulator as described in bellow steps.
  • Click on Create button. It will open Create new Android Virtual Device dialog as shown bellow.

Note : In Target drop down, You need to select that API level for which you have installed system images during SDK installation. I have installed Android 5.1.1 - API Level 22 so selected it here. Also do not put space in AVD Name textbox.
  • Fill values in all fields as shown in above image and click on OK button.
  • It will create AVD and show message as shown bellow.
  • New created device will be listed on AVD manager as shown bellow.

Same way you can create any other size device emulators too as per your system images installation for different Android API levels.

Start AVD Emulator
Note : Please make sure you have minimum 2 GB RAM in your system. 4 GB RAM is recommended. AVD Emulator uses large amount of memory. So please close all non-required software applications before starting it.

To start Emulator
  • Select New create AVD 2.7_Inch_QVGA from list.
  • Click on Start Button as bellow.
  • It will show Launch Options dialog. Click on Launch button.
  • It will launch android emulator as shown in bellow image. Full launch can take time from 5 to 10 minutes based on your system configuration.
  • Wait for a while. Emulator screen will looks like bellow after few minutes. Be patient.

So now android emulator is launched.

Unlocking Emulator Screen 
Same as android mobile device, You can unlock emulator screen by dragging lock icon up by mouse as shown in bellow image.


After unlocking, Emulator screen will looks like bellow.


This way you can create and launch emulator for android device in windows system. We will use this emulator to automate different android apps in my upcoming posts.

Verify Emulator Detected
You can detect emulator from command prompt using command adb devices as shown in bellow image.


So my emulator is running fine and detected by my system.