Friday, 16 June 2017

How to get Resolution of android device during runtime

How to get Resolution of android device during runtime


Getting Resolution of the android screen is one of the important aspect when application is to be made for different resolution devices.
So, in order to get the resolution of the device there is predefined library(Display Metrics) in android sdk. You just need to call the method provided by it. The methods are mentioned below.

 DisplayMetrics DM = new DisplayMetrics();  
 getWindowManager().getDefaultDisplay().getMetrics(DM);  

This DM object have the information about no. of pixels in height and width and density of the screen. To get these information Call following method:-

For no. of pixels in length

 DM.heightPixels;  

For no. of pixels in width

 DM.widthPixels;  

For Density of Screen

 DM.densityDpi;  

This information is used frequently in code so it is better to make a wrapper class of this and add some basic functions in it. The custom Wrapper class is defined below.

Wrapper Class for DM object


Firstly you have to pass the DM object to this class's constructor.

 DisplayMetrics DM = new DisplayMetrics();  
 getWindowManager().getDefaultDisplay().getMetrics(DM);  
 ScreenResolution SR = new ScreenResolution(DM);  

Now create the custom class named as ScreenResolution:-

import android.util.DisplayMetrics;
public class ScreenResolution { public static DisplayMetrics dm; public ScreenResolution(DisplayMetrics dm){ this.dm=dm; } public static int getHeight(){ return dm.heightPixels; } public static int getWidth(){ return dm.widthPixels; } public static int getDensity(){ return dm.densityDpi; } public static int percent_of_width(int param){ return ((param*(dm.widthPixels))/100); } public static int percent_of_height(int param){ return ((param*(dm.heightPixels))/100); } }

This class should be placed in custom Package. This class is beneficial in storing and getting the information about the screen's resolution.

ENJOY  DEVELOPING!!

Wednesday, 14 June 2017

ConcurrentHashMap in Java

ConcurrentHashMap

ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java 1.5 as part of Java concurrency package.  Prior to Java 1.5 if you need a Map implementation, which can be safely used in a concurrent and multi-threaded Java program, then you only have Hashtable or synchronized Map because HashMap is not thread-safe.
With ConcurrentHashMap, not only it can be safely used in concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. ConcurrentHashMap allows concurred read operations and same time, maintains integrity by synchronizing write operations.

How ConcurrentHashMap is implemented in Java

ConcurrentHashMap provided all functions supported by Hashtable with additional feature called "concurrency level", which allows ConcurrentHashMap to partition Map. ConcurrentHashMap allows multiple readers to read concurrently without any blocking. This is achieved by partitioning Map into different parts based on concurrency level and locking only a portion of Map during updates. Default concurrency level is 16. This means, 16 thread can operate on Map simultaneously, until they are operating on different part of Map. This makes ConcurrentHashMap high performance despite keeping thread-safety intact. Though, it comes with warning. Since update operations like put(), remove(), putAll() or clear() is not synchronized, concurrent retrieval may not reflect most recent change on Map.
Another important point to remember is iteration over CHM, Iterator returned by keySet of ConcurrentHashMap are weekly consistent and they only reflect state of ConcurrentHashMap and certain point and may not reflect any recent change. Iterator of ConcurrentHashMap's keySet area also fail-safe and doesn’t throw ConcurrentModificationExceptoin.

ConcurrentHashMap putifAbsent example in Java

Many times we need to insert entry into Map, if it’s not present already, and we wrote following kind of code:

synchronized(map){  
  if (map.get(key) == null){  
    return map.put(key, value);  
  } else{  
    return map.get(key);  
  }  
 }  

Though this code will work fine in HashMap and Hashtable, This won't work in ConcurrentHashMap; because, during put operation whole map is not locked, and while one thread is putting value, other thread's get() call can still return null which result in one thread overriding value inserted by other thread. Of course, you can wrap whole code in synchronized block and make it thread-safe but that will only make your code single threaded. ConcurrentHashMap provides putIfAbsent(key, value) which does same thing but atomically and thus eliminates above race condition.
Eg:
public class ConcurrentHashMapTest implements Runnable {  
     private String name;  
     private static Map<String,String> conpage=new ConcurrentHashMap<String,String>();  
     ConcurrentHashMapTest(String name){  
        conpage.put("1","A");  
        conpage.put("2","B");  
        conpage.put("3","C");  
        this.name=name;  
     }  
     public void run() {  
        try{  
            Iterator<String> it = conpage.keySet().iterator();  
            while(it.hasNext()){  
               String key=it.next();  
               conpage.put("A"+key, "A"+key);  
            }  
            System.out.println(name +" completed.");  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
     }  
     public static void main(String[] args) {  
        ExecutorService executor= Executors.newCachedThreadPool();  
        executor.execute(new ConcurrentHashMapTest("Thread one"));  
        Iterator<String> itt = conpage.keySet().iterator();  
        while(itt.hasNext()){  
            String key=itt.next();  
            System.out.println(conpage.get(key));  
        }  
        executor.execute(new ConcurrentHashMapTest("Thread two"));  
        Iterator<String> it = conpage.keySet().iterator();  
        while(it.hasNext()){  
            String key=it.next();  
            System.out.println(conpage.get(key));  
        }  
        executor.shutdownNow();  
     }     
 }  

Output-  
 A  
 C  
 B  
 Thread one completed.  
 A  
 A2  
 A1  
 A3  
 C  
 B  
 Thread two completed.  

When to use ConcurrentHashMap in Java

  • ConcurrentHashMap is best suited when you have multiple readers and few writers. If writers outnumber reader, or writer is equal to reader, than performance of ConcurrentHashMap effectively reduces to synchronized map or Hashtable.
  • ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads.
  • For those who have seen the green-box load jobs written in SpringBatch, many of the one-time populated Maps in beforeJob, whch are always read alone, are all ConcurrentHashMap ‘s.

Enjoy Learning :)

Eclipse and its Features

We work on Eclipse every day, but still we are not aware of all the powerful features of Eclipse. It provides a lot of shortcuts and other features which can help us in coding, debugging and other tasks, eventually delivering the bug free code in a lot lesser time.
Some of them are mentioned below and yet there are a lot more J 
Content Assist, Quick Fix and Class Navigation
Content assist
The content assistant allows you to get input help in an editor. It can be invoked by pressing CTRLSpace For example type syso in the editor of a Java source file and then press CTRLSpace. This will replace syso with System.out.println(""). If you have a reference to an object, for example the object person of the type Person and need to see it's methods, type person. and press CTRL+Space.
Quick Fix
Whenever Eclipse detects a problem, it will underline the problematic text in the editor. Select the underlined text and press CTRL1 to see proposals how to solve this problem. For example type myBoolean = true; If myBoolean is not yet defined, Eclipse will highlight it as an error. Select the variable and press CTRL1, Eclipse will suggest creating a field or local variable.
Quick Fix is extremely powerful. It allows you to create new local variables and fields as well as new methods and new classes. I can put try-catch statements around your exceptions. It can assign a statement to a variable and much more.
Opening a class
You can navigate between the classes in your project via the "Package Explorer" View. In addition you can open any class via positioning the cursor on the class in an editor and pressing F3. Alternatively, you can press CTRLShiftT. This will show a dialog in which you can enter the class name to open it.
Eclipse Shortcuts
Eclipse provides a lot of shortcuts to work efficiently with the IDE.
Table 1.  Navigation

Shortcut
Description
Ctrl + 2 + L
Assign statement to new local variable
Ctrl + 2 + F
Assign statement to new field
Table 4. Coding

Shortcut
Description
ALT + SHIFT + R
Rename
CTRL+2, R
Rename locally (in file), faster then ALT + SHIFT + R
ALT + SHIFT + T
Opens the quick refactoring menu
Table 6.  Handling the editor

Command
Description
F5
Goes to the next step in your program. If the next step is a method / function this command will jump into the associated code.
F6
F6 will step over the call, i.e. it will call a method / function without entering the associated code.
F7
F7 will go to the caller of the method/ function. This will leave the current code and go to the calling code.
F8
Use F8 to go to the next breakpoint. If no further breakpoint is encountered the program will run normally.

More Debugging Tips!!
  • If you want to temporary de-activate all your breakpoints you can press the button "Skip all breakpoints". This button is visible, if you select the "Breakpoints" tab. If you press this button again, your breakpoints will be reactivated.
    • After setting a breakpoint you can select the properties of the breakpoint, via right-click > Breakpoint Properties. You can define a condition that restricts when the breakpoint will become active.
    • watchpoint is a breakpoint set on a field. The debugger will stop whenever that field is read or changed.
    • You can set a watchpoint by double-clicking on the left margin, next to the field declaration. In the properties of a watchpoint you can define if the execution should stop during read access (Field Access) and during write access (Field Modification).
    • You can also set breakpoints which are triggered when exceptioins are thrown. To define an exception breakpoint click on the "Add Java Exception Breakpoint" icon in the "Breakpoints" View toolbar.
    • A method breakpoint is defined by double-clicking in the left margin of the editor next to the method header. You can define if you want to stop the program before entering or after leaving the method.
    • A Class Load Breakpoint will stop when the class is loaded. To set a class load breakpoint, right-click on a class in the Outline View and choose "Toggle Class Load Breakpoint".
For every breakpoint you can define a hit count in it's properties. The application is stopped once the breakpoint is reached the number of times defined in the hit count.

Templates
If you have to frequently type the same code / part of the document, you can create templates which can be activated via autocomplete (Ctrl + Space).
For example, assume that you are frequently creating public void name(){} methods. You could define a template which creates the method body for you.
To create a template for this, select the menu Window > Preferences > Java > Editor > Templates.



Press New. Create the template shown in the following screenshot.


cursor indicates that the cursor should be placed at this position after applying the template.
In this example the name "npm" is your keyword. Now every time you type "npm" in the Java editor and press CTRL+Space the system will allow you to replace your keyword with your template. 
 Automatic placement of semicolon
Eclipse can make typing more efficient by placing semicolons at the correct position in your source code.
In the Preference setting select Java > Editor > Typing. In the section "Automatically insert at correct position”, enable the "Semicolons" checkbox. You can now type a semicolon in the middle of your code and Eclipse will position it at the end of the current statement.



Enjoy Learning :)