Login Validation

Web Hosting
In this tutorial, I will show you how to validate login using static input. See output below.



Here's the view of my project.


Here's the code of LoginModel.java

package com.example.model;

public class LoginModel {

public String m_email, m_password;

//constructor
public LoginModel(String email, String password){
this.m_email = email;
this.m_password = password;
}

}


Here's the code of Controller.java

package com.example.controller;

import java.util.regex.Pattern;

import android.util.Patterns;

import com.example.model.LoginModel;

public class Controller{

//static variables
private static final String EMAIL = "gaudicos61@gmail.com";
private static final String PASSWORD = "gaudicos";

@SuppressWarnings("unused")
public boolean isCheckEmail(LoginModel model) {
Pattern pattern = Patterns.EMAIL_ADDRESS;
if(pattern.matcher(model.m_email).matches() == true && model.m_email.equals(EMAIL)){
return true;
}else{
return false;
}
}



public boolean isCheckPassword(LoginModel model){
if(PASSWORD.equals(model.m_password)){
return true;
}else{
return false;
}
}

}


Here's the code of MainActivity.java

package com.example.menudesign;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.controller.Controller;
import com.example.model.LoginModel;

public class MainActivity extends Activity implements OnClickListener{

private EditText et_email,et_password;
private TextView tv_error_email, tv_error_pass;
private Button btn_login;

LoginModel model;
Controller c_controller;

private int email_indicator = 0, password_indicator = 0;

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

initializeVars();


}

public void initializeVars(){
et_email = (EditText)findViewById(R.id.et_sample1);
et_password = (EditText)findViewById(R.id.et_sample2);
tv_error_email = (TextView)findViewById(R.id.tv_validate_email);
tv_error_pass = (TextView)findViewById(R.id.tv_validate_password);
btn_login = (Button)findViewById(R.id.btn_login);
tv_error_email.setVisibility(View.INVISIBLE);
tv_error_pass.setVisibility(View.INVISIBLE);
btn_login.setEnabled(false);

btn_login.setOnClickListener(this);

//listen the the editText when it's value changed
TextWatcher watcher = new TextWatcher() {

public void afterTextChanged(Editable s) {

model = new LoginModel(et_email.getText().toString(), et_password.getText().toString());
c_controller = new Controller();
   
try{ 
if(c_controller.isCheckEmail(model) == false && c_controller.isCheckPassword(model) == false){
     
tv_error_email.setVisibility(View.VISIBLE);
tv_error_email.setText("Invalid email address or doesnt match.");
tv_error_pass.setVisibility(View.VISIBLE);
tv_error_pass.setText("Invalid password or doesnt match.");
btn_login.setEnabled(false);
email_indicator = 0;
    password_indicator = 0;    
     
}else if(c_controller.isCheckEmail(model) == true && c_controller.isCheckPassword(model) == false){
     
   tv_error_pass.setVisibility(View.VISIBLE);
   tv_error_pass.setText("Invalid password or doesnt match.");
   btn_login.setEnabled(false);
   email_indicator = 1;
    password_indicator = 0;
   
    }else if(c_controller.isCheckEmail(model) == false && c_controller.isCheckPassword(model) == true){
     
    tv_error_email.setVisibility(View.VISIBLE);
    tv_error_email.setText("Invalid email address or doesnt match.");
    btn_login.setEnabled(false);
    email_indicator = 0;
    password_indicator = 1;
   
    }else{
   //means all input are valid, code here to login...
    email_indicator = 1;
    password_indicator = 1;
    btn_login.setEnabled(true);
    }
   

}catch(StringIndexOutOfBoundsException e){
     e.printStackTrace();
}
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
tv_error_email.setVisibility(View.INVISIBLE);
tv_error_pass.setVisibility(View.INVISIBLE);
};
};


et_email.addTextChangedListener(watcher);
et_password.addTextChangedListener(watcher);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btn_login:
if(email_indicator == 1 && password_indicator == 1){
Toast.makeText(getApplicationContext(), "You can now log in here!", Toast.LENGTH_SHORT).show();
}
}
}



}


Here's the code of 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_sample1"
        android:layout_width="500dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="46dp" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/et_sample2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/et_sample1"
        android:layout_alignRight="@+id/et_sample1"
        android:layout_below="@+id/et_sample1"
        android:layout_marginTop="10dp" />

    <TextView
        android:id="@+id/tv_validate_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/et_sample2"
        android:layout_below="@+id/et_sample1"
        android:textSize="12sp"
        android:visibility="gone"
        android:textColor="#FFFFFF"
        android:background="@drawable/ic_error_bg" />
    
    
    <TextView
        android:id="@+id/tv_validate_password"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/et_sample2"
        android:layout_below="@+id/et_sample2"
        android:textSize="12sp"
        android:visibility="gone"
        android:textColor="#FFFFFF"
        android:background="@drawable/ic_error_bg" />

    <Button
        android:id="@+id/btn_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_validate_password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="31dp"
        android:text="Login" />


</RelativeLayout>


Web Hosting
That's it, hope this simple tutorial may help you. Happy Coding.

Basic Calculator

Web Hosting
In this tutorial, I will show you how to create simple calculator in Android. See output below!



Here's the CalculatorModel.java

package com.example.calculator;

public class CalculatorModel {

double m_num1, m_num2;

//constructor

public CalculatorModel(double num1, double num2){
this.m_num1 = num1;
this.m_num2 = num2;
}

//setters

public void setNum1(double num1){
this.m_num1 = num1;
}

public void setNum2(double num2){
this.m_num2 = num2;
}

//getters

public double getNum1(){
return this.m_num1;
}

public double getNum2(){
return this.m_num2;
}

}


Here's the CalculatorController.java

package com.example.calculator;

public class CalculatorController {

public double addition(CalculatorModel cmodel){
return cmodel.m_num1 + cmodel.m_num2;
}
public double subtraction(CalculatorModel cmodel){
return cmodel.m_num1 - cmodel.m_num2;
}
public double multiplication(CalculatorModel cmodel){
return cmodel.m_num1 * cmodel.m_num2;
}
public double divistion(CalculatorModel cmodel){
return cmodel.m_num1 / cmodel.m_num2;
}
}


Here's the CalculatorActivity.java

package com.example.calculator;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class CalculatorActivity extends Activity implements OnClickListener{

EditText et_result;
Button btn_one, btn_two, btn_three, btn_four, btn_five, btn_six, btn_seven, 
btn_eight, btn_nine, btn_zero, btn_point, btn_add, btn_minus, btn_times, 
btn_divide, btn_equal, btn_clear;
double num1 = 0;
int indicator = 0;
CalculatorModel c_model;
CalculatorController c_controller;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
initializeVars();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.calculator, menu);
return true;
}
public void initializeVars(){
et_result = (EditText)findViewById(R.id.et_result);
btn_one = (Button)findViewById(R.id.btn_one);
btn_two = (Button)findViewById(R.id.btn_two);
btn_three = (Button)findViewById(R.id.btn_three);
btn_four = (Button)findViewById(R.id.btn_four);
btn_five = (Button)findViewById(R.id.btn_five);
btn_six = (Button)findViewById(R.id.btn_six);
btn_seven = (Button)findViewById(R.id.btn_seven);
btn_eight = (Button)findViewById(R.id.btn_eight);
btn_nine = (Button)findViewById(R.id.btn_nine);
btn_zero = (Button)findViewById(R.id.btn_zero);
btn_point = (Button)findViewById(R.id.btn_point);
btn_add = (Button)findViewById(R.id.btn_add);
btn_minus = (Button)findViewById(R.id.btn_minus);
btn_times = (Button)findViewById(R.id.btn_times);
btn_divide = (Button)findViewById(R.id.btn_divide);
btn_equal = (Button)findViewById(R.id.btn_equal);
btn_clear = (Button)findViewById(R.id.btn_clear);
btn_one.setOnClickListener(this);
btn_two.setOnClickListener(this);
btn_three.setOnClickListener(this);
btn_four.setOnClickListener(this);
btn_five.setOnClickListener(this);
btn_six.setOnClickListener(this);
btn_seven.setOnClickListener(this);
btn_eight.setOnClickListener(this);
btn_nine.setOnClickListener(this);
btn_zero.setOnClickListener(this);
btn_point.setOnClickListener(this);
btn_add.setOnClickListener(this);
btn_minus.setOnClickListener(this);
btn_times.setOnClickListener(this);
btn_divide.setOnClickListener(this);
btn_equal.setOnClickListener(this);
btn_clear.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
switch(v.getId()){
case R.id.btn_one:
et_result.setText(et_result.getText().toString()+btn_one.getText().toString());
break;
case R.id.btn_two:
et_result.setText(et_result.getText().toString()+btn_two.getText().toString());
break;
case R.id.btn_three:
et_result.setText(et_result.getText().toString()+btn_three.getText().toString());
break;
case R.id.btn_four:
et_result.setText(et_result.getText().toString()+btn_four.getText().toString());
break;
case R.id.btn_five:
et_result.setText(et_result.getText().toString()+btn_five.getText().toString());
break;
case R.id.btn_six:
et_result.setText(et_result.getText().toString()+btn_six.getText().toString());
break;
case R.id.btn_seven:
et_result.setText(et_result.getText().toString()+btn_seven.getText().toString());
break;
case R.id.btn_eight:
et_result.setText(et_result.getText().toString()+btn_eight.getText().toString());
break;
case R.id.btn_nine:
et_result.setText(et_result.getText().toString()+btn_nine.getText().toString());
break;
case R.id.btn_zero:
et_result.setText(et_result.getText().toString()+btn_zero.getText().toString());
break;
case R.id.btn_point:
et_result.setText(et_result.getText().toString()+btn_point.getText().toString());
break;
case R.id.btn_add:
num1 = Double.parseDouble(et_result.getText().toString());
et_result.setText("");
indicator = 1;
break;
case R.id.btn_minus:
num1 = Double.parseDouble(et_result.getText().toString());
et_result.setText("");
indicator = 2;
break;
case R.id.btn_times:
num1 = Double.parseDouble(et_result.getText().toString());
et_result.setText("");
indicator = 3;
break;
case R.id.btn_divide:
num1 = Double.parseDouble(et_result.getText().toString());
et_result.setText("");
indicator = 4;
break;
case R.id.btn_clear:
et_result.setText("");
break;
case R.id.btn_equal:
c_model = new CalculatorModel(num1, Double.parseDouble(et_result.getText().toString()));
c_controller = new CalculatorController();
switch(indicator){
case 1:
et_result.setText(Double.toString(c_controller.addition(c_model)));
break;
case 2:
et_result.setText(Double.toString(c_controller.subtraction(c_model)));
break;
case 3:
et_result.setText(Double.toString(c_controller.multiplication(c_model)));
break;
case 4:
et_result.setText(Double.toString(c_controller.divistion(c_model)));
break;
}
break;
}
}catch(Exception e){
e.printStackTrace();
}
}

}


And lastly, the activity_calculator.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".CalculatorActivity" >

    <RelativeLayout 
        android:id="@+id/rl_hold_calculator"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true">
        "
   <EditText
       android:id="@+id/et_result"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_marginTop="20dp"
       android:ems="10"
       android:inputType="numberDecimal" >
       <requestFocus />
   </EditText>
   <Button
       android:id="@+id/btn_one"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/et_result"
       android:layout_below="@+id/et_result"
       android:layout_marginTop="10dp"
       android:text="1" />
   <Button
       android:id="@+id/btn_two"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_one"
       android:layout_alignBottom="@+id/btn_one"
       android:layout_toRightOf="@+id/btn_one"
       android:text="2" />
   <Button
       android:id="@+id/btn_three"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_two"
       android:layout_alignBottom="@+id/btn_two"
       android:layout_toRightOf="@+id/btn_two"
       android:text="3" />
   <Button
       android:id="@+id/btn_four"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_three"
       android:layout_alignBottom="@+id/btn_three"
       android:layout_toRightOf="@+id/btn_three"
       android:text="4" />
   <Button
       android:id="@+id/btn_five"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/btn_one"
       android:layout_below="@+id/btn_one"
       android:layout_marginTop="10dp"
       android:text="5" />
   <Button
       android:id="@+id/btn_six"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_five"
       android:layout_alignBottom="@+id/btn_five"
       android:layout_alignLeft="@+id/btn_two"
       android:text="6" />
   <Button
       android:id="@+id/btn_seven"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_six"
       android:layout_alignBottom="@+id/btn_six"
       android:layout_alignLeft="@+id/btn_three"
       android:text="7" />
   <Button
       android:id="@+id/btn_eight"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_seven"
       android:layout_alignBottom="@+id/btn_seven"
       android:layout_toRightOf="@+id/btn_seven"
       android:text="8" />
    
    

   <Button
       android:id="@+id/btn_nine"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/btn_five"
       android:layout_below="@+id/btn_five"
       android:layout_marginTop="10dp"
       android:text="9" />
   <Button
       android:id="@+id/btn_zero"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_nine"
       android:layout_alignBottom="@+id/btn_nine"
       android:layout_toRightOf="@+id/btn_nine"
       android:text="0" />
   <Button
       android:id="@+id/btn_point"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_zero"
       android:layout_alignBottom="@+id/btn_zero"
       android:layout_toRightOf="@+id/btn_zero"
       android:text="." />
   <Button
       android:id="@+id/btn_clear"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_point"
       android:layout_alignBottom="@+id/btn_point"
       android:layout_toRightOf="@+id/btn_point"
       android:text="C" />
   <Button
       android:id="@+id/btn_add"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/btn_nine"
       android:layout_below="@+id/btn_nine"
       android:layout_marginTop="10dp"
       android:text="+" />
   <Button
       android:id="@+id/btn_minus"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_add"
       android:layout_alignBottom="@+id/btn_add"
       android:layout_toRightOf="@+id/btn_add"
       android:text="-" />
   <Button
       android:id="@+id/btn_times"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_minus"
       android:layout_alignBottom="@+id/btn_minus"
       android:layout_alignLeft="@+id/btn_point"
       android:text="*" />
   <Button
       android:id="@+id/btn_divide"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBaseline="@+id/btn_times"
       android:layout_alignBottom="@+id/btn_times"
       android:layout_alignLeft="@+id/btn_clear"
       android:text="/" />
   <Button
       android:id="@+id/btn_equal"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignLeft="@+id/btn_add"
       android:layout_alignParentRight="true"
       android:layout_below="@+id/btn_add"
       android:layout_marginTop="10dp"
       android:text="=" />
    
    </RelativeLayout>

</RelativeLayout>


Web Hosting
That's it, hope this simple tutorial may help you. Happy Coding!


Customized Spinner Using ArrayAdapter

Web Hosting
In this tutorial, I'm just referring from this link. See code below!

In this Example creating custom spinner with one image and two texts.
After spinner item selection showing selected item text on screen.

Steps :

       1.  Create Model (SpinnerModel.java) to store data for each spinner row.
       2.  Create a ArrayList to store Model (SpinnerModel.java) objects.
       3.  Store data in Models and Store Model objects in Arraylist.
       4.  Pass Model object Arraylist to custom adapter.
       5.  Custom Adapter use Arraylist data (Model Objects) and create rows for Spinner.
       6.  Create listener for Spinner and show spinner item selected values on activity.
 Note :
        Please read this tutorial first - Spinner Basics

Project Structure :


Custom Spinner project sketch

File : src/SpinnerModel.java


public class SpinnerModel {
 
        private  String CompanyName="";
        private  String Image=""; 
        private  String Url="";
        
        /*********** Set Methods ******************/
        public void setCompanyName(String CompanyName)
        {
            this.CompanyName = CompanyName;
        }
        
        public void setImage(String Image)
        {
            this.Image = Image;
        }
        
        public void setUrl(String Url)
        {
            this.Url = Url;
        }
        
        /*********** Get Methods ****************/
        public String getCompanyName()
        {
            return this.CompanyName;
        }
        
        public String getImage()
        {
            return this.Image;
        }
    
        public String getUrl()
        {
            return this.Url;
        } 
  }



File : res/layout/activity_custom_spinner.xml

Define spinner and output text.

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        
        <TextView
            android:paddingTop="20dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
            
        <Spinner
            android:id="@+id/spinner"
            android:drawSelectorOnTop="true"
            android:prompt="@string/defaultText"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            
            />
            
        <TextView
            android:paddingTop="20dip"
            android:paddingLeft="20dip"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/output"
            />
            
    </LinearLayout>



File : src/CustomSpinner.java

Explanation i have commented in code.

import java.util.ArrayList;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;  
 
public class CustomSpinner extends Activity {
 
    /**************  Intialize Variables *************/
    public  ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
    TextView output = null;
    CustomAdapter adapter;
    CustomSpinner activity = null;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_spinner);
        
        activity  = this;
        
        Spinner  SpinnerExample = (Spinner)findViewById(R.id.spinner);
        output                  = (TextView)findViewById(R.id.output);
        
        // Set data in arraylist
        setListData();
        
        // Resources passed to adapter to get image
        Resources res = getResources(); 
        
        // Create custom adapter object ( see below CustomAdapter.java )
        adapter = new CustomAdapter(activity, R.layout.spinner_rows, CustomListViewValuesArr,res);
        
        // Set adapter to spinner
        SpinnerExample.setAdapter(adapter);
        
        // Listener called when spinner item selected
        SpinnerExample.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
                // your code here
             
                // Get selected row data to show on screen
             String Company    = ((TextView) v.findViewById(R.id.company)).getText().toString();
             String CompanyUrl = ((TextView) v.findViewById(R.id.sub)).getText().toString();
             
             String OutputMsg = "Selected Company : \n\n"+Company+"\n"+CompanyUrl;
             output.setText(OutputMsg);
             
             Toast.makeText(
      getApplicationContext(),OutputMsg, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });
    }
 
    /****** Function to set data in ArrayList *************/
    public void setListData()
    {
     
        // Now i have taken static values by loop.
        // For further inhancement we can take data by webservice / json / xml;
        
  for (int i = 0; i < 11; i++) {
   
   final SpinnerModel sched = new SpinnerModel();
       
     /******* Firstly take data in model object ******/
      sched.setCompanyName("Company "+i);
      sched.setImage("image"+i);
      sched.setUrl("http:\\www."+i+".com");
      
   /******** Take Model Object in ArrayList **********/
   CustomListViewValuesArr.add(sched);
  }
  
    }
    
  }


File : src/CustomAdapter.java

Read comments in code for explanation

import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/***** Adapter class extends with ArrayAdapter ******/
public class CustomAdapter extends ArrayAdapter<String>{
 
 private Activity activity;
    private ArrayList data;
    public Resources res;
    SpinnerModel tempValues=null;
    LayoutInflater inflater;
 
    /*************  CustomAdapter Constructor *****************/
 public CustomAdapter(
                 CustomSpinner activitySpinner, 
                 int textViewResourceId,   
                 ArrayList objects,
                 Resources resLocal
                ) 
  {
        super(activitySpinner, textViewResourceId, objects);
        
        /********** Take passed values **********/
        activity = activitySpinner;
        data     = objects;
        res      = resLocal;
   
        /***********  Layout inflator to call external xml layout () **********************/
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        
   }

    @Override
    public View getDropDownView(int position, View convertView,ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    // This funtion called for each row ( Called data.size() times )
    public View getCustomView(int position, View convertView, ViewGroup parent) {

     /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
        View row = inflater.inflate(R.layout.spinner_rows, parent, false);
        
        /***** Get each Model object from Arraylist ********/
        tempValues = null;
        tempValues = (SpinnerModel) data.get(position);
        
        TextView label        = (TextView)row.findViewById(R.id.company);
        TextView sub          = (TextView)row.findViewById(R.id.sub);
        ImageView companyLogo = (ImageView)row.findViewById(R.id.image);
        
        if(position==0){
         
         // Default selected Spinner item 
         label.setText("Please select company");
         sub.setText("");
        }
        else
        {
            // Set values for spinner each row 
            label.setText(tempValues.getCompanyName());
            sub.setText(tempValues.getUrl());
            companyLogo.setImageResource(res.getIdentifier
                                         ("com.androidexample.customspinner:drawable/"
                                          + tempValues.getImage(),null,null));
            
        }   

        return row;
      }
 }



File : res/layout/spinner_rows.xml


    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:padding="3dip"
    >
        <ImageView
             android:id="@+id/image"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             />
        <TextView
             android:layout_toRightOf="@+id/image"
             android:padding="3dip"
             android:layout_marginTop="2dip"
             android:textColor="@drawable/red"
             android:textStyle="bold"
             android:id="@+id/company"
             android:layout_marginLeft="5dip"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"/>
         <TextView
             android:layout_toRightOf="@+id/image"
             android:padding="2dip"
             android:textColor="@drawable/darkgrey"
             android:layout_marginLeft="5dip"
             android:id="@+id/sub"
             android:layout_below="@+id/company"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"/>
    </RelativeLayout>


File : res/values/strings.xml


   <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="hello">Custom Spinner</string>
        <string name="defaultText">  Select your Company  </string>
        <string name="app_name">CustomSpinner Demo</string>
        <drawable name="Blue">#b0e0e6</drawable>
        <drawable name="white">#ffffff</drawable>
        <drawable name="black">#000000</drawable>
        <drawable name="green">#347C2C</drawable>
        <drawable name="pink">#FF00FF</drawable>
        <drawable name="violet">#a020f0</drawable>
        <drawable name="grey">#cccccc</drawable>
        <drawable name="red">#C11B17</drawable>
        <drawable name="yellow">#FFFF8C</drawable>
        <drawable name="PowderBlue">#b0e0e6</drawable>
        <drawable name="brown">#2F1700</drawable>
        <string name="select_Category">Select Company</string>
        <drawable name="darkgrey">#606060</drawable>
    
    </resources>
Web Hosting

DatePicker and TimePicker Dialog in Android

Web Hosting
In this tutorial, I will show you how to create a datepicker and timepicker dialog in android. I'm just refer this tutorial from this link.

We can use Time Picker  and Date Picker   widget to select a time and date , but TimePickerDialog and DatePickerDialog  is a better choice to do that.

In this post I will discuss how to use DatePickerDialog and TimePickerDialog to select Date and Time.



DatePickerDialog In Android
                       





Here I have described briefly, the Example with full source code is given below after this.
  
Declare following Variables in your Activity/Class

static final int DATE_DIALOG_ID = 0;
static final int TIME_DIALOG_ID=1;

// variables to save user selected date and time
public  int yearSelected,monthSelected,daySelected,hourSelected,minuteSelected;
  
// declare  the variables to show the date and time whenTime and Date Picker Dialog first appears
private int mYear, mMonth, mDay,mHour,mMinute; 

In the constructor you can initiallise the variable to current date and time.

                
                    final Calendar c = Calendar.getInstance();
                    mYear = c.get(Calendar.YEAR);
                    mMonth = c.get(Calendar.MONTH);
                    mDay = c.get(Calendar.DAY_OF_MONTH);
                    mHour = c.get(Calendar.HOUR_OF_DAY);
                    mMinute = c.get(Calendar.MINUTE);



//call the method when you need to show DatePickerDialog
 showDialog(DATE_DIALOG_ID);
//call the method when you need to show DatePickerDialog
  showDialog(TIME_DIALOG_ID);

// Register  DatePickerDialog listener
 private DatePickerDialog.OnDateSetListener mDateSetListener =
                        new DatePickerDialog.OnDateSetListener() {
                 // the callback received when the user "sets" the Date in the DatePickerDialog
                            public void onDateSet(DatePicker view, int yearSelected,
                                                  int monthOfYear, int dayOfMonth) {
                               year
Selected = yearSelected;
                               monthSelected = monthOfYear;
                               daySelected = dayOfMonth;
                              Toast.makeText(getApplicationContext(), "Date selected is:"+daySelected+"-"+monthSelected+"-"+yearSelected, Toast.LENGTH_LONG).show();
                                                         }
                        };


   // Register  TimePickerDialog listener                 
                        private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                            new TimePickerDialog.OnTimeSetListener() {
             // the callback received when the user "sets" the TimePickerDialog in the dialog
                                public void onTimeSet(TimePicker view, int hourOfDay, int min) {

                                    hourSelected = hourOfDay;
                                    minuteSelected = min;
                                   Toast.makeText(getApplicationContext(), "Time selected is:"+hourSelected+"-"+minuteSelected, Toast.LENGTH_LONG).show();
                                                                  }
                            };


// Method automatically gets Called when you call showDialog()  method
                        @Override
                        protected Dialog onCreateDialog(int id) {
                            switch (id) {
                            case DATE_DIALOG_ID:
                                return new DatePickerDialog(this,
                                            mDateSetListener,
                                            mYear, mMonth, mDay);
                            case TIME_DIALOG_ID:
                                return new TimePickerDialog(this,
                                        mTimeSetListener, mHour, mMinute, false);
                            
                            }
                            return null;
                        }
                        

Date And Time Picker Dialog Example with Full Source Code

In the example   I have 2 buttons  
1: Select Date - to show DatePickerDialog 
2: Select Time - to show TimePickertDialog
When user selects a Date and Time in respective Dialogs we will set the selected date and time in Respective buttons. We will set selected date in Select Date Button and selected time in Select Time Button(See the last Snapshot)


main.xml



DatePickerDialog In Android



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:textSize="25dp"
        android:layout_gravity="center_horizontal"
        android:text="Date And Time Picker Example" />

    <Button
        android:id="@+id/buttonSelectDate"
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Date" />

    <Button
        android:id="@+id/buttonSelectTime"
        android:layout_marginTop="20dp"
        android:textSize="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Select Time" />

</LinearLayout>




DateAndTimePickerActivity.java 

public class DateAndTimePickerActivity extends Activity
{

            Button btnSelectDate,btnSelectTime;
           
            static final int DATE_DIALOG_ID = 0;
            static final int TIME_DIALOG_ID=1;
           
          
      // variables to save user selected date and time
            public  int year,month,day,hour,minute;  

 // declare  the variables to Show/Set the date and time when Time and  Date Picker Dialog first appears
            private int mYear, mMonth, mDay,mHour,mMinute; 
            
            // constructor
            
            public DateAndTimePickerActivity()
            {
                        // Assign current Date and Time Values to Variables
                        final Calendar c = Calendar.getInstance();
                        mYear = c.get(Calendar.YEAR);
                        mMonth = c.get(Calendar.MONTH);
                        mDay = c.get(Calendar.DAY_OF_MONTH);
                        mHour = c.get(Calendar.HOUR_OF_DAY);
                        mMinute = c.get(Calendar.MINUTE);
            }
            
            @Override
            protected void onCreate(Bundle savedInstanceState) 
            {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.date_and_time_picker);
                        
                        // get the references of buttons
                        btnSelectDate=(Button)findViewById(R.id.buttonSelectDate);
                        btnSelectTime=(Button)findViewById(R.id.buttonSelectTime);
                        
                        // Set ClickListener on btnSelectDate 
                        btnSelectDate.setOnClickListener(new View.OnClickListener() {
                            
                            public void onClick(View v) {
                                // Show the DatePickerDialog
                                 showDialog(DATE_DIALOG_ID);
                            }
                        });
                        
                        // Set ClickListener on btnSelectTime
                        btnSelectTime.setOnClickListener(new View.OnClickListener() {
                            
                            public void onClick(View v) {
                                // Show the TimePickerDialog
                                 showDialog(TIME_DIALOG_ID);
                            }
                        });
                        
            }
            
            
            // Register  DatePickerDialog listener

             private DatePickerDialog.OnDateSetListener mDateSetListener =
                                    new DatePickerDialog.OnDateSetListener() {
                                // the callback received when the user "sets" the Date in the DatePickerDialog
                                        public void onDateSet(DatePicker view, int yearSelected,
                                                              int monthOfYear, int dayOfMonth) {
                                           year = yearSelected;
                                           month = monthOfYear;
                                           day = dayOfMonth;
                                           // Set the Selected Date in Select date Button
                                           btnSelectDate.setText("Date selected : "+day+"-"+month+"-"+year);
                                        }
                                    };

               // Register  TimePickerDialog listener                 
                                    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
                                        new TimePickerDialog.OnTimeSetListener() {
                                 // the callback received when the user "sets" the TimePickerDialog in the dialog
                                            public void onTimeSet(TimePicker view, int hourOfDay, int min) {
                                                hour = hourOfDay;
                                                minute = min;
                                                // Set the Selected Date in Select date Button
                                                btnSelectTime.setText("Time selected :"+hour+"-"+minute);
                                              }
                                        };


            // Method automatically gets Called when you call showDialog()  method
                                    @Override
                                    protected Dialog onCreateDialog(int id) {
                                        switch (id) {
                                        case DATE_DIALOG_ID:
                                 // create a new DatePickerDialog with values you want to show 
                                            return new DatePickerDialog(this,
                                                        mDateSetListener,
                                                        mYear, mMonth, mDay);
                                // create a new TimePickerDialog with values you want to show 
                                        case TIME_DIALOG_ID:
                                            return new TimePickerDialog(this,
                                                    mTimeSetListener, mHour, mMinute, false);
                                       
                                        }
                                        return null;
                                    }
                                    
}


TimePickerDialog In Android


Web Hosting
That's it, Happy Coding!