• Monday, August 6, 2018

    Playing video in Android with VideoView complete tutorial.

    Art Soft

    Android VideoView widget tutorial and reference with Example

    Android System provides VideoView widget in which we can play video file easily by providing video path or video URI.


    Steps:
    1. Add video view to activity layout (example: activity_main.xml)
    
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <VideoView
            android:id="@+id/videoView"
            android:layout_width="0dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_height="0dp" />
    
    </android.support.constraint.ConstraintLayout>
    
    
    2. Now initialize VideoView in Activity (example: MainActivity.java)

    
    package com.masoomyf.videoviewexample;
    
    import android.net.Uri;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.VideoView;
    
    public class MainActivity extends AppCompatActivity {
        //Video view object to hold video view.
        private VideoView mVideoView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //Setup the UI
            setupUI();
            //Load Video
            loadVideo();
    
        }
    
        private void loadVideo() {
            //Video is in /res/raw/sample.mp4 so we need uri.
            Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sample);
            //Set video URI in video view
            mVideoView.setVideoURI(uri);
            //start the video.
            mVideoView.start();
        }
    
        private void setupUI() {
            //Assigning video view
            mVideoView = findViewById(R.id.videoView);
        }
    
    
    }
    
    

    Optional Steps (To Add MediaController to VideoView)

    Android VideoView with MediaController

    1. Create field MediaController mediaController;
    2. Initialize it in setupUI():
    mediaController = new MediaController(this);
    mVideoView.setMediaController(mediaController);

    After performing following steps, MainActivity look like this:

    
    
    package com.masoomyf.videoviewexample;
    
    import android.net.Uri;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.MediaController;
    import android.widget.VideoView;
    
    public class MainActivity extends AppCompatActivity {
        //Video view object to hold video view.
        private VideoView mVideoView;
    
        //MediaController object to hold mediaController.
        private MediaController mediaController;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            //Setup the UI
            setupUI();
            //Load Video
            loadVideo();
    
        }
    
        private void loadVideo() {
            //Video is in /res/raw/sample.mp4 so we need uri.
            Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sample);
            //Set video URI in video view
            mVideoView.setVideoURI(uri);
            //start the video.
            mVideoView.start();
        }
    
        private void setupUI() {
            //Assigning video view
            mVideoView = findViewById(R.id.videoView);
            mediaController = new MediaController(this);
            mVideoView.setMediaController(mediaController);
    
        }
    
    
    }
    
    
    
    

    Thursday, July 5, 2018

    [JAVA] How to get credit card/debit card type(i.e. Visa, Master) from card number

    Steve Well
    Visa Card, Credit Card, Master Card

    Hello,
    If you want to get card type i.e. Visa, Master, Rupay etc. by card number, here is the code you can use.

    This code uses regex for filtering out card type. You can use this method for getting the card type from card number (without space separation).



    public String getCardType(String mCardNumber) {
            if (mCardNumber.startsWith("4")) {
                return "VISA";
            }else if (mCardNumber.matches("^508[5-9][0-9][0-9]|60698[5-9]|60699[0-9]|607[0-8][0-9][0-9]|6079[0-7][0-9]|60798[0-4]|(?!608000)608[0-4][0-9][0-9]|608500|6521[5-9][0-9]|652[2-9][0-9][0-9]|6530[0-9][0-9]|6531[0-4][0-9]")){
                return "RUPAY";
            } else if (mCardNumber.matches("^((6304)|(6706)|(6771)|(6709))[\\d]+")) {
                return "LASER";
            } else if (mCardNumber.matches("6(?:011|5[0-9]{2})[0-9]{12}[\\d]+")) {
                return "LASER";
            } else if (mCardNumber.matches("(5[06-8]|6\\d)\\d{14}(\\d{2,3})?[\\d]+") || mCardNumber.matches("(5[06-8]|6\\d)[\\d]+") || mCardNumber.matches("((504([435|645|774|775|809|993]))|(60([0206]|[3845]))|(622[018])\\d)[\\d]+")) {
                
                return "MAESTRO";
            } else if (mCardNumber.matches("^5[1-5][\\d]+")) {
                return "MASTER";
            } else if (mCardNumber.matches("^3[47][\\d]+")) {
                return "AMEX";
            } else if (mCardNumber.startsWith("36") || mCardNumber.matches("^30[0-5][\\d]+") || mCardNumber.matches("2(014|149)[\\d]+")) {
                return "DINR";
            } else if (mCardNumber.matches("^35(2[89]|[3-8][0-9])[\\d]+")) {
                return "JCB";
            }
            return "";
        }



    [PHP]How to get credit card/debit card type(i.e. Visa, Master) from card number

    [PHP]How to get credit card/debit card type(i.e. Visa, Master, Rupay) from card number

    Steve Well
    Visa Card, Credit Card, Master Card

    Hello,
    If you want to get card type i.e. Visa, Master, Rupay etc. by card number, here is the code you can use.

    This code uses regex for filtering out card type. You can use this function for getting the card type from card number (without space separation).



    <?php
    echo getCardType("512654265322155433");

    function getCardType($cardNumber){

            if($cardNumber[0] == 4){
                return "VISA";
            }
            else if(mb_ereg("^508[5-9][0-9][0-9]|60698[5-9]|60699[0-9]|607[0-8][0-9][0-9]|6079[0-7][0-9]|60798[0-4]|(?!608000)608[0-4][0-9][0-9]|608500|6521[5-9][0-9]|652[2-9][0-9][0-9]|6530[0-9][0-9]|6531[0-4][0-9]",$cardNumber)){
                return "RUPAY";

            } else if (mb_ereg_match("^((6304)|(6706)|(6771)|(6709))[\\d]+",$cardNumber)) {
                return "LASER";
            } else if (mb_ereg("6(?:011|5[0-9]{2})[0-9]{12}[\\d]+",$cardNumber)) {
                return "LASER";
            } else if (mb_ereg_match("(5[06-8]|6\\d)\\d{14}(\\d{2,3})?[\\d]+",$cardNumber) ||mb_ereg_match("(5[06-8]|6\\d)[\\d]+",$cardNumber) || mb_ereg_match("((504([435|645|774|775|809|993]))|(60([0206]|[3845]))|(622[018])\\d)[\\d]+",$cardNumber)) {
                if (strlen($cardNumber) >= 6) { // wel we have 6 digit bin
                    $substr = substr($cardNumber,0,6);
                    if (
                        strpos("504435",$substr)!==false ||
                        strpos("504645",$substr)!==false ||
                        strpos("504775",$substr)!==false ||
                        strpos("504809",$substr)!==false ||
                        strpos("504993",$substr)!==false ||
                        strpos("600206",$substr)!==false ||
                        strpos("603845",$substr)!==false ||
                        strpos("622018",$substr)!==false ||
                        strpos("504774",$substr)!==false
                    ) {
                        return "SMAE";
                    }
                }
                return "MAES";
            } else if (mb_ereg_match("^5[1-5][\\d]+",$cardNumber)) {
                return "MAST";
            } else if (mb_ereg_match("^3[47][\\d]+",$cardNumber)) {
                return "AMEX";
            } else if (($cardNumber[0]==3 && $cardNumber[1]==6) ||mb_ereg_match("^30[0-5][\\d]+",$cardNumber) ||mb_ereg_match("2(014|149)[\\d]+",$cardNumber)) {
                return "DINR";
            } else if (mb_ereg_match("^35(2[89]|[3-8][0-9])[\\d]+",$cardNumber)) {
                return "JCB";
            }
            return "";
        }



    [Java]How to get credit card/debit card type(i.e. Visa, Master) from card number

    Sunday, January 28, 2018

    Java - Very basic and simple bicycle Part's inventory database application.

    Syed Masoom Rizvi
    BicyclePart.java

    package com.masoomyf;
    /**
    * com.masoomyf created by masoomyf on 28-01-2018.
    */
    //Class for bicycle parts, its attributes.
    public class BicyclePart {
    //For storing part number.
    public long id;
    //For storing part name.
    public String name;
    //For storing list price.
    public double listPrice;
    //For storing sale price.
    public double salePrice;
    //For storing onSale whether true or false.
    public boolean onSale;
    //For storing quantity.
    public int quantity;
    //Constructor.
    public BicyclePart(long id, String name, double listPrice, double sellPrice, boolean onSale,int quantity) {
    //Initialize of new Object Bicycle part
    //with the given value.
    this.id = id;
    this.name = name;
    this.listPrice = listPrice;
    this.salePrice = sellPrice;
    this.onSale = onSale;
    this.quantity = quantity;
    }
    //It will take string line like: akjs,1234567890,12.2,52.3,false,10 and
    //convert it to bicycle object by splitting it with comma
    //We use static here to call it directly without creating BicyclePart object.
    //and will crete new Bicycle part and return it.
    public static BicyclePart getPartFromString(String string){
    //split function split the string and give its array.
    //string example: akjs,1234567890,12.2,52.3,false,10
    //ajks stores in 0 index, 1234567890 stores in 1 index and so on after splitting.
    String[] parts = string.split(",");
    //Creating new object with the split array and return it.
    //Long.parseLong or Interger.parseInt or any other use to convert string object
    //in the appropriate data type.
    return new BicyclePart(Long.parseLong(parts[1]), parts[0],
    Double.parseDouble(parts[2]),Double.parseDouble(parts[3]),
    Boolean.parseBoolean(parts[4]),Integer.parseInt(parts[5]));
    }
    public String toString(){
    //just return all the attribute, with comma between them,
    //to save it in database txt file.
    return name + "," + id + "," + listPrice + "," + salePrice + "," + onSale;
    }
    }

    Main.java

    package com.masoomyf;
    import java.io.*;
    import java.util.*;
    public class Main {
    //To store all bicycle parts.
    private static ArrayList<BicyclePart> bicycleParts;
    //flag if changes is made in database or not.
    //if yes save it.
    private static boolean databaseUpdated = false;
    //main database file.
    private static File wareHouseFile;
    public static void main(String[] args) {
    //initialize new ArrayList.
    //Array list is use instead of array because it is expandable as
    //well as it will collapse after deleting object.
    bicycleParts = new ArrayList<>();
    //Creating File object of database file.
    wareHouseFile = new File("wareHouseDb.txt");
    //for reading user input.
    Scanner inputReader = new Scanner(System.in);
    //Now check database file exists or not.
    //If there is no Bicycle parts in database, or user run it first time
    //Its return false, because there will be no database file.
    if(wareHouseFile.exists()){
    // file is exists, try to read it.
    try {
    //reading main file.
    //Creating file input stream to read file. and passing File object
    //of database txt file.
    FileInputStream inputStream = new FileInputStream(wareHouseFile);
    //Creating buffered reader for file input stream.
    //It's allow to read file line by line and many more options.
    //but we need only to read line by line.
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    //Creating String line, for storing each line of database file.
    String line;
    //loop until there is no new line available in database file.
    //If there is no new line its return null and while loop breaks.
    while ((line=reader.readLine())!=null){
    //check whether line is empty or not.
    //if line is empty get next line.
    if(line.isEmpty()){
    continue;
    }
    //If line is not empty perform the following.
    //get new line from file and add it to bicycle.
    //create new bicycle part and add it to arrayList.
    BicyclePart bicyclePart = BicyclePart.getPartFromString(line);
    bicycleParts.add(bicyclePart);
    }
    }catch (Exception ignore){
    //If we get any error during reading file.
    //output error message.
    System.out.println("Cant read ware house database.");
    }
    }
    //Now display these option, until user write quit.
    while (true){
    //It will useful when user chooses an option another that quit,
    //It allow user to read the previous message of console.
    System.out.println("Press any key to continue.....");
    //It will not continue until user press any button and enter.
    inputReader.nextLine();
    //User pressed enter, it means user read the previous information.
    //Now display menu again(or first time).
    System.out.println("Please select your option from the following menu:");
    System.out.println("Read: Read an inventory delivery file");
    System.out.println("Enter: Enter a part");
    System.out.println("Sell: Sell a part");
    System.out.println("Display: Display a part");
    System.out.println("SortName: Sort parts by part name");
    System.out.println("SortNumber: Sort parts by part number");
    System.out.println("Quit:");
    System.out.print("Enter your choice: ");
    //Now read the choice of user.
    String choice = inputReader.nextLine();
    //According to choice call the appropriate option.
    if(choice.equalsIgnoreCase("read")){
    readFile(inputReader);
    }
    else if(choice.equalsIgnoreCase("enter")){
    enterPart(inputReader);
    }
    else if(choice.equalsIgnoreCase("sell")){
    sellPart(inputReader);
    }
    else if(choice.equalsIgnoreCase("display")){
    displayPart(inputReader);
    }
    else if(choice.equalsIgnoreCase("sortName")){
    sortByName();
    }
    else if(choice.equalsIgnoreCase("sortNumber")){
    sortByNumber();
    }
    else if(choice.equalsIgnoreCase("quit")){
    //If user select quit.
    //save the database and break the loop.
    saveDatabase();
    break;
    }
    else {
    //If user writes another option other than provided menu.
    //Give this error.
    System.out.println("Invalid option chosen.");
    }
    }
    }
    //Reading file inventory.txt.
    //Passing scanner here, so we don't need to create again a new scanner.
    private static void readFile(Scanner inputReader) {
    //prompt user to enter file name i.e. inventory.txt.
    System.out.println("Enter file name to read from: ");
    //read the fileName.
    String fileName = inputReader.nextLine();
    //Pass the filename to new File object.
    //It will allow to check whether file is exists or not.
    File file = new File(fileName);
    //If file not exists display error message and return from this method.
    if(!file.exists()){
    System.out.println("Error: File not exists.");
    return;
    }
    //If file exists try the following.
    try {
    //Create a new scanner by passing file object of inventory.txt
    //You can choose buffered reader also.
    //Just learn new thing.
    Scanner fileReader = new Scanner(file);
    //Marking this line as nextLine.
    //For future use.
    nextLine:
    //check if there is new line by looping.
    while (fileReader.hasNextLine()){
    //New line present, read the new line and store it into line.
    String line = fileReader.nextLine();
    //Now create a new Bicycle part.
    BicyclePart temp = BicyclePart.getPartFromString(line);
    //Now check, if this part exists in bicycleArrayList(database)
    //by comparing the temp part number with every bicycle part's number
    //store in array list(database)
    for (BicyclePart bicyclePart:bicycleParts){
    //Check if bicycle part is present or not.
    if(temp.id==bicyclePart.id){
    //Yes present.
    //Update it with new details, available in temp.
    bicyclePart.listPrice = temp.listPrice;
    bicyclePart.salePrice = temp.salePrice;
    bicyclePart.onSale = temp.onSale;
    //Add the quantity.
    bicyclePart.quantity += temp.quantity;
    //Flag the databaseUpdated to true.
    //means save the database on exit, because it gets changed.
    databaseUpdated = true;
    //we use continue nextLine here because if we use only
    //continue, for loop get's continue, and we don't it.
    //so just skip the for loop and continue the while loop
    //without executing the below lines.
    //Below line is for new part's that are not available
    //in our database.
    continue nextLine;
    }
    }
    //If there is no part that matches the temp, that's mean
    //part is new and add it to database.
    bicycleParts.add(temp);
    //Flag the databaseUpdated to true.
    //means save the database on exit, because it gets changed.
    databaseUpdated=true;
    }
    }catch (Exception e){
    //If something happen wrong, output the error.
    System.out.println("Error: " + e.getMessage());
    }
    }
    private static void enterPart(Scanner inputReader) {
    //Prompt and read all parts info from user.
    System.out.print("Enter part name: ");
    String name = inputReader.nextLine();
    //Below extra inputReader.nextLine is used because, we read a datatype
    //other than string.
    //If we don't call extra nextLine method, after reading this if we read a
    //string, it will give us a new line.
    //Example: we have to read an integer.
    //we use inputReader.nextInteger().
    //After that user write 45 or any number and press enter.
    //45 passed to caller, and enter remains in scanner, and we try to read new
    //line in future, it will just pass the enter which is in scanner.
    //rather than wait for a new string user will enter.
    System.out.print("Enter part number: ");
    long id = inputReader.nextLong();
    inputReader.nextLine();
    System.out.print("Enter list price: ");
    double listPrice = inputReader.nextDouble();
    inputReader.nextLine();
    System.out.print("Enter sell price: ");
    double salePrice = inputReader.nextDouble();
    inputReader.nextLine();
    System.out.print("Part is on sale? [true/false]: ");
    boolean onSale = inputReader.nextBoolean();
    inputReader.nextLine();
    System.out.println("Enter quantity: ");
    int quantity = inputReader.nextInt();
    inputReader.nextLine();
    //Now first check if bicycle part enter by user is present
    //in database or not. If yes update it and stop the method execution.
    for (BicyclePart bicyclePart: bicycleParts){
    if(bicyclePart.id == id){
    bicyclePart.listPrice = listPrice;
    bicyclePart.salePrice = salePrice;
    bicyclePart.onSale = onSale;
    bicyclePart.quantity += quantity;
    System.out.println("Bicycle part updated.");
    databaseUpdated = true;
    return;
    }
    }
    //If not add the new part to database.
    BicyclePart bicyclePart = new BicyclePart(id,name,listPrice,salePrice,onSale,quantity);
    bicycleParts.add(bicyclePart);
    System.out.println("New bicycle part is added.");
    databaseUpdated = true;
    }
    //For selling part.
    private static void sellPart(Scanner inputReader) {
    System.out.println("Enter part number: ");
    //Get the partNumber.
    long partNumber = inputReader.nextLong();
    //Remove the extra enter comes with long.
    inputReader.nextLine();
    //Check part enter by user is present in database or not.
    for (BicyclePart part: bicycleParts){
    if(partNumber == part.id){
    //if yes call sellPart(BicyclePart),
    //this method is also sellPart but with different signature
    //i.e. sellPart(Scanner).
    sellPart(part);
    //and stop executing this method.
    return;
    }
    }
    //If part is present then this line never execute.
    //If not present, this line will execute.
    //And show error message.
    System.out.println("Error: Bicycle part not exists.");
    }
    private static void sellPart(BicyclePart part){
    //check quantity is not less than one.
    //if yes give the error and stop execution of this method.
    if(part.quantity < 1){
    System.out.println("Error: No quantity left.");
    return;
    }
    //If quantity is more than zero(means available)
    //Print the part name and its cost.
    System.out.println("Part Name: " + part.name);
    // here tertiary operator is used for taking decision in line.
    // (true|false ? if true : if false)
    System.out.println("Part Cost: " + (part.onSale?part.salePrice:part.listPrice));
    if(part.onSale){
    System.out.println("Part is on sale.");
    }
    //Display the current date.
    System.out.println("Sold Time: " + new Date().toString());
    //decrease the part quantity.
    part.quantity--;
    //change the flag to true.
    //if it changes by another method, no problem.
    databaseUpdated=true;
    }
    //For displaying part.
    private static void displayPart(Scanner inputReader) {
    System.out.print("Enter part name: ");
    //read part name.
    //here no extra inputReader.nextLine() is use because string is read.
    //it automatically read the string with new line and omit it.
    String partName = inputReader.nextLine();
    //loop through database bicycle array list and check whether part name
    //is available or not.
    for (BicyclePart part: bicycleParts){
    if(partName.equalsIgnoreCase(part.name)){
    //if available call displayPart(BicyclePart) method.
    displayPart(part);
    //return.
    return;
    }
    }
    //if no part is available display the error.
    System.out.println("Error: Bicycle part not exists.");
    }
    //simple displayPart method.
    private static void displayPart(BicyclePart part) {
    System.out.println("Part Name: " + part.name);
    System.out.println("Part Cost: " + (part.onSale?part.salePrice:part.listPrice));
    }
    //sortByName method.
    private static void sortByName() {
    //sort the arraylist with the help of new Comparator.
    //java has compare option for datatype pre-defined in java,
    //If we create a new datatype(i.e. class), we have to implement and override the compare
    //method.
    bicycleParts.sort(new Comparator<BicyclePart>() {
    @Override
    public int compare(BicyclePart o1, BicyclePart o2) {
    //Compare the Bicycle Name with another one.
    //Java has string compare method.
    //so we use here and return the compare value to Comparator.
    return o1.name.compareToIgnoreCase(o2.name);
    }
    });
    //Now simply print all parts avail in database.
    System.out.println("Sorted part names: ");
    for (BicyclePart bicyclePart: bicycleParts){
    System.out.println(bicyclePart.name);
    }
    }
    //same as above but, here only change is that arraylist is sort by it's part number
    private static void sortByNumber() {
    bicycleParts.sort(new Comparator<BicyclePart>() {
    @Override
    //Compare with part number.
    public int compare(BicyclePart o1, BicyclePart o2) {
    return Long.compare(o1.id,o2.id);
    }
    });
    //Print the sorted arrayList.
    System.out.println("Sorted part names: ");
    for (BicyclePart bicyclePart: bicycleParts){
    System.out.println(bicyclePart.name);
    }
    }
    private static void saveDatabase() {
    //Check databaseUpdated flag.
    //If it is false, means no method execute which change the current database.
    //Therefore no need to save it.
    //return back.
    if(!databaseUpdated)return;
    //if it is true. write it to file.
    //first write it to temp file.
    //then delete the old database file.
    //after that rename the temp file to database file.
    try {
    //Create file output stream to write the data.
    FileOutputStream outputStream = new FileOutputStream("temp.txt");
    //create buffered writer to write line by line.
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
    //loop through all part available in array list(database)
    for (BicyclePart bicyclePart:bicycleParts){
    //write the bicycle part to file follow with a new line.
    //bicycle.toString is defined in BicyclePart.java
    //which gives whole thing in string with comma seperator.
    writer.write(bicyclePart.toString() + "\n");
    }
    //close the writer.
    writer.close();
    //close output stream.
    outputStream.close();
    //check if the old database file actually exists or not.
    //if exists delete it.
    if(wareHouseFile.exists())
    wareHouseFile.delete();
    //create a file object with name temp.txt
    File file = new File("temp.txt");
    //rename it to database file.
    file.renameTo(wareHouseFile);
    }catch (Exception ignore){
    //rise error if anything happens wrong.
    ignore.printStackTrace();
    }
    }
    }