Thursday, 5 November 2015

Validate mobile number using regular expressions in android

Hi guys Here I am going to explain how to validate  Mobile number using Regular Expressions

MobileNo = mobileid.getstring();


if(Helper.isValidMobile(MobileNo)){
    Toast.makeText(activity, "Valid", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "Not Valid", Toast.LENGTH_SHORT).show();
}


public static boolean isValidMobile(String argEditText) {
    try {
        Pattern pattern = Pattern.compile("^[+]?[0-9]{10,13}$");
        Matcher matcher = pattern.matcher(argEditText);
        return matcher.matches();
    } catch (Exception e) {
        if (ConfVars.PRINTEXECEPTOION) {
            e.printStackTrace();
        }
        return false;
    }
}

Validate Email Id using regular expressions in android

Hi guys  Here I am going to explain how to validate  email id  using Regular Expressions

EmailID = emailid.getstring();


if(Helper.isValidEmail(EmailID)){
    Toast.makeText(activity, "Valid", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(activity, "Not Valid", Toast.LENGTH_SHORT).show();
}

public static boolean isValidEmail(String argEditText) {
    try {
        Pattern pattern = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
        Matcher matcher = pattern.matcher(argEditText);
        return matcher.matches();
    } catch (Exception e) {
        if (ConfVars.PRINTEXECEPTOION) {
            e.printStackTrace();
        }
        return false;
    }
}

Read incoming message automatically in android for verify OTP

Hi guys i am going to explain how to read the incoming message in android automatically to verify OTP without closing the app using the BrodcastReceiver

Step 1).IncomingSms.class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

public class IncomingSms extends BroadcastReceiver 
{
  @Override
public void onReceive(Context context, Intent intent) 
{

final Bundle bundle = intent.getExtras();
  try {
  if (bundle != null) 
{
   final Object[] pdusObj = (Object[]) bundle.get("pdus");
   for (int i = 0; i < pdusObj .length; i++) 
 {
    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[])                                                                                                    pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber ;
String message = currentMessage .getDisplayMessageBody();
    try
  {
   if (senderNum .equals("TA-DOCOMO")) 
   {
Otp Sms = new Otp();
Sms.recivedSms(message );
   }
}
catch(Exception e){}

}
  }

} catch (Exception e) 
{
                
 }
}

}

Step 2).Otp.class

   public class Otp extends Activity 
   {

      static EditText OtpNumber;
       protected void onCreate(Bundle savedInstanceState) 
         {
super.onCreate(savedInstanceState);
setContentView(R.layout.otp);
                OtpNumber= (EditText) findViewById(R.id.txtName);
        }
      public void recivedSms(String message) 
       {
try 
         {
OtpNumber.setText(message);
       } 
         catch (Exception e) 
             {         
                   }
      }

       }   

Step 3).Add the below permissions and receiver to your manifest file


    <uses-permission android:name="android.permission.RECEIVE_SMS" >
    </uses-permission>
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS" >
     </uses-permission>

    <receiver android:name=".IncomingSms">
        <intent-filter>
         <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
        </intent-filter>
    </receiver>

Wednesday, 4 November 2015

How to trigger the button in android without click the button in android

Very simply trigger the button without click the button in oncreate

Button bt1 = (Button)findViewbyId(R.id.btl);
bl.performClick();

bl.setOnClickListener(new OnClickListener() 
         {public void onClick 
         (View  v) { 
             Intent i = new Intent(getApplicationContext(), exampleActivity.class);
             startActivity(i);}
         });

Monday, 12 October 2015

creating a multi select dialog box in android

  1. Create a java Activity class where you want your dialog to appear. 
  2. Create a field     private ArrayList mSelectedItems; for storing your array list.
  3. Call launchAddItems() when you need to create the dialog.
     
  4. Add the following function to create the dialog protected void
  5.  launchAddItems() {
              mSelectedItems = new ArrayList();
              final String items[] = {"Android","Iphone","Nokia"};

              AlertDialog.Builder ab=new AlertDialog.Builder(this);
              ab.setTitle("Dialog Title")
              .setMultiChoiceItems(items, null,  new DialogInterface.OnMultiChoiceClickListener(){

                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    if (isChecked){
                          mSelectedItems.add(which);
                    }
                    else if(mSelectedItems.contains(which)){
                        mSelectedItems.remove(Integer.valueOf(which));
                    }
                }
                 
              }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int id) {
                      // User clicked OK, so save the mSelectedItems results somewhere
                      // or return them to the component that opened the dialog
                  }
              }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int id) {
                  }
              });

              ab.create();;
             
           
              ab.show();       
        }

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();
}
});
}
});
}
}