Skip to main content


Showing posts from 2017

Using TypeFace in Android

In android, when you using the custom fonts. You need to create the assets folder in the main, then paste your .ttf or .otf format fonts.

Here some methods will be very useful for you,

Set the typeface

    public Typeface setTypeFace(Context context) {
        Typeface typeface = Typeface.createFromAsset(context.getAssets(),
        return typeface;


Like you can set the EditText, Spinner and other widgets.

Using the spannable text view in android,

Spannable span = new SpannableString("Hello Android, Have a great day!");        
span.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    span.setSpan(new ForegroundColorSpan(Color.RED), 13, 25, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Using Custom TypeFace:
import android.content.res.Resources;
import android…

Date conversion into different data type

Most of times, we've busy with converting one data type into another data type and validations. That's a developer's life. Actually it's makes life interesting.

This is old, anyhow I post here. Just try it.

Convert current time to long Timestamp.
    public static long getCurrentTimeStamp(Context context) {
        long timestamp = 0;
        try {
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.getDefault());
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMMM-yyyy hh:mm ss a");
            timestamp = c.getTime().getTime();
        } catch (Exception e) {
            //handle exception
        return timestamp;

Convert Date into String

    public static String convertDate(Date date) {
        String format = "dd-MMM-yyyy hh:mm a";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String stringDate = "";
        try {
            stringDate = sdf.format(date)…

Convert the Model class or List into JSON string.

Sometimes making the json structure is so hard, but this way could be very easier to do any kind of object model into json structure.

Add the following dependency in app.gradle.
compile ''

public class User {
    String userId;
    String userName;
    String userAge;
    String userAddress;
    String userCity;

    public User() {

    public User(String userId, String userName, String userAge, String userAddress, String userCity) {
        this.userId = userId;
        this.userName = userName;
        this.userAge = userAge;
        this.userAddress = userAddress;
        this.userCity = userCity;

    public String getUserId() {
        return userId;

    public void setUserId(String userId) {
        this.userId = userId;

    public String getUserName() {
        return userName;

    public void setUserName(String userName) {
        this.userName = userName;

    public String getUserAge() {
        return userAge;


Detecting shut down and reboot in android

Hi, Have a great day frnds..

Now we going to look up the detecting shut down and reboot events in android.

Here is the code:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ShutDownReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) {
            Log.i("event", "shutdown");
        } else if (intent.getAction().equals(Intent.ACTION_REBOOT)) {
            Log.i("event", "reboot");

Then apply in your activity,

shutDownReceiver = new ShutDownReceiver();

    protected void onPause() {

    protected void onResume() {
registerReceiver(shutDownReceiver, fil…

Detecting Screen on and Screen Off via services

Hi buddies, have a happy Sunday.

Today I'll explore about detecting screen on and screen off in android devices.

I got your mind, can use also by Broad cast Receivers. Yes, you can.

But how do you know, if app goes offline and screen off.

First write the Broad cast receiver class for receiving results.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ScreenReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            screenOff = true;
            Log.i("screenLog", "screen off");

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            screenOff = false;
            Log.i("screenLog", "screen on");

Then write the service class:


import a…

Print the large string values in android log cat.


Have a happy Monday.

In Android, sometimes we need to print the large numbers of strings value in log. But log can't accept whole value of the string.

In this case, we need to split the logs. It's very simple android code, I attached below this blog.

public static void logLargeString(String TAG, String msg) {         if (str.length() > 3000) {             Log.i(TAG, msg.substring(0, 3000));             logLargeString(TAG, msg.substring(3000));         } else {             Log.i(TAG, msg);         } }
Just use it and enjoy...

Backward and Forward Asterisks

Hi, Have a happy Sunday. Today I'm going to explain, how to deal with asterisks problems.

Just before the day, I've been attend the interview.

To print out Asterisk (*) in system console in specific order.

This is backward asterisks, I'm failed to do that, because of less time, no test cases and unfortunate system freezes. Yeah, this is not accept by recruiters. It's very simple problem, I know.

Anyway 15 minutes passes by. No clues.

I'm going to give the answer by two ways here now.
1. Backward Asterisks
2. Forward Asterisks


public class Asterisks{
     * @param args the command line arguments
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner scan = new Scanner(;
        System.out.println("Enter the number of rows : ");
        int n = scan.nextInt();
        System.out.println("Backward Asterisks");
        for (int i = n; i >=0; i--) {

Vending Machine Task - Java

Hi, Happy Weekends. Most boring thing is every time you've been asked same questions or you've been requested to do same tasks in different ways. I faced a lot.

In IT field, It's happens for everyone at least one time. Don't be sad, It's a good practice and helpful. We can also prove our self to do same works in different ways, It's a kind of practice. It's a kind of strategy.

In earlier times, Most of times in interview, I getting the calculator tasks in Android. Yeah, I do successfully in each time.

Here I come to explain the Vending Machine Task in Java. I've asked for this task for three times in a row now, each time differently.

What is Vending Machine?
A vending machine is a machine that dispenses items such as snacks, beverages, alcohol, cigarettes, lottery tickets to customers automatically, after the customer inserts currency or credit into the machine.

How it's works?
Vending machine is having a different product items with different deno…

Image Gallery Using Flickr

Hi friends, have a great day. Now I just explain how to use Flickr.

Flickr is one of largest media library in the world, you can store your photos & videos in this application.

Both web version and mobile version are available.

API details:

You can access the flickr API by create the app, get the api_key and secret key.

You can able to show the public or your own photo catalogues.

Public feeds are available in

I create one simple application to access the public photos using Flickr API.

You can download or clone in Github

Algorithm - Heap Sort

Heap Sort
Heapsort is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region.

It's an In-Place algorithm, but It's not a stable sort.


public class HeapSort {
    private static int num;
    public static void sort(int array[]) {
        for (int i = num; i > 0; i--) {
            swap(array, 0, i);
            num = num - 1;
            maxHeap(array, 0);
    public static void doSort(int arr[]) {
        num = arr.length - 1;
        for (int i = num / 2; i >= 0; i--) {
            maxHeap(arr, i);
    public static void maxHeap(int array[], int i) {
        int left = 2 * i;
        int right = 2 * i + 1;
        int max = i;
        if (left <= num && array[left] > array[i]) {

Algorithm - Merge Sort

Merge Sort
Merge sort is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output.

public class MergeSort {

    static int[] tempArr;

    public static void main(String a[]) {

        int[] inputArr = {11, 8, 34, 5, -4, 19, 0, 25, 97, 83, 8};
        for (int i : inputArr) {
            System.out.print(" ");

    static void sort(int array[]) {
        tempArr = new int[array.length];
        doMergeSort(array, 0, array.length - 1);

    static void doMergeSort(int[] array, int lowerIndex, int higherIndex) {

        if (lowerIndex < higherIndex) {
            int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
            // Below step sorts the left side of the array
            doMergeSort(array, lowerIndex, middle);
            // Below step sort…

Algorithm - Quick Sort

Quick Sort
Quicksort  is an efficient sorting algorithm, serving as a systematic method for placing the elements of an array in order. it is still a commonly used algorithm for sorting. When implemented well, it can be about two or three times faster than merge sort and heapsort.

public class QuickSort {

    static void sort(int[] inputArr) {

        if (inputArr == null || inputArr.length == 0) {
        doQuickSort(inputArr,0, inputArr.length - 1);

    static void doQuickSort(int[] array, int lowerIndex, int higherIndex) {

        int i = lowerIndex;
        int j = higherIndex;
        int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
        while (i <= j) {
            while (array[i] < pivot) {
            while (array[j] > pivot) {
            if (i <= j) {
                exchangeNumbers(array,i, j);

Algorithm - Insertion Sort

Insertion Sort
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It's not much efficient in large sets of data.


public class InsertionSort {

    public static void main(String arg[]) {
        int[] arr1 = {84, 43, 17, 65, 6, 19, 83, 4};
        int[] arr2 = doSort(arr1);
        for (int i = 0; i < arr2.length; i++) {
            if (i > 0) {
                System.out.print(", ");

    public static int[] doSort(int[] array) {

        int temp;
        for (int i = 1; i < array.length; i++) {
            for (int j = i; j > 0; j--) {
                if (array[j] < array[j - 1]) {
                    temp = array[j];
                    array[j] = array[j - 1];
                    array[j - 1] = temp;
        return array;

Result: 4, 6, 17, 19, 43, 65, 83, 84

Algorithm - Selection Sort

Selection Sort
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.

The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary by one element to the right.

Algorithm is not suitable for large data sets.


public class SelectionSort {

    public static int[] sortNumbers(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int index = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[index]) {
                    index = j;

            int smallerNumber = arr[index];
            arr[index] = arr[i…

Algorithm - Bubble sort

Now we are going to look up some algorithms.

Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order

Example in Java:

public class BubbleSort {

    public static void bubble_sort(int arr[]) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // swap temp and arr[i]
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;

    private static void swapNumbers(int i, int j, int[] array) {
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;

    private static void printNumbers(int[] input) {
        int n = input.length;
        for (int i = 0; i < n; ++i) {
            if (i != n) {
                System.out.print(input[i] + &quo…

Print the numbers in Triangle or Pyramid Shape.

Here is the task, want to print the numbers in triangle or pyramid shape.

Like this,

     2    2
   3   3    3
4   4    4    4


import java.util.Scanner;
public class PyramidShape {
     public static void main(String[] args)
        Scanner in = new Scanner(;
        System.out.println("Enter the Number of rows : ");
        int rows = in.nextInt();
        int count = 1;
        for (int i = rows; i > 0; i--){
            for (int j = 1; j <= i; j++){
                System.out.print(" ");
            for (int j = 1; j <= count; j++){
                System.out.print(count+" ");