Sunday 6 March 2016

How to Create Custom Adapter for ListView in Android

Objective:

First, what is adapter? It's like a bridge that take data from source and make view to user.


ArrayAdapter is normally used to process only one dynamic data. But in real world , most of the cases we have to process more than one dynamic data. That's why we need custom adapter.

I'm going to explain things like a story. So advance sorry to geeks. :)

Our Project:

We will make a contact app where 
  • user store contact Name, Number & a default Image in a List-View temporary.
  • when user click any item in the list view, another activity will show that contact details.
  • where we set a call & message button to call or message that number.
Overview of our project:

 

 

I  will give a link to source code of the project.

Let's Get Started:

What do we need?
I assume that you have done the XML part of the project (Contacts & Contact Details) as I'm going to focus on 
  • Contact Model Class
  • Contact Adapter
  • Contact Details
if you have problem about layout, download the source code and find xml layouts in the layout folder.

Contact Model Class:

We need three field variable 
  • name
  • phone No
  • image id
We create a constructor using these fields to create an object of Contact.

// ADLabs
public class ContactModel {

    private String name;
    private String phoneNo;
    private int imageID;

    public ContactModel(String name, String phoneNo, int imageID) {
        setName(name);
        setPhoneNo(phoneNo);
        setImageID(imageID);
    }
    . . . . . . . .

}

Contact Adapter Class:

Here we will design our adapter for this we will extend ArrayAdapter class to override methods that already written by sdk.

We need two fields
  • context
  • ArrayList(<ContactModel>) contactList
We create a constructor using these fields to pass them from Main Activity.

// ADLabs

public class ContactAdapter extends ArrayAdapter {

    Context context;
    ArrayList contactList;

    public ContactAdapter(Context context, ArrayList objects) {
        super(context, R.layout.custom_layout, objects);
        this.context=context;
        this.contactList=objects;

    }

Inside the super method we specify our custom_layout that we going to use in ListView.

Now make a static class 'class_name' that contains EditText &ImageView referances.


// ADLabs

static class ViewHolder{
        ImageView pic;
        TextView showNameTV;
        TextView showPhoneNoTV;

    }


Why do we need such a class?
Answer is we will use an object that contains these fields.

Now, override 'getView'
From the name of method we can guess that return something view. Yes, We will generate our custom view for ListView by overriding this method.


// ADLabs

// generate view by myself instead of OS
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

     // Create reference of ViewHolder Class
        ViewHolder viewHolder ;

  // If view all ready created...
        if(convertView == null){

            // Call System Service: Layout_Inflater Service
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   // to convert my xml custom layout into view! by Layout_Inflater Service
            convertView = layoutInflater.inflate(R.layout.custom_layout,null);
   
   // Create Object
            viewHolder = new ViewHolder();
   // Initialize  
            viewHolder.pic= (ImageView) convertView.findViewById(R.id.showImageID);
            viewHolder.showNameTV= (TextView) convertView.findViewById(R.id.showNameID);
            viewHolder.showPhoneNoTV= (TextView) convertView.findViewById(R.id.showPhoneNoID);
   // Tag that object
            convertView.setTag(viewHolder);

        }else {
   // use already tagged object
            viewHolder = (ViewHolder) convertView.getTag();

        }
        // Set Values to 
        viewHolder.pic.setImageResource(contactList.get(position).getImageID());
        viewHolder.showNameTV.setText(contactList.get(position).getName());
        viewHolder.showPhoneNoTV.setText(contactList.get(position).getPhoneNo());

        return convertView;
    }



Inside the getView method

  • Create a ViewHolder Class reference.
  • At starting point view is null. So if condition will execute.
  • Call a system Service: Layout_Inflater_Service. This service will convert our custom layout XML file to view.
  • keep the generated view in a reference.
  • Create object of ViewHolder class
  • Initialize through object.
  • Tag this view Object for further use.
  • Set values through object and return that view.
  • Next time else condition will execute as we already created our view.
  • Retrieve view Object.
  • Set values through object & return view.

Now inside Main Activity:

we will put user input in a ArrayList(<ContactModel>) and pass it through Contact Adapter.
Code:


// ADLabs

        contactsLV = (ListView) findViewById(R.id.contactsLVID);
        nameET = (EditText) findViewById(R.id.nameETID);
        phoneNoET = (EditText) findViewById(R.id.phoneETID); 

        ArrayList<contactmodel>contactList = new ArrayList<>();
         
        // Create Adapter        
        ContactAdapter adapter = new ContactAdapter(getApplicationContext(),contactList);
        contactsLV.setAdapter(adapter);

        contactsLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {

                Intent intent = new Intent(MainActivity.this,Main2Activity.class);
                intent.putExtra("nameKey",contactList.get(position).getName());
                intent.putExtra("phoneNoKey",contactList.get(position).getPhoneNo());
                intent.putExtra("imageKey",contactList.get(position).getImageID());
                startActivity(intent);
            }
        });


We we press any item in the list, Intent will pass value of current position to Main2Activity.

Now, Main2Activity Code: (Contact Details)

Code:

// ADLabs

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        profileImage = (ImageView) findViewById(R.id.contactDetailImgID);
        profileName = (TextView) findViewById(R.id.contactDetailNameID);
        profilePhoneNo = (TextView) findViewById(R.id.contactDetailPhoneID);
        callBtn = (ImageButton) findViewById(R.id.callBtnID);
        msgBtn = (ImageButton) findViewById(R.id.msgBtnID);

        profileImage.setImageResource(getIntent().getIntExtra("imageKey", 0));
        profileName.setText(getIntent().getStringExtra("nameKey"));
        phoneNo = getIntent().getStringExtra("phoneNoKey");
        profilePhoneNo.setText(phoneNo);


    }

    public void callNumber(View view){
        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNo));
        startActivity(callIntent);

    }

    public void msgNumber(View view){
        Intent msgIntent = new Intent(Intent.ACTION_SENDTO,Uri.parse("smsto:" + phoneNo));
        startActivity(msgIntent);
    }


We will retrieve value from Intent by message key and set them.
When Call button clicked Action_Call service will run.
When Message button clicked Action_SendTo service will run.

Try It Now.



( ͡° ͜ʖ ͡°)
Happy Coding :)
-@D

Thursday 3 March 2016

How to process forms using PHP & MySQL

What to Do:

Lets say Mr. Kopa is a university student. He want to take a course in the upcoming semester. So, he go to university website and click in the registration button.
Then registration form appear, he fill all of the field and hit submit button. He wanted to review his info by clicking review button.
Now, what happens during this process, consider the following picture.
 
Form Process






















> A html form is first showed up 
> When submit button is clicked data is processed by php script and stored to database.
> When review button is clicked php script retrieved from database, process it and  displayed.

Lets build our project:
We will distribute our workload to our stuff. 

  • index.php file will display form with the help of html
  • process-student.php file will take the info from index.php
  • process-student.php file will save the info in database by config.php
  • then courseform.php will show up and take info just line index.php
  • the view.php will display all info that already stored in database

What's inside them:

index.php file function:


html has two main part: head & body. In side body we will use <form> tab, post method will pass the data to action php script, in our case its process-student.php
<input> tab is used to make field and every field has a unique name. This unique name is used to pass data by post method.

config.php file function:


This file will provide the host-name, user-name, user-password , database-name of MySQL database.

process-student.php file function:

This file first load the config.php file to connect the database. '$_post' method will catch the data from index file by these unique name.
SQL query store data into the database table that we already created.
If SQL query somehow fail it will stop the script and show the specific error, or it will redirect to courseform.php file.

courseform.php file function:

This file function is as same as index file. It will take the course info from user.

process-course.php file function:

Same function as process-student file.


view.php file function:

This file log in the database and retrieve data from data-table by SQL query then displayed to the user.

That's the basic functions of our files.

How to run it: 
  • Download the source files from download link and place it to localhost root.
  • Create database as student_db and import the backup sql file.
  • Then go to browser and put the url: localhost/index.php


Happy Coding :)
@D

Sunday 21 February 2016

Java: Inheritance Relationship with Example.

Association Vs Inheritance

Association: Association in Java establish relationship between two classes through their Objects. This relationship can be four type.

  • One to One
  • One to Many
  • Many to One
  • Many  to Many
Inheritance: Inheritance is a process where one class gain the properties (public field & method) of another class. The class which inherits the properties of other class is known as subclass(child/derived class) and the class whose properties will be inherited is known as super-class(parent/base class).

Difference: They both have code reuse ability but inheritance has the ownership of base class.

Keyword: extends

Case Study:

Suppose, In a Bank, there are two types of accounts.
  • Savings Account
  • Current Account
Both accounts have the following fields
  • Account Number
  • Account Name
  • Balance
and methods
  • Deposit
  • Withdraw
Savings account has interest rate and 
current account has service charge field.

Lets see the class diagram:
Class Diagram
Here, BankAccount is parent class and SavingsAccount & CurrentAccount are child class.

Savings account is not allowed to null the account balance and current account is allowed to take loan from bank.
So we have to overwrite the withdraw method for logic implementation.

Lets see the following code:

BankAccount Class:

// ADLabs


public class BankAccount {

 private String accountNO;
 private String accountName;
 private double balance;

 public BankAccount(String accountNO, String accountName) {
  this.accountNO = accountNO;
  this.accountName = accountName;

 }

 public BankAccount() {
  balance = 0;
 }

 public void deposit(double money) {
  balance += money;
  System.out.println("Money Successfully Deposited!");
 }

 public void withdraw(double money) {
  balance -= money;
  System.out.println("Balance :" + balance);
 }

 public double getBalance() {
  return balance;
 }

 public void setBalance(double balance) {
  this.balance = balance;
 }

}

SavingsAccount Class :
// ADLabs


public class SavingsAccount extends BankAccount {

 private float interestRate;

 public SavingsAccount(String accountNO, String accountName, float interestRate) {
  super(accountNO, accountName);
  this.interestRate = interestRate;
 }

 public void monthEndBalance() {
  float money = (float) (getBalance() + (getBalance() * (interestRate / 12)));
  System.out.println("Month End Balance will be :" + money);
 }

 public void withdraw(double money) {
  // Overwrite the super method.
  if (getBalance() - money >= 500) {
   super.withdraw(money);
  } else
   System.out.println("Insufficient Balance!");
 }
}


CurrentAccount Class:

// ADLabs


public class CurrentAccount extends BankAccount {
 private float serviceCharge;

 public CurrentAccount(String accountNO, String accountName, float serviceCharge) {
  super(accountNO, accountName);
  this.serviceCharge = serviceCharge;
 }

 public void monthEndBalance() {

  float money = (float) (getBalance() - (getBalance() * (serviceCharge / 12)));
  System.out.println("Month End Balance will be :" + money);
 }

 public void withdraw(double money) {
  // Overwrite the super method.
  double check = getBalance() - money;
  if (check < 0) {
   super.withdraw(money);
   System.out.println("You Loan from Bank :" + check);
  }
 }
}


main Class:
// ADLabs


public class StartPoint {

 public static void main(String[] args) {

  SavingsAccount account1 = new SavingsAccount("SA-1012", "Kopa Samsu", 5);
  CurrentAccount account2 = new CurrentAccount("CA-1023", "Musa Bin", 7);

  account1.deposit(5000);
  account2.deposit(5000);
  account1.monthEndBalance();
  account2.monthEndBalance();
  account1.withdraw(1000);
  account2.withdraw(5500);
 }

}


Console:

Money Successfully Deposited!
Money Successfully Deposited!
Month End Balance will be :7083.3335
Month End Balance will be :2083.3335
Balance :4000.0
Balance :-500.0
You Loan from Bank :-500.0


( ͡° ͜ʖ ͡°)
Happy Coding :)
-@D

Thursday 18 February 2016

Java: Class Diagram & OneToOne Association Relationship.

Q: Create two classes and define one-to-one association relationship between them. Demonstrate it from "main" method.

//

Consider a person, in our case its Vai (Don) "Kopa Samsu".

( ͡° ͜ʖ ͡°)


// Profile
Name     : " Kopa Samsu "
Address : " D3, 22A Road, Dhaka, 1100 "

Mr. Kopa Samsu has only one Den that is the address specified in his profile.
Now, Create a Person Class and Address Class in our java project.


  • Person Class will contain firstName, lastName and personAddress attributes.
  • Address Class will contain houseNo, roadNo, postCode, district attributes.
  • Person Class will also use Calculator Class to find out the amount of Salami(money) to given to Vai.

  Class Diagram: One-to-One Association Relationship.


Address ClassPerson Class_1____________________>1



// Person Class CODE:


// ADLabs

public class Person {
 private String firstName;
 private String middleName;
 private String lastName;
 private Address personAddress;

 public void setPersonAddress(Address personAddress) {
  this.personAddress = personAddress;
 }

 public Address getPersonAddress() {
  return personAddress;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public Person(String firstName, String middleName, String lastName) {
  this(firstName, lastName);
  setMiddleName(middleName);
 }

 public Person(String firstName, String lastName) {
  this();
  setFirstName(firstName);
  setLastName(lastName);
 }

 public Person() {

 }

 public double getSalami() {
  double basic = 10000;
  double specialCase = 5000;
  Calculator aCalc = new Calculator();
  double total = aCalc.add(basic, specialCase);
  return total;
 }

 public String getMiddleName() {
  return middleName;
 }

 public void setMiddleName(String middleName) {
  this.middleName = middleName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getFullName() {
  String fullName = firstName + " " + lastName;
  return fullName;
 }
}



// Address Class CODE
:

// ADLabs
public class Address {
 private String houseNo;
 private String roadNo;
 private String district;
 private int postCode;

 public Address(String houseNo, String roadNo, String district, int postCode) {
  this.houseNo = houseNo;
  this.roadNo = roadNo;
  this.postCode = postCode;
  this.district = district;
 }

 public String getHouseNo() {
  return houseNo;
 }

 public void setHouseNo(String houseNo) {
  this.houseNo = houseNo;
 }

 public String getRoadNo() {
  return roadNo;
 }

 public void setRoadNo(String roadNo) {
  this.roadNo = roadNo;
 }

 public int getPostCode() {
  return postCode;
 }

 public void setPostCode(int postCode) {
  this.postCode = postCode;
 }

 public String getDistrict() {
  return district;
 }

 public void setDistrict(String district) {
  this.district = district;
 }

}



// Calculator Class:

// ADLabs

public class Calculator {
 public double add(double n1, double n2) {
  return n1 + n2;
 }

 public double subtract(double n1, double n2) {
  return n1 - n2;
 }
}


// main Class Code:

// ADLabs

public class StartPoint {

 public static void main(String[] args) {

  Person aPerson = new Person();
  aPerson.setFirstName("Kopa");
  aPerson.setLastName("Samsu");

  Address address1 = new Address("D3", "22A", "Dhaka", 1100);

  aPerson.setPersonAddress(address1);

  System.out.println("Go to this Address :\n");
  System.out.println("Name: " + aPerson.getFullName());
  System.out.println("House Number: " + aPerson.getPersonAddress().getHouseNo());
  System.out.println("Road No: " + aPerson.getPersonAddress().getRoadNo());
  System.out.println("District :" + aPerson.getPersonAddress().getDistrict() + "\n");
  System.out.println("Give Salami :");
  System.out.println("Salami : " + aPerson.getSalami());
 }

}


Happy Coding :)
-@D

Tuesday 16 February 2016

Java: Draw a Palindromic Pyramid / Triangle java program.

Problem: Palindromic Pyramid

Draw a palindromic pyramid or triangle of a given height.
Sample Input:
5
Sample Output:
        1
      121
    12321
  1234321
123454321

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();

  // Palindromic Triangle

  for (int i = 1; i <= n; i++) {

   for (int j = i; j < n; j++) {

    System.out.print(" ");
   }

   for (int k = 1; k <= i; k++)
    System.out.print(k);
   for (int l = i - 1; l > 0; l--)
    System.out.print(l);

   System.out.println();

  }

  sc.close();
 }

}




Console:

Enter any Int Num:5

        1
      121
    12321
  1234321
123454321

Happy Coding :)
-@D