Assigning Labels(Text View)
The simplest widgets the label, referred to in Android as a TextView.
As in most GUI toolkits, labels are bits of text that can’t be edited directly by users.
Typically, labels are used to identify adjacent widgets (e.g., a “Name:” label next to a field where the
user fills in a name
TextView has numerous other properties of relevance for labels, such as the following
- text: defines the text that would be displayed on the screen.
- textStyle: sets the style of the text. The possible choices are bold, italic and normal.
- fontFamily: specifies the font family for the text.
- typeFace: as you can imagine it defines the typeface for the text. The possible values are normal,
- textSize: defines the size of the text. It is recommended to use sp for the size.
- textColor: sets the color of the text. The color has to be defined in hex encoding or as a
- background: sets the background color of the text. Again the color should be defined in hex
- textColorHighlight: defines the color when the text is marked as highlighted.
- textIsSelectable: indicates whether the text can be selected (true) or not (false). This attribute
- lines: defines the exact height of the TextView in lines.
- clickable: indicates if the view reacts to click events.
- autoLink: identifies the links into the text and converts them into clickable ones. The available
Example 1
Step 1: (activity_main.xml)
sans, serif and monospace.
reference to another resource.
encoding or as a reference to another resource.
can be used in order to allow copy-paste controls.
choices are web, email, phone, map or all of them.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt1"
android:text="Click to text view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:clickable="true"
android:onClick="perform_action"
/>
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.tvexample;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void perform_action(View v)
{
TextView tv= (TextView) findViewById(R.id.txt1);
tv.setText("This text view is clicked");
tv.setTextColor(Color.GREEN);
}
}
Button
attributes and methods of Button
Inherited from android.widget.TextView Class:
Attribute Description
android:autoText If set, specifies that this TextView has a textual input
Inherited from android.view.View Class:
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display.
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the
android:id This supplies an identifier name for this view,
android:onClick This is the name of the method in this View's context
android:visibility This controls the initial visibility of the view.
Example:-
Step 1: (activity_main.xml)
Step 2: (MainActivity.java)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click" />
</LinearLayout>
ppackage com.example.btexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1= (Button) findViewById(R.id.btn1);
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "click to the button",
}
});
}
}
EditText
attributes and methods of EditText
hint: defines the hint text that would be displayed in the edit text. The text can be defined directly
singleLine: sets whether the text is appeared in one line (true) or if it is wrapped into multiple ones
maxLength: specifies the maximum number of characters that the user could put into the text field.
digits: specifies the specific numbers that are accepted to be used.
inputType: declares the type of data that the user can fill in the text field. Some of the possible
or as a reference tovalues/strings.xml resource.
(false).
password: indicates that the input is going to be a password, so the text is hidden to the user.
As we mentioned we can use the components of TextView, where some of them are defined to our
background: sets the background color of the edit text. Again the color should be defined in hex
clickable: indicates if the view reacts to click events.
Also in this example, we used more general components such
Example:-1
Step 1: (activity_main.xml)
choices are textCapWords, email, phone etc, so the input in the text field is adjusted respectively.
For multiple than one choices we should use | character for separation.
Another way to do this, is to set the attribute inputType into textPassword.
example:
encoding or as a reference to another resource.
as layout_width and layout_height or id, which uniquely identifies the respective view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Your Name" />
<EditText
android:id="@+id/et1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text" />
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display" />
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.edittextexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class MainActivity extends Activity
{
EditText e1;
Button b1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.et1);
b1 = (Button) findViewById(R.id.btn1);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String str = e1.getText().toString();
Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG).show();
}
});
}
}
Example:-2
<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" >
<EditText
android:layout_width="fill_parent"
android:layout_height="50dp"
android:id="@+id/editInp"
android:hint="@string/hello_world"
android:singleLine="true"
android:inputType="textCapWords"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/editInp"
android:hint="Numbers from 1-5"
android:background="#ff00ff"
android:id="@+id/editDig"
android:digits="12345" />
<EditText
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/editDig"
android:id="@+id/editPass"
android:hint="Password"
android:password="true" />
<EditText
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/editPass"
android:id="@+id/editPhone"
android:inputType="phone"
android:maxLength="10"
android:clickable="true"
android:hint="Phone" />
<Button
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="@+id/editPhone"
android:id="@+id/displayBtn"
android:text="Display" />
</RelativeLayout>
Step 2: (MainActivity.java)
package com.example.edittextexample;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.graphics.Color;
public class MainActivity extends Activity {
private EditText input, digits, pass, phone;
private Button display;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.editInp);
digits = (EditText) findViewById(R.id.editDig);
pass = (EditText) findViewById(R.id.editPass);
phone = (EditText) findViewById(R.id.editPhone);
phone.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
msg.show();
}
});
display = (Button) findViewById(R.id.displayBtn);
display.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
input.setTextColor(Color.RED);
Toast.makeText(getBaseContext(), displayString,Toast.LENGTH_LONG ).show();
}
});
}
}
Example:3
Event Name:-EditText Event(OnFocusChange)
Step:-1(Activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
<EditText
android:id="@+id/et2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
</LinearLayout>
Step:-2(mainactivity.java)
package com.example.edtexample;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.app.Activity;
public class MainActivity extends Activity implements OnFocusChangeListener
{
EditText et1,et2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=(EditText)findViewById(R.id.et1);
et1.setOnFocusChangeListener(this);
et2=(EditText)findViewById(R.id.et2);
et2.setOnFocusChangeListener(this);
}
public void onFocusChange(View v, boolean arg1) {
// TODO Auto-generated method stub
if (v.getId()== R.id.et1 )
{
}
else if (v.getId()== R.id.et2 )
{
}
}
}
Example:4
Event Name:- EditText Event (Text Changed)
Step:-1(Activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
/>
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
Step:-2(mainactivity.java)
package com.example.edtexample;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements TextWatcher
{
EditText et1;
TextView tv1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=(EditText)findViewById(R.id.et1);
et1.addTextChangedListener(this);
tv1=(TextView)findViewById(R.id.tv1);
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
tv1.setText(et1.getText().toString());
}
}
AutoCompleteTextView
attributes and methods of AutoCompleteTextView
Attribute Description
android:completionHint This defines the hint displayed in the drop
android:completionHintView This defines the hint view displayed in the
android:completionThreshold This defines the number of characters that
android:dropDownAnchor This is the View to anchor the auto-complete
android:dropDownHeight This specifies the basic height of the
android:dropDownHorizontalOffset The amount of pixels by which the drop
android:dropDownSelector This is the selector in a drop down list.
android:dropDownVerticalOffset The amount of pixels by which the drop
android:dropDownWidth This specifies the basic width of the
android:popupBackground This sets the background.
Example:-
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="@+id/act1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.actexample;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class MainActivity extends Activity
{
android:ems="15"
AutoCompleteTextView act1;
String[] s1 = { "Android", "Avd", "Oracle" };
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
act1= (AutoCompleteTextView)findViewById(R.id.act1);
ArrayAdapter ad1 = new ArrayAdapter(this,android.R.layout.select_dialog_item, s1);
act1.setThreshold(1);
act1.setAdapter(ad1);
}
}
ImageButton
attributes and methods of ImageButton
Inherited from
Attribute Description
android:adjustViewBounds Set this to true if you want the ImageView to adjust
android:baseline This is the offset of the baseline within this view.
android:baselineAlignBottom If true, the image view will be baseline aligned with
android:cropToPadding If true, the image will be cropped to fit within its
android:src This sets a drawable as the content of this
Inherited from android.view.View Class:
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the
android:id This supplies an identifier name for this view,
android:onClick This is the name of the method in this View's context
android:visibility This controls the initial visibility of the view.
Example:-
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageButton
android:id="@+id/ib1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
Step 2: (MainActivity.java)
</LinearLayout>
package com.example.ibexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity
{
ImageButton ib1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
private void addListenerOnButton()
{
Ib1 = (ImageButton)findViewById(R.id.ib1);
Ib1.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
}
});
}
}
CheckBox
attributes and methods of CheckBox
Inherited from android.widget.TextView Class:
Attribute Description
android:autoText If set, specifies that this TextView has a textual input
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display.
Inherited from android.view.View Class:
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the
android:id This supplies an identifier name for this view,
android:onClick This is the name of the method in this View's context
android:visibility This controls the initial visibility of the view.
Example:-1
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android" />
<CheckBox
android:id="@+id/chk2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java" />
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.chkexample;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements OnClickListener
{
CheckBox chk1,chk2;
TextView tv1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chk1=(CheckBox)findViewById(R.id.chk1);
chk1.setOnClickListener(this);
chk2=(CheckBox)findViewById(R.id.chk2);
chk2.setOnClickListener(this);
tv1=(TextView)findViewById(R.id.tv1);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
String s1="Your Subject:-\n";
if(chk1.isChecked())
{
}
if(chk2.isChecked())
{
}
tv1.setText(s1);
}
}
Example:-2
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android" />
<CheckBox
android:id="@+id/chk2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java" />
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.checkboxexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends Activity {
CheckBox chk1, chk2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnCheck1();
addListenerOnCheck2();
}
private void addListenerOnCheck1()
{
chk1 = (CheckBox) findViewById(R.id.chk1);
chk2 = (CheckBox) findViewById(R.id.chk2);
chk2.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
StringBuffer s1= new StringBuffer();
S1.append("Advance Java Selection : ").append(chk1.isChecked());
S1.append("\nAndroid Selection : ").append(chk2.isChecked());
Toast.makeText(MainActivity.this, s1.toString(), Toast.LENGTH_LONG).show();
}
});
}
private void addListenerOnCheck2()
{
chk1 = (CheckBox) findViewById(R.id.chk1);
chk2 = (CheckBox) findViewById(R.id.chk2);
chk1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
StringBuffer s1 = new StringBuffer();
S1.append("Advance Java Selection : ").append(chk1.isChecked());
S1.append("\nAndroid Selection : ").append(chk2.isChecked());
}
});
}
}
RadioButton
attributes and methods of RadioButton
Inherited from android.widget.TextView Class:
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display.
Inherited from android.view.View Class:
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view,
android:onClick This is the name of the method in this View's context to invoke
android:visibility This controls the initial visibility of the view.
Example:-
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RadioGroup
android:id="@+id/rg1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/rbm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:checked="true" />
<RadioButton
android:id="@+id/rbf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.rbexample;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.app.Activity;
public class MainActivity extends Activity implements OnCheckedChangeListener
{
RadioGroup rg1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rg1=(RadioGroup)findViewById(R.id.rg1);
rg1.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(RadioGroup arg0, int id)
{
// TODO Auto-generated method stub
if(id==R.id.rbm)
{
}
else if(id==R.id.rbf)
{
}
}
}
ToggleButton
attributes and methods of ToggleButton
Following are the important attributes related to ToggleButton control. You can check Android official
documentation for complete list of attributes and related methods which you can use to change these
attributes are run time.
Attribute Description
android:disabledAlpha This is the alpha to apply to the indicator when disabled.
android:textOff This is the text for the button when it is not checked.
android:textOn This is the text for the button when it is checked.
Inherited from android.widget.TextView Class:
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display.
Inherited from android.view.View Class:
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view,
android:onClick This is the name of the method in this View's context to invoke
android:visibility This controls the initial visibility of the view.
Example:-
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ToggleButton
android:id="@+id/tb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bgtoggle"
android:textOff=""
android:textOn="" />
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
/>
</LinearLayout>
Step 2: (MainActivity.java)
package com.tbexample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends Activity
{
ToggleButton tb1;
TextView tv1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main);
tb1 =(ToggleButton)findViewById(R.id.tb1);
tv1=(TextView)findViewById(R.id.tv1);
tv1.setText("OFF");
tb1.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
});
}
}
Spinner
What is an Android Spinner ?
The spinner is nothing but a label with a dropdown list often seen on web page forms. When the
Syntax
This is the basic syntax used to declare a spinner, but it is incomplete. The spinner values that pop
A spinner has various XML attributes or functionalities:
user clicks this label, the dropdown list appears, and this allows the users to make a selection
based on this list. The “ItemClick” event is triggered when the user makes a selection. The Android
Spinner control is a mobile version of the standard dropdown list used on a website. It’s effective
in input control and makes the developer’s work easier and reduces overhead of complex designs.
The most important feature of the spinner is that it prevents excessive space utilization, which
otherwise would be required to list items.
<Spinner
android:id=”@+id/list”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginTop=”5dp” />
up on the screen for a selection are yet to be defined.
DropDownHorizontalOffset: This attribute runs the setdropDownHorizontalOffset method. It
aligns a dropdown list in a horizontal manner.
DropDownSelector: This shown the dropdown display.
DropDownVerticalOffset: It aligns the dropdown list in a vertical manner.
dropDownWidth: Defines the width of the dropdown list of spinner using
setDropDownWidth() method.
Gravity: Defines the positioning of the selected item using setGravity() method.
popupBackground: Makes the background drawable to be used for a dropdown through
setPopupBackgroundResource() method.
Prompt: Prompts the display when the spinner’s dialog is shown.
SpinnerMode: Display different modes of the spinner options.
Example:-1
Step:-1(String.xml)
<string name="title_activity_main">SpinnerExample</string>
<string name="cp">Choose a country</string>
<string-array name="country_arrays">
<item>United States</item>
<item>Singapore</item>
<item>India</item>
</string-array>
<resources>
</resources>
Step:-2(Activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="@+id/sp1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/country_arrays"
android:prompt="@string/cp" />
</LinearLayout>
Step:-3(mainactivity.java)
package com.example.spexample;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.Toast;
import android.app.Activity;
public class MainActivity extends Activity implements OnItemSelectedListener
{
Spinner sp1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp1 = (Spinner) findViewById(R.id.sp1);
sp1.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> av, View v, int p,long id)
{
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),av.getItemAtPosition(p).toString(),
Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Example:-2(Dynamic Spinner)
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:id="@+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit" />
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.dynamicspinner;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
<Spinner
private Spinner spinner2;
private Button btnSubmit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnSpinner2();
addListenerOnButton();
}
private void addListenerOnButton() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
}
});
}
private void addItemsOnSpinner2() {
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
}
// TODO Auto-generated method stub
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("Rahul");
list.add("Mann");
list.add("Prem");
ArrayAdapter<String> dataAdapter = new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
spinner2.setAdapter(dataAdapter);
Toast:- List & Adapters
Android ListView is a view which groups several items and display them in vertical scrollable list.
The list items are automatically inserted to the list using an Adapter that pulls content from a source
such as an array or database.
An adapter actually bridges between UI components and the data source that fill data into UI
Component.
Adapter can be used to supply the data to like spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can be populated by binding them
to an Adapter, which retrieves data from an external source and creates a View that represents each
data entry.
Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and
building views for an AdapterView ( ie. ListView or GridView). The two most common adapters are
ArrayAdapter and Simple CursorAdapter. We will see separate examples for both the adapters.
ListView Attributes
Following are the important attributes specific to GridView:
Attribute Description
android:id This is the ID which uniquely identifies the layout.
android:divider This is drawable or color to draw between list
android:dividerHeight This specifies height of the divider. This could be
android:entries Specifies the reference to an array resource that
android:footerDividersEnabled When set to false, the ListView will not draw the
android:headerDividersEnabled When set to false, the ListView will not draw the
ArrayAdapter
You can use this adapter when your data source is an array.
By default, ArrayAdapter creates a view for each array item by calling toString() on each item and
placing the contents in a TextView.
Consider you have an array of strings you want to display in a ListView, initialize a
new ArrayAdapter using a constructor to specify the layout for each string and the string array:
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.ListView,StringArray);
Here are arguments for this constructor:
First argument this is the application context. Most of the case, keep it this.
Second argument will be layout defined in XML file and having TextView for each string in the
Final argument is an array of strings which will be populated in the text view.
Once you have array adaptor created, then simply call setAdapter() on your ListView object as
follows:
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
Example:-1
Step 1: (activity_main.xml)
array.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/lv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.lvexample;
import android.os.Bundle;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.app.Activity;
import android.view.View;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String s1[]={"INDIA","USA","UK"};
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, s1);
lv1=(ListView)findViewById(R.id.lv1);
lv1.setAdapter(ad1);
lv1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Toast.makeText(getApplicationContext(),s1[arg2],Toast.
LENGTH_SHORT).show();
}
});
}
}
ListView lv1;
ArrayAdapter<String> ad1= new
DatePicker
Method called onCreateDialog gets automatically called. So we have to override that method too.
Its syntax is given below:
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
In the last step, you have to register the DatePickerDialog listener and override its onDateSet
method. This onDateSet method contains the updated day, month and year. Its syntax is given
below:
private DatePickerDialog.OnDateSetListener myDateListener
= new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// arg1 = year
// arg2 = month
// arg3 = day
}
};
Sr.No Method & description
1 getDayOfMonth()
This method gets the selected day of month
2 getMonth()
This method gets the selected month
3 getYear()
This method gets the selected year
4 setMaxDate(long maxDate)
This method sets the maximal date supported by this DatePicker in
milliseconds since January 1, 1970 00:00:00 in getDefault() time zone
5 setMinDate(long minDate)
This method sets the minimal date supported by this NumberPicker in
milliseconds since January 1, 1970 00:00:00 in getDefault() time zone
6 setSpinnersShown(boolean shown)
This method sets whether the spinners are shown
7 updateDate(int year, int month, int dayOfMonth)
This method updates the current date
Example:-1
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<DatePicker
android:id="@+id/dp1"
android:layout_width=" wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt1"
android:layout_width=" wrap_content"
android:layout_height="wrap_content"
android:onClick="perform"
android:text="Select this date" />
Step 2: (MainActivity.java)
</LinearLayout>
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Toast;
public class MainActivity extends Activity
{
DatePicker dp1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dp1 = (DatePicker) findViewById(R.id.dp1);
}
public void perform(View v)
{
int d = dp1.getDayOfMonth();
int m = dp1.getMonth();
int y = dp1.getYear();
m=m+1;
Toast.makeText(this, d +"/"+ m +"/"+ y, Toast.LENGTH_SHORT).show();
}
}
Time Picker
Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode. The time
consists of hours, minutes and clock format. Android provides this functionality through TimePicker
class.
In order to use TimePicker class, you have to first define the TimePicker component in your activity.xml.
It is define as below:
<TimePicker
android:id="@+id/tp1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
After that you have to create an object of TimePicker class and get a reference of the above defined xml
component. Its syntax is given below.
import android.widget.TimePicker;
private TimePicker timePicker1;
tp1 = (TimePicker) findViewById(R.id.tp1);
In order to get the time selected by the user on the screen, you will use getCurrentHour() and
getCurrentMinute() method of the TimePicker Class. Their syntax is given below.
int hour = timePicker1.getCurrentHour();
int min = timePicker1.getCurrentMinute();
Apart form these methods , there are other methods in the API that gives more control over TimePicker
Component. They are listed below.
Sr.No Method & description
1 is24HourView()
This method returns true if this is in 24 hour view else false
2 isEnabled()
This method returns the enabled status for this view
3 setCurrentHour(Integer currentHour)
This method sets the current hour
4 setCurrentMinute(Integer currentMinute)
This method sets the current minute
5 setEnabled(boolean enabled)
This method set the enabled state of this view
6 setIs24HourView(Boolean is24HourView)
This method set whether in 24 hour or AM/PM mode
7 setOnTimeChangedListener(TimePicker.OnTimeChangedListener
onTimeChangedListener)
This method Set the callback that indicates the time has been adjusted by
the user
Example
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TimePicker
android:id="@+id/tp1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="settime"
android:text="DisplayTime" />
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.timepickerexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.TimePicker;
public class MainActivity extends Activity
{
TimePicker tp1;
String f = "";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tp1=(TimePicker) findViewById(R.id.tp1);
}
public void settime(View v)
{
int h = tp1.getCurrentHour();
int m = tp1.getCurrentMinute();
showTime(h, m);
}
private void showTime(int h, int m)
{
h += 12;
f = "AM";
}
f = "PM";
}
h -= 12;
f = "PM";
}
f = "AM";
}
}
}
Android Progress Bar using ProgressDialog
Progress bars are used to show progress of a task. For example, when you are uploading or
downloading something from the internet, it is better to show the progress of download/upload to the
user.
In android there is a class called ProgressDialog that allows you to create progress bar. In order to do
this, you need to instantiate an object of this class. Its syntax is.
Now you can set some properties of this dialog. Such as, its style, its text etc.
progress.setMessage("Downloading Movie :) ");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(true);
Apart from these methods, there are other methods that are provided by the ProgressDialog class
Sr. No Title and description
1 getMax()
ProgressDialog progress = new ProgressDialog(this);
This method returns the maximum value of the progress.
2 incrementProgressBy(int diff)
This method increments the progress bar by the difference of value passed as a parameter.
3 setIndeterminate(boolean indeterminate)
This method sets the progress indicator as determinate or indeterminate.
4 setMax(int max)
This method sets the maximum value of the progress dialog.
5 setProgress(int value)
This method is used to update the progress dialog with some specific value.
6 show(Context context, CharSequence title, CharSequence message)
This is a static method, used to display progress dialog.
Example:-1
Step 1: (activity_main.xml)
Step 2: (MainActivity.java)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
package com.example.pdexample;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
public class MainActivity extends Activity
{
ProgressDialog pd1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showProgressbar();
}
private void showProgressabar()
{
// TODO Auto-generated method stub
pd1=new ProgressDialog(this);
pd1.setCancelable(true);
pd1.setMessage("Movie Download");
pd1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd1.setProgress(0);
pd1.setMax(100);
pd1.show();
}
}
Example:-2
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/pb1"
android:layout_width="216dp"
android:layout_height="wrap_content"
android:max="100"
android:minHeight="50dp"
android:minWidth="200dp"
android:progress="1"
style="?android:attr/progressBarStyleHorizontal"/>
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.lvexample;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity
{
ProgressBar pb1;
int s = 0;
TextView tv1;
Handler h = new Handler();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb1 = (ProgressBar) findViewById(R.id.pb1);
tv1 = (TextView) findViewById(R.id.tv1);
// Start long running operation in a background thread
new Thread(new Runnable()
{
}).start();
}
}
What is AlertDialog Box
Android Alert dialog is used in many android applications. This dialog displays alerts to the users and
is used to get confirmation from the users. An Alert dialog has three parts.
Title: Note that title is optional.
Content: This displays the message to the user. It can be a string message or a list or custom
Action Button(s): This button is of three types. They are Positive, Negative and Neutral action
layout.
buttons. An alert dialog can have maximum three action buttons. If you want the user to accept
the action, use Positive action button. It is normally displayed as OK/YES. If the user wants to
cancel the action , then you can use Negative action button (NO). If the user wants to postpone
the decison use Neutral action button (Later).
Methods used to add an Alert dialog
To add action button to the Alert dialog, the you have to use the following methods.
setPositiveButton (CharSequence text, DialogInterface.OnClickListener listener): The first
argument is the text to be displayed. The second argument is the listener to be invoked when the
positive button is pressed.
setNegativeButton (CharSequence text, DialogInterface.OnClickListener listener): The arguments
are the same as the setPositiveButton method. However, the second argument is applicable when
the negative button is pressed.
setNeutralButton (CharSequence text, DialogInterface.OnClickListener listener): The arguments
are same as the SetPositiveButton method.
You may also want to check out this course to help understand Android dialog boxes better.
Code to build an AlertDialog Object
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);
AlertDialog dialog = builder.create();
The first line creates an AlertDialog.builder object and then its constructor is called. The second
line sets the message and the dialog of the object. Finally, we use the create function to create an
AlertDialog box.
AlertDialog Class
In order to create the Alert dialog, you can use the AlertDialog.Builder class. The AlertDialog class
is a subclass of the Dialog class. It is used to display one, two or three buttons.
Important functions of the AlertDialog class
AlertDialog(Context context)- Here Context refers to the application environment.
getButton(int whichButton)- The whichButton stands for the identifier of the button. This
function will return one of the buttons used in the dialog. It will return null if the button
doesn’t exist.
getListView()- Use this function to get the list view used in the dialog.
setButton(int whichButton, CharSequence text, DialogInterface.OnClickListener listener)- Use
setButton(int whichButton, CharSequence text, Message msg)-This function defines the
setIcon(int resId)-This function is called with resId set to 0 if you don’t want to display an icon.
setMessage(CharSequence message)- Use this function to display a string in the dialog box.
setTitle (CharSequence title)- Use this method to add title to the dialog box.
Example:-1
Program to Create Android Alert Dialog with One Button
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/bt1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Show Alert" />
this function when you want a listener to be invoked when the positive button is selected.
message to be sent when a button is pressed.
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.chkexample;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button)findViewById(R.id.bt1);
bt1.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
AlertDialog ad1= new AlertDialog.Builder(MainActivity.this).create();
ad1.setTitle("Alert Dialog");
ad1.setMessage("Welcome to Android Alert Dialog ");
ad1.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getBaseContext(),"You clicked on OK",
Toast.LENGTH_SHORT).show();
}
});
ad1.show();
}
});
}
Example:-2(Two Button Alertdialog Box)
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
Button bt1;
@Override
{
}
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Show Alert With Two Button" />
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.AlertDialogexample;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
private Button b1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
private void addListenerOnButton()
{
b1 = (Button)findViewById(R.id.btnone);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
alertDialog.setTitle("Confirm Delete...");
alertDialog.setMessage("Are you sure you want delete this?");
alertDialog.setIcon(R.drawable.delete);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
});
}
Example:-3(Three Button to AlertDialog Box)
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Show Alert With Three Button" />
</LinearLayout>
Step 2: (MainActivity.java)
package com.example.AlertDialogexample;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
}
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity
{
private Button b1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
private void addListenerOnButton()
{
b1 = (Button)findViewById(R.id.btnone);
b1.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
alertDialog.setTitle("Save File...");
alertDialog.setMessage("Do you want to save this file?");
alertDialog.setIcon(R.drawable.save);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
}
});
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});
{
public void onClick(DialogInterface dialog, int which)
{
alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener()
}
});
alertDialog.show();
}
});
}
}
Menu
Android provides the following three type of menus:
Options menu
Context menu
Popup menu
Each of these menu have different usage and have different work flow as shown in the table below.
Options Menu X X X
Context Menu – Floating X X
Context Menu – Action Mode X X X X
Popup Menu X
Initialize a Menu
From the view of user program, operation to a menu is done by the Menu interface. In the initial
The most common way is to use a MenuInflater to inflate menu from a XML menu resource
callback, we can call corresponding method of the interface to do the initial job.
definition.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
The hierarchy of menu can be well defined with the <item> and <menu> xml notion.
A menu item is defined in <item>, and we can set properties such as title, id and icon for each menu
item. A submenu is a menu that included inside a .
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_item1" android:title="@string/menu_item1"/ >
<item android:id="@+id/menu_item2" android:title="@string/menu_item2" >
<!-- "file" submenu -->
<menu>
<item android:id="@+id/sub_menu_item1"
android:title="@string/sub_menu_item1" />
<item android:id="@+id/sub_menu_item2"
android:title="@string/sub_menu_item2" />
</menu>
</item>
</menu>
In the above example, please note that the title property should be referred to a predefined string
resource. For the id property, the “+” can be used to create a new id resource.
Action for the selection event
The following is a sample code snippet for the menu item action:
// Handle item selection
switch (item.getItemId())
{
case R.id. menu_item1:
//act for menu_item1
return true;
case R.id. sub_menu_item1:
//act for sub_menu_item1
return true;
default:
//pass the event to parent, for options menu, use below
return super.onOptionsItemSelected(item);
}
Options Menu
For Android 2.3.x (API level 10) or lower, the options menu will be shown in the bottom of screen
with a 2×3 grid layout, on the press of Menu button. For Android 3.0 (API level 11) and higher, the
menu is placed in the action bar, and will be expanded when clicked. When using ADT, the options
menu will be created by default for activity.
Initialize the Menu
This callback is used for initialization purpose, which will only be called once when the menu is
shown for the first time.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Update the Menu
After the initialization, modification should be done in onPrepareOptionsMenu callback, in
On Android 2.3.x and lower, the callback is always called before showing the option menu to
which we can add/remove/modify the menu according to the working status of the program.
user. On Android 3.0 or higher, the invalidateOptionsMenu() should be called so as to trigger the
onPerpareOptionsMenu().
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Do the enable/disable/modification here
return super.onPrepareOptionsMenu(menu);
}
Context Menu
Context Menu is used when the content is contextually related to the place/view where a menu is
triggered.
Android provides the following two kinds of context menu:
Floating context menu – This is displayed next to a view when it is long pressed
Action mode context menu – This shows an action bar when the view is long pressed. In action
Floating Context Menu
Declare Context Menu Provider
For the view that registers as context menu provider, OS will trigger the context menu sequence
Registration for the context menu should be done by calling Activity.registerForContextMenu()
bar mode, it is also possible to select multiple items to do a batch operation.
Initialize the Menu
when long-lick event of the view is received.
with the view instance as argument.
public void registerForContextMenu(View view) {
view.setOnCreateContextMenuListener(this);
}
The callback function of menu initial is onCreateContextMenu.
Additionally, there is a View instance passed to it, which can be used to determinate the
content of menu according to different views.
Floating context menu does not have an update callback function, which means we should
inflate/initial the menu every time. So, when the context menu contains too much items, an
attention of lag should be paid.
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfomenuInfo) {
//Do the initial here
super.onCreateContextMenu(menu, v, menuInfo);
}
Action for a selection event
Similar to options menu, floating contextual menu has a callback function of click event, the
onContextItemSelected.
@Override
public boolean onContextItemSelected(MenuItem item) {
// Do the action by id here
return super.onContextItemSelected(item);
}
Popup Menu
Popup menu is a menu that anchors to a view. Be different with other menus described above,
PopupMenu is a class belongs to the Widget package, and user program can initial and show a
popup menu on the action of any event.
Initialize and display popup menu
A typical popup initialization can be done as shown in the following code-snippet.
PopupMenu popup = new PopupMenu(this, view);
getMenuInflater().inflate(R.menu.main, popup.getMenu());
popup.show();
Action for selected event
Popup menu item click event will be pass to onMenuItemClick() if the anchor view implements
Otherwise, a listener handle should be registered by the call of
the PopupMenu.OnMenuItemClickListener.
@Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
PopupMenu.setOnMenuItemClickListerner();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
return false;
}
});
Example:-1
Step:-1(Resmenuactivitiy_main)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_save"
android:title="Save" />
<item android:id="@+id/menu_search"
android:title="Search" />
</menu>
Step 2: (MainActivity.java)
package com.example.chkexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_save:
Toast.makeText(getBaseContext(),"Bookmark is Selected", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_search:
Toast.makeText(getBaseContext(), "Search is Selected", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Android Option Menu
Android Option Menus are the primary menus of android. They can be used for settings, search, delete
item etc.
Here, we are going to see two examples of option menus. First, the simple option menus and second,
options menus with images.
Here, we are inflating the menu by calling the inflate() method of MenuInflater class. To perform event
handling on menu items, you need to override onOptionsItemSelected() method of Activity class.
Android Option Menu Example
Step:-1(res/layout/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:id="@+id/main_layout">
</RelativeLayout>
Step:-2(res/Menu/activity_main.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/redcolor"
android:title="RED"/>
<item android:id="@+id/bluecolor"
android:title="BLUE"/>
<item android:id="@+id/greencolor"
android:title="GREEN"/>
</menu>
Step:-3(Mainactivity.java)
package com.example.menuexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.graphics.Color;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rl = (RelativeLayout) findViewById(R.id.main_layout);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);//Menu Resource, Menu
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.redcolor:
rl.setBackgroundColor(Color.RED);
return true;
case R.id.bluecolor:
rl.setBackgroundColor(Color.BLUE);
return true;
case R.id.greencolor:
rl.setBackgroundColor(Color.GREEN);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
RelativeLayout rl;
Android Context Menu Example
Android context menu appears when user press long click on the element. It is also known as floating
menu.
It doesn't support item shortcuts and icons.
Android Context Menu Example
Step:-1(res/layout/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:id="@+id/main_layout">
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Step:-2(Mainactivity.java)
package com.example.menuexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ListView l1;
String contacts[]={"Rahul","Ravi","Ajit"};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l1=(ListView)findViewById(R.id.listView1);
ArrayAdapter<String> adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contacts);
l1.setAdapter(adapter);
// Register the ListView for Context menu
registerForContextMenu(l1);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select The Action");
menu.add(0, v.getId(), 0, "Call");//groupId, itemId, order, title
menu.add(0, v.getId(), 0, "SMS");
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
if(item.getTitle()=="Call")
{
Toast.makeText(getApplicationContext(),"calling
code",Toast.LENGTH_LONG).show();
}
else if(item.getTitle()=="SMS")
{
Toast.makeText(getApplicationContext(),"sending sms
code",Toast.LENGTH_LONG).show();
}
else
{
return false;
}
return true;
}
}
Android Popup Menu Example
Android Popup Menu displays the menu below the anchor text if space is available otherwise above the
anchor text. It disappears if you click outside the popup menu.
The android.widget.PopupMenu is the direct subclass of java.lang.Object class.
Android Popup Menu Example
Step:-1(res/layout/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:id="@+id/main_layout">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Popup" />
</RelativeLayout>
Step:-2(res/Menu/activity_main.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/one"
android:title="One"/>
<item
android:id="@+id/two"
android:title="Two"/>
<item
android:id="@+id/three"
android:title="Three"/>
</menu>
Step:-3(Mainactivity.java)
package com.example.popupmenu;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
public class MainActivity extends Activity {
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item)
{
Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();
return true;
}
});
popup.show();
}
});
}
}
Intent And Intent Filter
What is Intent?
Intents are system messages, running around the inside of the device, notifying applications of
An Android Intent is an object carrying an intent ie. message from one component to another
The intents can communicate messages among any of the three core components of an application -
The intent itself, an Intent object, is a passive data structure holding an abstract description of an
For example, let's assume that you have an Activity that needs to launch an email client and sends
There are separate mechanisms for delivering intents to each type of component - activities,
various events, from hardware state changes (e.g.,an SD card was inserted), to incoming data
(e.g., an SMS message arrived),to application events (e.g., your activity was launched from the
device’s main menu).
component with-in the application or outside the application.
activities, services, and broadcast receivers.
operation to be performed.
an email using your Android device. For this purpose, your Activity would send an ACTION_SEND
along with appropriate chooser, to the Android Intent Resolver. The specified chooser gives the
proper interface for the user to pick how to send your email data.
services, and broadcast receivers.
S.N. Method & Description
1 Context.startActivity()
The Intent object is passed to this method to launch a new activity or get an
existing activity to do something new.
2 Context.startService()
The Intent object is passed to this method to initiate a service or deliver new
instructions to an ongoing service.
3 Context.sendBroadcast()
The Intent object is passed to this method to deliver the message to all
interested broadcast receivers.
Intent Objects
An Intent object is a bundle of information which is used by the component that receives the intent
plus information used by the Android system.
An Intent object can contain the following components based on what it is communicating or going
to perform:
ACTION
This is mandatory part of the Intent object and is a string naming the action to be performed —
or, in the case of broadcast intents, the action that took place and is being reported.
The action largely determines how the rest of the intent object is structured . The Intent class
defines a number of action constants corresponding to different intents. Here is a list of Android
Intent Standard Actions
The action in an Intent object can be set by the setAction() method and read by getAction().
DATA
The URI of the data to be acted on and the MIME type of that data. For example, if the action
field is ACTION_EDIT, the data field would contain the URI of the document to be displayed for
editing.
The setData() method specifies data only as a URI, setType() specifies it only as a MIME type, and
setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and
the type by getType().
Some examples of action/data pairs are:
S.N. Action/Data Pair & Description
1 ACTION_VIEW content://contacts/people/1
Display information about the person whose identifier is "1".
2 ACTION_DIAL content://contacts/people/1
Display the phone dialer with the person filled in.
3 ACTION_VIEW tel:123
Display the phone dialer with the given number filled in.
4 ACTION_DIAL tel:123
Display the phone dialer with the given number filled in.
5 ACTION_EDIT content://contacts/people/1
Edit information about the person whose identifier is "1".
6 ACTION_VIEW content://contacts/people/
Display a list of people, which the user can browse through.
CATEGORY
The category is an optional part of Intent object and it's a string containing additional
information about the kind of component that should handle the intent. The addCategory()
method places a category in an Intent object, removeCategory() deletes a category previously
added, and getCategories() gets the set of all categories currently in the object. Here is a list
of Android Intent Standard Categories.
You can check detail on Intent Filters in below section to understand how do we use categories
to choose appropriate acivity coressponding to an Intent.
EXTRAS
This will be in key-value pairs for additional information that should be delivered to the
component handling the intent. The extras can be set and read using the putExtras() and
getExtras() methods respectively. Here is a list of Android Intent Standard Extra Data
FLAGS
These flags are optional part of Intent object and instruct the Android system how to launch an
COMPONENT NAME
This optional field is an android ComponentName object representing either Activity, Service or
activity, and how to treat it after it's launched etc.
The component name is set by setComponent(), setClass(), or setClassName() and read by
Types of Intents
There are following two types of intents supported by Android till version 4.1
EXPLICIT INTENTS
These intents designate the target component by its name and they are typically used for
BroadcastReceiver class. If it is set, the Intent object is delivered to an instance of the designated
class otherwise Android uses other information in the Intent object to locate a suitable target.
getComponent().
For example:
application-internal messages - such as an activity starting a subordinate service or launching a
sister activity.
// Explicit Intent by specifying its class name
Intent i = new Intent(this, TargetActivity.class);
i.putExtra("Key1", "ABC");
i.putExtra("Key2", "123");
// Starts TargetActivity
startActivity(i);
IMPLICIT INTENTS
These intents do not name a target and the field for the component name is left blank. Implicit
For example:
The target component which receives the intent can use the getExtras() method to get the extra
For example:
intents are often used to activate components in other applications.
// Implicit Intent by specifying a URI
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.example.com"));
// Starts Implicit Activity
startActivity(i);
data sent by the source component.
// Get bundle object at appropriate place in your code
Bundle extras = getIntent().getExtras();
// Extract data using passed keys
String value1 = extras.getString("Key1");
String value2 = extras.getString("Key2");
Example:-
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enter your name"
/>
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
/>
<Button
android:id="@+id/bt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take me to next screen" />
</LinearLayout>
Step 2: (second.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/tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Step 3: (MainActivity.java)
package com.example.intentexamplenew;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity
{
EditText et1;
Button bt1;
String s1;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.et1);
bt1 = (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
}
});
}
}
Step 4: (SecondActivity.java)
package com.example.intentexamplenew;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.TextView;
public class GreetingActivity extends Activity
{
TextView tv2;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tv2 = (TextView) findViewById(R.id.tv2);
Intent i2 = getIntent();
String s2 = (String) i2.getSerializableExtra("uname");
t1.setText("Welcome " + s2);
}
}
Step 4: (AndroidManifest.xml)
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.intentexamplenew"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:label="@string/app_name" >
</activity>
</application>
</manifest>
Basic operation of SQLite Database
SQLite is an open-source relational database i.e. used to perform database operations on android
devices such as storing, manipulating or retrieving persistent data from the database.
It is embedded in android by default. So, there is no need to perform any database setup or
administration task.
Here, we are going to see the example of sqlite to store and fetch the data.
Data is displayed in the logcat.
SQLiteOpenHelper class provides the functionality to use the SQLite database.
SQLiteOpenHelper class
The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version
management. For performing any database operation, you have to provide the implementation of
onCreate() and onUpgrade() methods of SQLiteOpenHelper class.
Constructors of SQLiteOpenHelper class
There are two constructors of SQLiteOpenHelper class.
SQLiteOpenHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version)
SQLiteOpenHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version,
DatabaseErrorHandler errorHandler)
Methods of SQLiteOpenHelper class
There are many methods in SQLiteOpenHelper class. Some of them are as follows:
public abstract void onCreate(SQLiteDatabase db) called only once when database is
public abstract void onUpgrade(SQLiteDatabase db,
int oldVersion, int newVersion)
public synchronized void close () closes the database object.
public void onDowngrade(SQLiteDatabase db, int
oldVersion, int newVersion)
Methods of SQLiteDatabase class
There are many methods in SQLiteDatabase class. Some of them are as follows:
void execSQL(String sql) executes the sql query not select query.
Method Description
long insert(String table,
String nullColumnHack,
ContentValues values)
int update(String table,
ContentValues values, String
whereClause, String[]
whereArgs)
Cursor query(String table,
String[] columns, String
selection, String[]
selectionArgs, String
groupBy, String having,
String orderBy)
Database – Package
The main package is android.database.sqlite that contains the classes to manage your own
databases
Database – Creation
In order to create a database you just need to call this method openOrCreateDatabase with your
database name and mode as a parameter.
It returns an instance of SQLite database which you have to recieve in your own object.
Its syntax is given below
name",MODE_PRIVATE,null);
Apart from this , there are other functions availaible in the databsae package , that does this job.
They are listed below
Sr.No Method & Description
1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,
SQLiteDatabse mydatabase = openOrCreateDatabase("your database
2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
3 openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
DatabaseErrorHandler errorHandler)
This method only opens the existing database with the appropriate flag mode. The common
flags mode could be OPEN_READWRITE OPEN_READONLY
It is similar to the above method as it also opens the exisiting database but it does not define
any handler to handle the errors of databases
It not only opens but create the datbase if it not exists. This method is equivalent to
openDatabase method
4 openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
This method is similar to above method but it takes the File object as a path rather then a
string. It is equavilent to file.getPath()
Database – Insertion
we can create table or insert data into table using execSQL method defined in SQLiteDatabase class.
Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS test(Username VARCHAR,Password
VARCHAR);");
mydatabase.execSQL("INSERT INTO test VALUES('admin','admin');");
This will insert some values into our table in our database. Another method that also does the same
job but take some additional parameter is given below
Sr.No Method & Description
1 execSQL(String sql, Object[] bindArgs)
This method not only insert data , but also used to update or modify already existing data in
database using bind arguments
Database – Fetching
We can retrieve anything from datbase using an object of the Cursor class. We will call a method of
this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can
move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from test",null);
resultSet.moveToFirst();
String username = resultSet.getString(1);
String password = resultSet.getString(2);
There are other functions availaible in the Cursor class that allows us to effectively retrieve the data.
That includes
Sr.No Method & Description
1 getColumnCount()
2 getColumnIndex(String columnName)
3 getColumnName(int columnIndex)
4 getColumnNames()
5 getCount()
6 getPosition()
This method return the total number of columns of the table.
This method returns the index number of a column by specifying the name of the column
This method returns the name of the column by specifying the index of the column
This method returns the array of all the column names of the table.
This method returns the total number of rows in the cursor
7 isClosed()
Datbase - Helper class
For managing all the operations related to the datbase , an helper class has been given and is called
This method returns the current position of the cursor in the table
This method returns true if the cursor is closed and return false otherwise
SQLiteOpenHelper. It automatically manages the creation and updation of the datbase. Its syntax is
given below
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) {}
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}
}
Example 1: Using Helper Class File
Simple SQLite Database Tutorial
Step:1 (Book.java)
package com.example.sqlliteexample;
public class Book
{
private int id;
private String title;
private String author;
public Book()
{
}
public Book(String title,String author)
{
super();
this.title=title;
this.author=author;
}
@Override
public String toString()
{
return "Book [id=" + id +",title=" + title + ", author=" + author + "]";
}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
}
public void setTitle(String title)
{
}
public String getTitle()
{
}
public void setAuthor(String author)
{
}
public String getAuthor()
{
}
}
return this.id;
this.title=title;
return this.title;
this.author=author;
return this.author;
Step:2
extends SQLiteOpenHelper
This is the main step.
Create a new class MySQLiteHelper extends SQLiteOpenHelper.
MySQLiteHelper constructor must call the super class constructor.
Override onCreate() method to create the table(s)
Override onUpgrade() to drop old tables and create new ones.
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "BookDB";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, "+
"author TEXT )";
// create books table
db.execSQL(CREATE_BOOK_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older books table if existed
db.execSQL("DROP TABLE IF EXISTS books");
// create fresh books table
this.onCreate(db);
}
}
Add, Get, Update & Delete a Book
In the same file “MySQLiteHelper.java” we will add 5 methods
addBook(Book book)
getBook(int id)
getAllBooks()
update(Book book)
delete(Book book)
Some static constants
Define static constants for table & columns names;
// Books table name
private static final String TABLE_BOOKS = "books";
// Books Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_AUTHOR = "author";
private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};
addBook(Book book)
public void addBook(Book book){
//for logging
Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TITLE, book.getTitle()); // get title
values.put(KEY_AUTHOR, book.getAuthor()); // get author
// 3. insert
db.insert(TABLE_BOOKS, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
getBook(int id)
public Book getBook(int id){
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_BOOKS, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
Book book = new Book();
book.setId(Integer.parseInt(cursor.getString(0)));
book.setTitle(cursor.getString(1));
book.setAuthor(cursor.getString(2));
//log
Log.d("getBook("+id+")", book.toString());
// 5. return book
return book;
}
getAllBooks()
public List<Book> getAllBooks() {
List<Book> books = new LinkedList<Book>();
// 1. build the query
String query = "SELECT * FROM " + TABLE_BOOKS;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each row, build book and add it to list
Book book = null;
if (cursor.moveToFirst()) {
do {
book = new Book();
book.setId(Integer.parseInt(cursor.getString(0)));
book.setTitle(cursor.getString(1));
book.setAuthor(cursor.getString(2));
// Add book to books
books.add(book);
} while (cursor.moveToNext());
}
Log.d("getAllBooks()", books.toString());
// return books
return books;
}
update(Book book)
public int updateBook(Book book) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("title", book.getTitle()); // get title
values.put("author", book.getAuthor()); // get author
// 3. updating row
int i = db.update(TABLE_BOOKS, //table
values, // column/value
KEY_ID+" = ?", // selections
new String[] { String.valueOf(book.getId()) }); //selection args
// 4. close
db.close();
return i;
}
delete(Book book)
public void deleteBook(Book book) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_BOOKS, //table name
KEY_ID+" = ?", // selections
new String[] { String.valueOf(book.getId()) }); //selections args
// 3. close
db.close();
//log
Log.d("deleteBook", book.toString());
}
Step:3(Complete MySQLiteHelper.java Code)
package com.example.sqlliteexample;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION=1;
private static final String DATABASE_NAME="BookDB";
public MySQLiteHelper(Context context)
super(context, DATABASE_NAME,null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_BOOK_TABLE = "CREATE TABLE books ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, "+
"author TEXT )";
// create books table
db.execSQL(CREATE_BOOK_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS books");
// create fresh books table
this.onCreate(db);
//---------------------------------------------------------------------
/**
CRUD operations (create "add", read "get", update, delete) book + get all books +
delete all books
*/
// Books table name
private static final String TABLE_BOOKS = "books";
// Books Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_AUTHOR = "author";
private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR};
public void addBook(Book book){
Log.d("addBook", book.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_TITLE, book.getTitle()); // get title
values.put(KEY_AUTHOR, book.getAuthor()); // get author
// 3. insert
db.insert(TABLE_BOOKS, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
public Book getBook(int id){
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_BOOKS, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
Book book = new Book();
book.setId(Integer.parseInt(cursor.getString(0)));
book.setTitle(cursor.getString(1));
book.setAuthor(cursor.getString(2));
Log.d("getBook("+id+")", book.toString());
// 5. return book
return book;
}
// Get All Books
public List<Book> getAllBooks() {
List<Book> books = new LinkedList<Book>();
// 1. build the query
String query = "SELECT * FROM " + TABLE_BOOKS;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each row, build book and add it to list
Book book = null;
if (cursor.moveToFirst()) {
do {
book = new Book();
book.setId(Integer.parseInt(cursor.getString(0)));
book.setTitle(cursor.getString(1));
book.setAuthor(cursor.getString(2));
// Add book to books
books.add(book);
} while (cursor.moveToNext());
}
Log.d("getAllBooks()", books.toString());
// return books
return books;
}
// Updating single book
public int updateBook(Book book) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("title", book.getTitle()); // get title
values.put("author", book.getAuthor()); // get author
// 3. updating row
int i = db.update(TABLE_BOOKS, //table
values, // column/value
KEY_ID+" = ?", // selections
new String[] { String.valueOf(book.getId()) }); //selection args
// 4. close
db.close();
return i;
}
// Deleting single book
public void deleteBook(Book book) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_BOOKS,
KEY_ID+" = ?",
new String[] { String.valueOf(book.getId()) });
// 3. close
db.close();
Log.d("deleteBook", book.toString());
}
}
Step:4 (MainActivity.java)
package com.example.sqlliteexample;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MySQLiteHelper db = new MySQLiteHelper(this);
/**
* CRUD Operations
* */
// add Books
db.addBook(new Book("Java", "Ravi"));
db.addBook(new Book("Android", "Rahul"));
db.addBook(new Book("PHP", "Pratik"));
// get all books
List<Book> list = db.getAllBooks();
// delete one book
db.deleteBook(list.get(0));
// get all books
db.getAllBooks();
}
}
Example:2(Note:- SQLite Example Not Create MySQLiteHelper.java file)
Step:1 (String.xml)
<resources>
<string name="app_name">sqlex</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="roll_no">Enter Rollno: </string>
<string name="name">Enter Name: </string>
<string name="marks">Enter Marks: </string>
<string name="add">Add</string>
<string name="delete">Delete</string>
<string name="modify">Modify</string>
<string name="view">View</string>
<string name="view_all">View All</string>
<string name="show_info">Show Information</string>
<string name="title">Student Details</string>
</resources>
Step:2 (activity_main.xml)
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayout"
android:stretchColumns="0"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="@string/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:text="@string/roll_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="@+id/editRollno"
android:layout_width="150dp"
android:layout_height="40dp"/>
<TextView android:text="@string/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="@+id/editName"
android:layout_width="150dp"
android:layout_height="40dp"/>
<TextView android:text="@string/marks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="@+id/editMarks"
android:layout_width="150dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnAdd"
android:layout_width="100dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnDelete"
android:layout_width="100dp"
android:layout_height="40dp"/>n
<Button android:id="@+id/btnModify"
android:layout_width="100dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnView"
android:layout_width="100dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnViewAll"
android:layout_width="100dp"
android:layout_height="40dp"/>
<Button
android:id="@+id/btnShowInfo"
android:layout_width="186dp"
android:layout_height="wrap_content"
android:layout_x="80dp"
android:layout_y="352dp"
android:text="@string/show_info" />
</AbsoluteLayout>
Step:3 (MainActivity.java)
package com.example.sqlex;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener
{
EditText editRollno,editName,editMarks;
Button btnAdd,btnDelete,btnModify,btnView,btnViewAll,btnShowInfo;
SQLiteDatabase db;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editRollno=(EditText)findViewById(R.id.editRollno);
editName=(EditText)findViewById(R.id.editName);
editMarks=(EditText)findViewById(R.id.editMarks);
btnAdd=(Button)findViewById(R.id.btnAdd);
btnDelete=(Button)findViewById(R.id.btnDelete);
btnModify=(Button)findViewById(R.id.btnModify);
btnView=(Button)findViewById(R.id.btnView);
btnViewAll=(Button)findViewById(R.id.btnViewAll);
btnShowInfo=(Button)findViewById(R.id.btnShowInfo);
btnAdd.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnModify.setOnClickListener(this);
btnView.setOnClickListener(this);
btnViewAll.setOnClickListener(this);
btnShowInfo.setOnClickListener(this);
db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks
VARCHAR);");
}
public void onClick(View view)
{
if(view==btnAdd)
{
if(editRollno.getText().toString().trim().length()==0||
editName.getText().toString().trim().length()==0||
editMarks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student
VALUES('"+editRollno.getText()+"','"+editName.getText()+
"','"+editMarks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
if(view==btnDelete)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE rollno='"+editRollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
if(view==btnModify)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("UPDATE student SET
name='"+editName.getText()+"',marks='"+editMarks.getText()+
"' WHERE rollno='"+editRollno.getText()+"'");
showMessage("Success", "Record Modified");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
if(view==btnView)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
editName.setText(c.getString(1));
editMarks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
if(view==btnViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
if(view==btnShowInfo)
{
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
showMessage("Student Management Application", "Developed By Rahul Patel");
}
public void clearText()
{
editRollno.setText("");
editName.setText("");
editMarks.setText("");
editRollno.requestFocus();
}
}
Example:- Create spinner with strings taken from resource folder(res >> value folder). On changing
spinner value, change background of screen.
Step:-1(String.xml)
<resources>
<string name="app_name">ChangeColor</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
<string name="color_prompt">Choose a Color</string>
<string-array name="color_arrays">
<item>Red</item>
<item>Blue</item>
<item>Green</item>
</string-array>
</resources>
Step:-2(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:id="@+id/main_layout">
<Spinner
android:id="@+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/color_arrays"
android:prompt="@string/color_prompt"
/>
</RelativeLayout>
Step:-3(MainActivity.java)
package com.example.changecolor;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.app.Activity;
import android.graphics.Color;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
public class MainActivity extends Activity implements OnItemSelectedListener
{
Spinner spin;
RelativeLayout rl;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spin=(Spinner) findViewById(R.id.spinner1);
rl = (RelativeLayout) findViewById(R.id.main_layout);
spin.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView arg0, View arg1, int arg2,long arg3)
{
// TODO Auto-generated method stub
String name=spin.getSelectedItem().toString();
if(name.equals("Red"))
rl.setBackgroundColor(Color.RED);
else if(name.equals("Blue"))
rl.setBackgroundColor(Color.BLUE);
else if(name.equals("Green"))
rl.setBackgroundColor(Color.GREEN);
}
public void onNothingSelected(AdapterView arg0)
{
// TODO Auto-generated method stub
}
}
Extra Example
Example 1: Addition Of two Number
Step 1: (activity_main.xml)
< LinearLayout 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:orientation="vertical" >
<EditText
android:id="@+id/txtn2"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:digits="0123456789"
android:hint="Numbers from 0-9" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number 2" />
<EditText
android:id="@+id/txtn1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:digits="0123456789"
android:hint="Numbers from 0-9" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number 1" />
<Button
android:id="@+id/btnsum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Addition" />
</ LinearLayout >
Step 2: (MainActivity.java)
package com.example.additionexample;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText txtn1,txtn2;
private Button btnsum;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
private void addListenerOnButton() {
txtn1 = (EditText)findViewById(R.id.txtn1);
txtn2 = (EditText)findViewById(R.id.txtn2);
btnsum = (Button)findViewById(R.id.btnsum);
btnsum.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
String t1 = txtn1.getText().toString();
String t2 = txtn2.getText().toString();
int i1 = Integer.parseInt(t1);
int i2 = Integer.parseInt(t2);
int i3 = i1+i2;
Toast.makeText(getApplicationContext(),String.valueOf(i3),Toast.LENGTH_LONG).
show();
}
});
}
}
Example 2: Login Request Example in Android
Step 1: (activity_main.xml)
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1" >
<TableRow>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name: " >
</TextView>
<EditText
android:id="@+id/txtUname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" >
</EditText>
</TableRow>
<TableRow>
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password: " >
</TextView>
<EditText
android:id="@+id/txtPwd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"
android:text="" >
</EditText>
</TableRow>
<TableRow>
<Button
android:id="@+id/btnCancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Cancel" >
</Button>
<Button
android:id="@+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login" >
</Button>
</TableRow>
</TableLayout>
Step 2: (MainActivity.java)
package com.example.loginrequestexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnCancel;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtUserName=(EditText)this.findViewById(R.id.txtUname);
txtPassword=(EditText)this.findViewById(R.id.txtPwd);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if((txtUserName.getText().toString()).equals(txtPassword.getText().toString()))
{
}
else
{
}
}
});
}
}
Example:-3
Create login application where you will have to validate EmailID (UserName) . Till the user name and
password is not validated, login button should remain disabled.
Step 1: (activity_main.xml)
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/TableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="1" >
<TableRow>
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name: " >
</TextView>
<EditText
android:id="@+id/txtUname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" >
</EditText>
</TableRow>
<TableRow>
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password: " >
</TextView>
<EditText
android:id="@+id/txtPwd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:password="true"
android:text="" >
</EditText>
</TableRow>
<TableRow>
<Button
android:id="@+id/btnClear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Clear" >
</Button>
<Button
android:id="@+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login" >
</Button>
</TableRow>
</TableLayout>
Step 2: (MainActivity.java)
package com.example.disablebuttonlogin;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity
{
String uname="abc@gmail.com";
String pwd="rahul";
EditText txtUsr,txtPwd;
Button btnLogin,btnClear;
boolean usrStatus=false;
boolean pwdStatus=false;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin= (Button) findViewById(R.id.btnLogin);
txtUsr = (EditText)findViewById(R.id.txtUname);
txtPwd = (EditText)findViewById(R.id.txtPwd);
btnLogin.setEnabled(false);
btnLogin.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Valid UserName And Password",
Toast.LENGTH_LONG).show();
}
});
final Button btnClear = (Button)findViewById(R.id.btnClear);
btnClear.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
txtUsr.setText("");
txtPwd.setText("");
}
});
txtUsr.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
if(uname.equals(txtUsr.getText().toString()))
{
usrStatus=true;
}
else
{
usrStatus=false;
}
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3)
{
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0)
{
if(usrStatus && pwdStatus)
{
btnLogin.setEnabled(true);
}
else
{
btnLogin.setEnabled(false);
}
}
});
txtPwd.addTextChangedListener(new TextWatcher()
{
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
if(pwd.equals(txtPwd.getText().toString()))
{
pwdStatus=true;
}
else
{
pwdStatus=false;
}
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,int arg3)
{
}
public void afterTextChanged(Editable arg0)
{
if(usrStatus && pwdStatus)
{
btnLogin.setEnabled(true);
}
else
{
btnLogin.setEnabled(false);
}
}
});
}
}
Example:-4
Edittext Validation Example
Step 1: (activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="REGISTER USER"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#176CEC"
android:textStyle="bold" />
<EditText
android:id="@+id/editText_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:ems="10"
android:hint="YOUR EMAIL"
android:inputType="textEmailAddress"
android:padding="12dp" />
<EditText
android:id="@+id/editText_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:background="#fff"
android:ems="10"
android:hint="ENTER PASSWORD"
android:inputType="textPassword"
android:padding="12dp" />
<Button
android:id="@+id/btn_signup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#176CEC"
android:text="SIGN UP"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff"
android:textStyle="bold" />
Step 2: (MainActivity.java)
</LinearLayout>
package com.example.edittextvalidation;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
public class MainActivity extends Activity
{
private EditText emailEditText;
private EditText passEditText;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailEditText = (EditText) findViewById(R.id.editText_email);
passEditText = (EditText) findViewById(R.id.editText_password);
findViewById(R.id.btn_signup).setOnClickListener(new OnClickListener()
{
});
}
private boolean isValidEmail(String email)
{
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
Pattern p1 = Pattern.compile(EMAIL_PATTERN);
Matcher m1 = p1.matcher(email);
return m1.matches();
}
// validating password with retype password
private boolean isValidPassword(String pass)
{
if (pass != null && pass.length() > 6)
{
}
return false;
}
}
No comments:
Post a Comment