Wednesday, 23 September 2015

Credit card validator using Luhn's algorithm

I'm writing an algorithm to read from a file a list of numbers, and for each, determine if it is valid. If it is, then display which card type it is.

public class CreditCardValidator {

    /**
     * @param args the command line arguments
     * @throws java.io.FileNotFoundException
     */
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner(new File(args[0])); // read from a file
        while (scan.hasNextLine()) {
            String str = scan.nextLine();
            if (validate(str)) {
                System.out.println(creditCardType(str));
            } else {
                System.out.println("Invalid");
            }
        }
    }

    private static boolean validate(String str) {
        String reverse = new StringBuilder().append(str).reverse().toString();
        int[] array = new int[str.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = Integer.parseInt("" + reverse.charAt(i));
        }
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            if (i % 2 == 1) {
                array[i] *= 2;
                if (array[i] > 9) {
                    array[i] -= 9;
                }
            }
            sum += array[i];
        }
        return sum % 10 == 0;
    }

    private static String creditCardType(String str) {
        int input1Char = Integer.parseInt(str.substring(0, 1));
        int input2Chars = Integer.parseInt(str.substring(0, 2));
        int input3Chars = Integer.parseInt(str.substring(0, 3));
        int input4Chars = Integer.parseInt(str.substring(0, 4));
        int input6Chars = Integer.parseInt(str.substring(0, 6));

        if (input2Chars == 34 || input2Chars == 37) {
            if (str.length() == 15) {
                return "American Express";
            }
        }

        if (input4Chars == 6011
                || (input6Chars >= 622126 && input6Chars <= 622925)
                || (input3Chars >= 644 && input3Chars <= 649)
                || input2Chars == 65) {
            if (str.length() == 16) {
                return "Discover";
            }
        }

        if (input2Chars >= 51 && input2Chars <= 55) {
            if (str.length() >= 16 && str.length() <= 19) {
                return "MasterCard";
            }
        }

        if (input1Char == 4) {
            if (str.length() >= 13 && str.length() <= 16) {
                return "Visa";
            }
        }
        return "Invalid Credit Card Type";
    }
}

Tuesday, 22 September 2015

Custom Alert Dialog box in Andorid

custom.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter user name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" >
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enter password"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />

    <TableRow
        android:id="@+id/tableRow"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ok" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="cancel" />
    </TableRow>

</LinearLayout>

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1custom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="130dp"
        android:text="Custom dialog" />

</RelativeLayout>

MainActivity.java:
package com.karthik.customdialog;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.button1custom);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog customDialog = new Dialog(MainActivity.this);
customDialog.setTitle("Custom Dialog");
customDialog.setContentView(R.layout.custom);
customDialog.show();
Button okButton = (Button)customDialog. findViewById(R.id.button1);
okButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "ok button is working", Toast.LENGTH_SHORT).show();
}
});
Button cancelButton =(Button)customDialog.findViewById(R.id.button2) ;
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
customDialog.dismiss();
}
});
}
});
}
}




AlertDialogbox in Android

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="107dp"
        android:text="Show Alert" />

</RelativeLayout>


ActivityMain.java

package com.karthik.alertdialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 
  Button b = (Button)findViewById(R.id.button1);
 
  b.setOnClickListener(new OnClickListener() {
  
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
   
    builder.setTitle("Exit");
   
    builder.setMessage("are you sure");
   
    builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
    
     @Override
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      finish();
     }
    });
   
    builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
    
     @Override
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
     
     }
    });
   
   
    AlertDialog alert = builder.create();
   
    alert.show();
   }
  });
 }

}



Forcing overflow menu


    Add the following code on your activity in
    "oncreate" method after "setcontentview"


try {
    ViewConfiguration config = ViewConfiguration.get(this);
    Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
    if(menuKeyField != null) {
        menuKeyField.setAccessible(true);
        menuKeyField.setBoolean(config, false);
    }
} catch (Exception ex) {
    // Ignore
}

Friday, 18 September 2015

Enable The Move To SDCard Button For Android App

In this tutorial we show you how to enable “Move to SD Card” button and allow your application to move to SD Card. Ever since Android 2.2 (API Level 8), you can allow your application to be installed on the SDCard. This is an optional feature that available in Android device that allows installed applications to move from device storage to SD Card and vice-versa.

How to copy app from internal memory to SD Card?

In Android, you can go to device Settings >> Applications >> Manage Applications >> and then click on your app to view the app details. You will find a ‘Move to SD Card’ button which is available for some apps and for some apps it will be disabled (not click-able) for other apps. By default it is disabled for your application.

How to enable the ‘Move to SD Card’ button in for your App in Android?

For allowing the system to install your application on the external storage, you have to include the android:installLocation attribute in the <manifest> element, with a value of either “preferExternal”, “auto” or “intenalOnly”
  1. preferExternal , this request that your application may installed on the external storage, but the system does not guarantee that your application will be installed on the external storage. If the external storage is full, the system will install it on the internal storage. The user can also move your application between the two locations.
  2. auto , this indicate that your application may be installed on the external storage, but you don’t have a preference of install location. The system will decide where to install your application based on several factors. The user can also move your application between the two locations.
  3. intenalOnly , always installs application in internal storage.

How to add an event to device calendar In android

In this post, we will learn how to add an event to your device calendar in android.
Android allows us to invoke activities from other application using intent. Here in this example, we will be using the appropriate intent to invoke the default calendar application, and pre-filled with event details. User must must confirm to add the event, or can change, edit any of the details associated with a particular events.
Use the following code snippet to invoke the default calendar event.
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType("vnd.android.cursor.item/event");
startActivity(intent);
The above snippet will invoke the calendar application with empty fields and allow user to enter the event details before adding. However, you can pre-fill the event details by passing the details in the form of intent extras. The Extras values describes the event details, such as event start time, event end time, event title, event description, etc.
The following two class are important to understand for adding the events.
  1. CalendarContract : Defines the data model of calendar and event related information. This data is stored in a number of tables, listed below.
  2. CalendarContract.Events: This table holds the event-specific information. Each row in this table has the information for a single event—for example, event title, location, start time, end time, and so on. The event can occur one-time or can recur multiple times. Attendees, reminders, and extended properties are stored in separate tables. They each have an EVENT_ID that references the _ID in the Events table.
The following code bundle can be used to pass the information to calendar intent.
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime);
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,endTime);
intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
intent.putExtra(Events.TITLE, "Neel Birthday");
intent.putExtra(Events.DESCRIPTION, "This is a sample description");
intent.putExtra(Events.EVENT_LOCATION, "My Guest House");
intent.putExtra(Events.RRULE, "FREQ=YEARLY");
Most of the statements except the RRULE are self explanatory. The RRULE defines the repeat frequency for the events and follows the standard iCalendar recurrence rule format (see RFC 5544 for details).
Output of the above code is as follows.

Friday, 4 September 2015

Android Studio Tips and Tricks (Shortcut keys for easy access)

This year end the Eclipse support for Android Development is going to end. So, here are Some tips and tricks useful for Android Studio...


Customizing Android Studio with Themes:

You can download themes from http://www.ideacolorthemes.org/themes/ and customize the intelliij themes...


Programming key commands

Command look-up (Autocomplete command name) 
  •  CTRL + SHIFT + A 

Project quick fix 
  • ALT + ENTER  

Reformat code
  • CTRL + ALT + L (Win)
  • OPTION + CMD + L (Mac)

Show docs for selected API 
  • CTRL + Q (Win)
  • F1 (Mac)

Show parameters for selected method 
  • CTRL + P

Generate method 
  • ALT + Insert (Win)
  • CMD + N (Mac)

Jump to source 
  • F4 (Win)
  • CMD + down-arrow (Mac)

Delete line 
  • CTRL + Y (Win)
  • CMD + Backspace (Mac)

Search by symbol name 
  • CTRL + ALT + SHIFT + N (Win)
  • OPTION + CMD + O (Mac)
Project and editor key commands

Build 
  • CTRL + F9 (Win)
  • CMD + F9 (Mac)

Build and run 

  • SHIFT + F10 (Win)
  • CTRL + R (Mac)

Toggle project visibility 

  • ALT + 1 (Win)
  • CMD + 1 (Mac)

Navigate open tabs 

  • ALT + left-arrow; ALT + right-arrow (Win)
  • CTRL + left-arrow; CTRL + right-arrow (Mac)

Open Class File Symbol
Open class

  • CTRL+N(win)
  • CMD+O(mac)

Open file

  • CTRL+SHIFT+n(win)
  • CMD+SHIFT+o (mac)

Open Symbol

  • CTRL+SHIFT+ALT+N
  • CMD+ALT+O

Recent Files Opened

  • CTRL+E(win)
  • CMD+E(mac)

Recently edited files

  • CTRL+SHIFT+E(win)
  • CMD+SHIFT+E(mac)

Previous Next/Previous Error

  • SHIFT-F2/F2(win)

Last edited Location

  • CTRL+SHIFT+backspace(win)
  • CMD+SHIFT+backspace(mac)

Go to Declaration
  • CTRL+B(win)
  • CMD+B(mac)
Go to Super
  • CTRL+U(win)
  • CMD+Y(mac)

Creating New Files in Project Folder....

You can quickly add new code and resource files by clicking the appropriate directory in the Project pane and pressingALT + INSERT on Windows and Linux or COMMAND + N on Mac. Based on the type of directory selected, Android Studio offers to create the appropriate file type.
For example, if you select a layout directory, press ALT + INSERT on Windows, and select Layout resource file, a dialog opens so you can name the file (you can exclude the .xml suffix) and choose a root view element. The editor then switches to the layout design editor so you can begin designing your layout.

Creating layouts

Android Studio offers an advanced layout editor that allows you to drag-and-drop widgets into your layout and preview your layout while editing the XML.
While editing in the Text view, you can preview the layout on devices by opening the Preview pane available on the right side of the window. Within the Preview pane, you can modify the preview by changing various options at the top of the pane, including the preview device, layout theme, platform version and more. To preview the layout on multiple devices simultaneously, select Preview All Screen Sizes from the device drop-down.

Display line numbers for the code:

One of the most commonly used feature in Eclipse is the display of line numbers which can also be enabled in Android studio. You can enable them by going to File>Settings> Editor> Appearance and check-marking Show line numbers option.