You are on page 1of 48

Storage Methods:

1. Shared Preferences
2. SQLite Databse
3. XML
1). Shared Preferences :
Interface for accessing and modifying preference data returned by
getSharedPreferences(String, int).
SharedPreferences
spf=getSharedPreferences("mypreferences",Context.MODE_PRIVATE);
SharedPreferences.Editor
Interface used for modifying values in a SharedPreferences object.
Create a new Editor for these preferences, through which you can make modifications to the data in the
preferences and atomically commit those changes back to the SharedPreferences object.
SharedPreferences.Editor editor=spf.edit();
Note : to get the data from shared prefernces shared prefrences object is enough but to insert data or to
modify data we need to create Shared Preferences.Editor Object.
The data is stored using key,value pairs you need pass a unique key for each value and you can
insert Boolean, Float , Long , String , int data type values.
Sample Program on Shared Preferences :

main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="38dp"
android:text="Enter Name :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="83dp"
android:text="Enter Password :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView1"
android:layout_marginLeft="27dp"
android:layout_toRightOf="@+id/textView1" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/editText1" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginTop="53dp"
android:onClick="Save"
android:text="Save" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="34dp"
android:onClick="getDetails"
android:text="getDetails" />
</RelativeLayout>
TestProjectActivity.java
package com.mahesh.test;
import ................;
public class TestProjectActivity extends Activity {
SharedPreferences spf;
SharedPreferences.Editor spe;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spf=getSharedPreferences("myprefs", Context.MODE_PRIVATE);
spe=spf.edit();
}
public void Save(View v){
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
spe.putString("name", et1.getText().toString());
spe.putString("pass", et2.getText().toString());
spe.commit();
}

public void getDetails(View v){


String name=spf.getString("name","There is no value with this key");
String pass=spf.getString("pass", "There is no value with this key");
Toast.makeText(getApplicationContext(),"User Name is :"+name+" Pass is :"+pass
,Toast.LENGTH_LONG ).show();
}
}
to explore persisted shared preferences select DDMS-data-data-select your package open shared
preferences you will get an xml with the preferences name.

2).

SQLite DataBase :

SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other
common database management tasks.
Note : Database names must be unique within an application, not across all applications.
openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
Is used to create the SQLite Object if the data base is not available creates a new database if
database is already available then it opens the database .
SQLiteDatabase db=openOrCreateDatabase("mydb",Context.MODE_PRIVATE, null);

Cursor : This interface provides random read-write access to the result set returned by a database
query.
db.execSQL("create table employee(eid varchar2(20),ename varchar2(20),desig
varchar2(20),dept varchar2(20));");
This statement creates a new table with employee if table is not there it will create a new table.
If table is already available it will through u an exception u need to handle it.
try{
db.execSQL("create table employee(eid varchar2(20),ename varchar2(20),desig
varchar2(20),dept varchar2(20));");
}catch(Exception e){e.printStackTrace();}
Sample Program on SQLite Database :

sqlite.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="33dp"
android:text="Employee id :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="40dp"
android:text="Employee Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="54dp"
android:text="Desig :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView3"
android:layout_marginTop="66dp"
android:text="Dept :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_marginLeft="35dp"
android:layout_toRightOf="@+id/textView2" >

<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView2" />
<EditText
android:id="@+id/editText3"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText2"
android:layout_alignParentRight="true" />
<EditText
android:id="@+id/editText4"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView4"
android:layout_alignBottom="@+id/textView4"
android:layout_alignLeft="@+id/editText3"
android:layout_alignParentRight="true" />
<RelativeLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText4"
android:layout_toRightOf="@+id/textView3"
android:orientation="vertical" >
</RelativeLayout>
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="Delete"
android:text="Delete" />
<Button
android:id="@+id/button2"

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignParentLeft="true"
android:onClick="Update"
android:text="Update" />
<Button
android:id="@+id/button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText4"
android:layout_marginTop="14dp"
android:onClick="Insert"
android:text="Insert" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button3"
android:onClick="getDetails"
android:text="getDetails" />
</RelativeLayout>

TestProjectActivity.java

sqlite.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="33dp"
android:text="Employee id :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="40dp"
android:text="Employee Name:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="54dp"
android:text="Desig :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView1"
android:layout_marginLeft="35dp"
android:layout_toRightOf="@+id/textView2" >
<requestFocus />

</EditText>

<EditText
android:id="@+id/editText2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/textView2" />
<EditText
android:id="@+id/editText3"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_alignLeft="@+id/editText2"
android:layout_alignParentRight="true" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Dept :"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="@+id/editText4"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText3"
android:layout_alignParentRight="true"
android:layout_centerVertical="true" />
<Button
android:id="@+id/button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText4"
android:onClick="Insert"
android:text="Insert" />
<Button
android:id="@+id/button4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:layout_alignParentLeft="true"
android:layout_below="@+id/button3"
android:onClick="getDetails"
android:text="getDetails" />
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button4"
android:onClick="Update"
android:text="Update" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/button2"
android:onClick="Delete"
android:text="Delete" />
</RelativeLayout>
TestProjectActivity. Java
package com.mahesh.test;
import ............;
public class TestProjectActivity extends Activity {
SQLiteDatabase db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlite);
db=openOrCreateDatabase("mydb",Context.MODE_PRIVATE, null);
try{
db.execSQL("create table employee(eid varchar2(20),ename varchar2(20),desig varchar2(20),dept
varchar2(20));");

}catch(Exception e){
e.printStackTrace();
}
}
public void Insert(View v){
EditText et1,et2,et3,et4;
et1=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
et4=(EditText)findViewById(R.id.editText4);
ContentValues cv=new ContentValues();
cv.put("eid",et1.getText().toString());
cv.put("ename", et2.getText().toString());
cv.put("desig", et3.getText().toString());
cv.put("dept", et4.getText().toString());
db.insert("employee",null,cv);
et1.setText("");
et2.setText("");
et3.setText("");
et4.setText("");
}
public void Update(View v){
EditText et1,et2,et3,et4;
et1=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
et4=(EditText)findViewById(R.id.editText4);
ContentValues cv=new ContentValues();
cv.put("ename", et2.getText().toString());
cv.put("desig", et3.getText().toString());
cv.put("dept", et4.getText().toString());
db.update("employee", cv, "eid=?", new String[]{et1.getText().toString()});

et1.setText("");
et2.setText("");
et3.setText("");
et4.setText("");
}
public void Delete(View v){
EditText et1;
et1=(EditText)findViewById(R.id.editText1);
db.delete("employee", "eid=?", new String[]{et1.getText().toString()});
et1.setText("");
}
public void getDetails(View v){
EditText et1;
et1=(EditText)findViewById(R.id.editText1);
Cursor c=db.query("employee", new String[]{"eid","ename","desig","dept"}, "eid=?", new
String[]{et1.getText().toString()}, null, null, null);
while (c.moveToNext()) {
Toast.makeText(getApplicationContext(), "Eid is :"+c.getString(0)+"\n Ename
is :"+c.getString(1)+"\n Desig is :"+c.getString(2)+"\n Dept
is :"+c.getString(3),Toast.LENGTH_LONG).show();
}
}
}

If you want explore the db file select DDMS- data data select your package inside package u will
find a database folder and select u r db file u can pull that one to ur system by selecting pull a file from
the device icon . SQLite browser is used to explore your sqlite dbfile .

Using XML :
You can persist the data as a XML file . The advantage if u persist the data in xml u can store
the data into ur external and internal storage and xml interapable language . If you want share your to
some other technologies use XML format.
To read and write the data into xml file we need XML parsers.
There are two types of parser are available
1).
2).

JAXP ( DOM (read-write) , SAX (Read-only))


JAXB
Android does not support JAXB.

For the above Activity instead of persisting the data into SQLite we will store the data in to XML

Working with DOM :


to run this application u need to add the below permission in the AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Before run this application u need to create a xml file in your sdcard as the following structure
mnt/sdcard/xml/ Employees.xml with root tag as <employees></employees>
package com.mahesh.test;
import java.io.File;
import .........................;
public class TestProjectActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlite);
}
public void Insert(View v){
try{
EditText et1,et2,et3,et4;
et1=(EditText)findViewById(R.id.editText1);
et2=(EditText)findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
et4=(EditText)findViewById(R.id.editText4);
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
File f=new File(Environment.getExternalStorageDirectory()+"/xml/Employees.xml");
// to parse the file there xml file should be available with root tag <employees> <
/employees> otherwise create a new document element

Document d=db.parse(f);
Element e1=d.createElement("employee");
Element e2=d.createElement("eid");
Element e3=d.createElement("ename");
Element e4=d.createElement("desig");
Element e5=d.createElement("dept");
String eid,ename,desig,dept;
eid=et1.getText().toString();
ename=et2.getText().toString();
desig=et3.getText().toString();
dept=et4.getText().toString();
Node n1=d.createTextNode(eid);
Node n2=d.createTextNode(ename);
Node n3=d.createTextNode(desig);
Node n4=d.createTextNode(dept);
e2.appendChild(n1);
e3.appendChild(n2);
e4.appendChild(n3);
e5.appendChild(n4);
e1.appendChild(e2);
e1.appendChild(e3);
e1.appendChild(e4);
e1.appendChild(e5);
d.getDocumentElement().appendChild(e1);
TransformerFactory tfr=TransformerFactory.newInstance();
Transformer tf=tfr.newTransformer();
DOMSource ds=new DOMSource(d);
// AssetManager am=getAssets();
StreamResult sr=new StreamResult(f);
// StreamResult sr=new
StreamResult(openFileOutput("Employees.xml",Context.MODE_WORLD_WRITEABLE));
tf.transform(ds, sr);
et1.setText("");

et2.setText("");
et3.setText("");
et4.setText("");
}catch(Exception e){
e.printStackTrace();
}
}
public void Update(View v){
// Note : i want to update the data whose name is mahesh i want change the data to Rajesh
try{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
File f=new File(Environment.getExternalStorageDirectory()+"/xml/Employees.xml");
// to parse the file there xml file should be available with root tag <employees> <
/employees> otherwise create a new document element
Document d=db.parse(f);
NodeList nl=d.getElementsByTagName("ename");
for(int i=0;i<nl.getLength();i++){
Node n=nl.item(i);
if(n.getFirstChild().getNodeValue().equals("Mahesh")){
n.getFirstChild().setNodeValue("Rajesh");
}
}
TransformerFactory tfr=TransformerFactory.newInstance();
Transformer tf=tfr.newTransformer();
DOMSource ds=new DOMSource(d);
// AssetManager am=getAssets();
StreamResult sr=new StreamResult(f);

// StreamResult sr=new
StreamResult(openFileOutput("Employees.xml",Context.MODE_WORLD_WRITEABLE));
tf.transform(ds, sr);
}catch(Exception e){
e.printStackTrace();
}
}
public void Delete(View v){
// i want remove the ename from the employee record whose name is Rajesh
try{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
File f=new File(Environment.getExternalStorageDirectory()+"/xml/Employees.xml");
// to parse the file there xml file should be available with root tag <employees> <
/employees> otherwise create a new document element
Document d=db.parse(f);
NodeList nl=d.getElementsByTagName("employee");
for(int i=0;i<nl.getLength();i++){
Node n=nl.item(i);
NodeList nl1=n.getChildNodes();
for(int j=0;j<nl1.getLength();j++){
if(nl1.item(j).getFirstChild().getNodeValue().equals("Rajesh")){
n.removeChild(nl1.item(j));
}
}
TransformerFactory tfr=TransformerFactory.newInstance();
Transformer tf=tfr.newTransformer();

DOMSource ds=new DOMSource(d);


// AssetManager am=getAssets();
StreamResult sr=new StreamResult(f);
// StreamResult sr=new
StreamResult(openFileOutput("Employees.xml",Context.MODE_WORLD_WRITEABLE));
tf.transform(ds, sr);
}
}catch(Exception e){
e.printStackTrace();
}
}
public void getDetails(View v){
// i want to display the employee records in a Toast message
try{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
File f=new File(Environment.getExternalStorageDirectory()+"/xml/Employees.xml");
// to parse the file there xml file should be available with root tag <employees> <
/employees> otherwise create a new document element
Document d=db.parse(f);
String msg="";
NodeList nl=d.getElementsByTagName("employee");
for(int i=0;i<nl.getLength();i++){
Node n=nl.item(i);
NodeList nl1=n.getChildNodes();
for(int j=0;j<nl1.getLength();j++){
msg=msg+nl1.item(j).getFirstChild().getNodeValue()+"\n";

}
Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_LONG).show();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Before performing delete operation

after delete operation

SAX Parser :
SAX Parser is the read only parser compare to DOM Parser reading the data using SAX
Parser is easy and having move advantages than DOM Parser .
Code to get the data using SAX Parser :
add this method in the previous example
public void getDataUsingSAX(View v){
try{
File f=new File(Environment.getExternalStorageDirectory()+"/xml/Employees.xml");
SAXParserFactory spf=SAXParserFactory.newInstance();
SAXParser sp=spf.newSAXParser();
sp.parse(f, new DefaultHandler(){
Boolean eid,ename,desig,dept;
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
super.characters(ch, start, length);
if(eid){
Toast.makeText(getApplicationContext(), "Employee id is :"+new
String(ch, start, length), Toast.LENGTH_SHORT).show();
}
if(ename){
Toast.makeText(getApplicationContext(), "Employee Name
is :"+new String(ch, start, length), Toast.LENGTH_SHORT).show();
}
if(desig){
Toast.makeText(getApplicationContext(), "Employee Desig
is :"+new String(ch, start, length), Toast.LENGTH_SHORT).show();
}

if(dept){
Toast.makeText(getApplicationContext(), "Employee Dept
is :"+new String(ch, start, length), Toast.LENGTH_SHORT).show();
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
super.endElement(uri, localName, qName);
if(qName.equals("eid")){
eid=false;
}
if(qName.equals("ename")){
ename=false;
}
if(qName.equals("desig")){
desig=false;
}
if(qName.equals("dept")){
dept=false;
}
}
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
super.startElement(uri, localName, qName, attributes);
System.out.println(qName);
if(qName.equals("eid")){
eid=true;
}
if(qName.equals("ename")){
ename=true;
}
if(qName.equals("desig")){
desig=true;
}

if(qName.equals("dept")){
dept=true;
}
}
});
}catch(Exception e){
e.printStackTrace();
}
}
Android With Restful WebServices Communication :
Android SDK inbuild is having supporting libraries to communicate with Restful WebServices
Sample code to interact With Restful WebServices :
(My Intension is I will pass two parameters to server, get the response from the server display the
response message using Toast)

login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"

android:layout_alignParentTop="true"
android:layout_marginTop="32dp"
android:text="Enter Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="44dp"
android:text="Enter Password"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_marginTop="35dp"
android:layout_toRightOf="@+id/textView2"
android:onClick="Login"
android:text="Login" />
<EditText
android:id="@+id/editText1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_toRightOf="@+id/button1" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_toRightOf="@+id/button1" />
</RelativeLayout>

WebServicesTest . Java
package com.mahesh.xml;
import ........................;
public class WebServicesTest extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void Login(View v){
try{
// Calling Restful WebServices as a path Params
DefaultHttpClient httpClient=new DefaultHttpClient();
// we need to add the request type
Post request HttpPost

get | post if it is a get request call HttpGet if it is

// Here specify your webservice URL address my web service is running on this
IPAddress and the port Number and i am passing the parameters as a path parameters
HttpGet get=new HttpGet("http://192.168.137.1:8888//rest/welcome/mahesh/bened");
/* In case of Query Paramaters
* HttpGet get=new HttpGet("http://192.168.137.1:8888//rest/welcome?
name=mahesh&pass=bened);
*
* InCase of Matrix Parameters
*
* HttpGet get=new
HttpGet("http://192.168.137.1:8888//rest/welcome/name:mahesh;pass=bened);
*
*/
// Here I am getting the text/plain as a response we need add as header
get.addHeader("accept", "text/plain");
/*
* Header are different based on your response if your getting a image file

* get.addHeader("accept","image/jpg");
* if ur getting a XML as Output
* get.Header("accept","application/xml");
* if ur getting a JSON as Output
* get.Header("accept","application/json");
*/
HttpResponse response=httpClient.execute(get);
InputStream isr=response.getEntity().getContent();
int i=isr.read();
String msg="";
while(i!=-1){
msg=msg+(char)i;
i=isr.read();
}
Toast.makeText(getApplicationContext(), "Response from the server is :"+msg,
Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
} } }
If you are calling a Java or Other WebComponent :
public void Login(View v){
URL u=new URL("http://192.168.137.1:8888//Android?uname=mahesh&pass=bened");
InputStream isr=response.getEntity().getContent();
int i=isr.read();
String msg="";
while(i!=-1){
msg=msg+(char)i;
i=isr.read();
}
Toast.makeText(getApplicationContext(), "Response from the server is :"+msg,
Toast.LENGTH_LONG).show();
}
To Work with above application you need add the following permissions in the
AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

Working With WebView:


A View that displays web pages. This class is the basis upon which you can roll your own web
browser or simply display some online content within your Activity. It uses the WebKit rendering
engine to display web pages and includes methods to navigate forward and backward through a history,
zoom in and out, perform text searches and more.
To enable the built-in zoom, set WebSettings.setBuiltInZoomControls(boolean) (introduced in API
version 3).
Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must
add the INTERNET permissions to your Android Manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

Sample Application on WebView :


Take the input from the user through edittext and when you press go button load
the web page in the webview

WebServicesTest.java

WebServicesTest.java
package com.mahesh.xml;
import ..................;
public class WebServicesTest extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void Go(View v){
EditText et1=(EditText)findViewById(R.id.editText1);
WebView wv=(WebView)findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.getSettings().setUseWideViewPort(true);
wv.getSettings().setAllowFileAccess(true);
wv.getSettings().getLoadsImagesAutomatically();
wv.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String arg0, String arg1, String arg2,
String arg3, long arg4) {
Intent i=new Intent(Intent.ACTION_VIEW);
startActivity(i);
}
});
final ProgressDialog pdialog=new ProgressDialog(this);
pdialog.setTitle("Message...");
pdialog.setIcon(R.drawable.ic_launcher);
pdialog.setMessage("Pls wait page is loading.......");
pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

wv.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pdialog.dismiss();
}
@Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
pdialog.show();
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
});
wv.loadUrl("http://"+et1.getText().toString());
} }
Working With Wifi :
WifiManager :
This class provides the primary API for managing all aspects of Wi-Fi
connectivity. Get an instance of this class by calling
Context.getSystemService(Context.WIFI_SERVICE). It deals with several categories of items:
The list of configured networks. The list can be viewed and updated, and attributes of individual
entries can be modified.
The currently active Wi-Fi network, if any. Connectivity can be established or torn down, and
dynamic information about the state of the network can be queried.
Results of access point scans, containing enough information to make decisions about what
access point to connect to.
It defines the names of various Intent actions that are broadcast upon any sort of change in WiFi state. To work with this application you need to add the following persmissions in the
manifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

WifiConfiguration :
A class representing a configured Wi-Fi network, including the security configuration.
Sample Code to Work With Wifi :

wifi.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="114dp"
android:layout_marginTop="27dp"
android:onClick="Wifi"
android:text="Wifi"
/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_alignParentLeft="true"
android:layout_below="@+id/toggleButton1"
android:layout_marginLeft="95dp"
android:layout_marginTop="55dp"
android:onClick="getWifiList"
android:text="getWifiList" />
</RelativeLayout>
WifiExample.java
package com.mahesh.xml;
import ..................;
public class WifiExample extends Activity {
WifiManager wManager;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
wManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);
setContentView(R.layout.wifi);
button=(Button)findViewById(R.id.toggleButton1);
if(wManager.getWifiState()==wManager.WIFI_STATE_DISABLED){
button.setText("Wifi On");
}else if(wManager.getWifiState()==wManager.WIFI_STATE_ENABLED){
button.setText("Wifi Off");
}
}
public void Wifi(View v){
if(wManager.getWifiState()==wManager.WIFI_STATE_DISABLED){
wManager.setWifiEnabled(true);
button.setText("Wifi Off");
}else if(wManager.getWifiState()==wManager.WIFI_STATE_ENABLED){
wManager.setWifiEnabled(false);
button.setText("Wifi On");
}
}

public void getWifiList(View v){

List<WifiConfiguration> wificonfig=wManager.getConfiguredNetworks();
for(WifiConfiguration wifi:wificonfig){
Toast.makeText(getApplicationContext(), " SSID : "+wifi.SSID +" \n
BSSID :"+wifi.BSSID+"\n Status :"+wifi.status+"\n
Priority :"+wifi.priority,Toast.LENGTH_LONG).show();
}
}
}
Notification Manager :
class to notify the user of events that happen. This is how you tell the user that something has
happened in the background.
Notifications can take different forms:
A persistent icon that goes in the status bar and is accessible through the launcher, (when the
user selects it, a designated Intent can be launched),
Turning on or flashing LEDs on the device, or
Alerting the user by flashing the backlight, playing a sound, or vibrating.
Each of the notify methods takes an int id parameter. This id identifies this notification from your app
to the system, so that id should be unique within your app. If you call one of the notify methods with an
id that is currently active and a new set of notification parameters, it will be updated. For example, if
you pass a new status bar icon, the old icon in the status bar will be replaced with the new one. This is
also the same id you pass to the cancel(int) method to clear this notification.
You do not instantiate this class directly; instead, retrieve it through getSystemService(String).
Notification :
Notification
A Notification object defines the details of the notification message that is displayed in the status bar
and "Notifications" window, and any other alert settings, such as sounds and blinking lights.
A status bar notification requires all of the following:
An icon for the status bar
A title and expanded message for the expanded view (unless you define a custom expanded
view)
A PendingIntent, to be fired when the notification is selected
Optional settings for the status bar notification include:
A ticker-text message for the status bar
An alert sound

A vibrate setting
A flashing LED setting
Vibrator :
Class that operates the vibrator on the device.
If your process exits, any vibration you started with will stop.
You do not instantiate this class directly; instead, retrieve it through getSystemService(String).
Vibrator vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
Need to add the following permission in the AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE"/>

Develop a sample code to display notification and Vibrate the device when wifi is switch on or
wifi switch off for the above application.

package com.mahesh.xml;
import java.util.List;
import ............................;
public class WifiExample extends Activity {
WifiManager wManager;
Button button;

NotificationManager nManager;
Notification notification;
Vibrator vibrator;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi);
wManager=(WifiManager)getSystemService(Context.WIFI_SERVICE);
button=(Button)findViewById(R.id.toggleButton1);
nManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
if(wManager.getWifiState()==wManager.WIFI_STATE_DISABLED){
button.setText("Wifi On");
}else if(wManager.getWifiState()==wManager.WIFI_STATE_ENABLED){
button.setText("Wifi Off");
}
}
public void Wifi(View v){
if(wManager.getWifiState()==wManager.WIFI_STATE_DISABLED){
wManager.setWifiEnabled(true);
button.setText("Wifi Off");
notification=new Notification(R.drawable.ic_launcher, "Wifi State Changed",
System.currentTimeMillis());
notification.setLatestEventInfo(getBaseContext(), "Wifi State Changed","Wifi
Enabled", getPendingIntent());
nManager.notify(1, notification);
vibrator.vibrate(1000);
}else if(wManager.getWifiState()==wManager.WIFI_STATE_ENABLED){
wManager.setWifiEnabled(false);
button.setText("Wifi On");
notification=new Notification(R.drawable.ic_launcher, "Wifi State
Changed", System.currentTimeMillis());
notification.setLatestEventInfo(getBaseContext(), "Wifi State

Changed","Wifi Disabled", getPendingIntent());


nManager.notify(1, notification);
vibrator.vibrate(1000);
}
}
private PendingIntent getPendingIntent() {
Intent i=new Intent(getBaseContext(), WifiExample.class);
PendingIntent pi=PendingIntent.getActivity(getBaseContext(), 0,i, 0);
return pi;
}
public void getWifiList(View v){
List<WifiConfiguration> wificonfig=wManager.getConfiguredNetworks();
for(WifiConfiguration wifi:wificonfig){
Toast.makeText(getApplicationContext(), " SSID : "+wifi.SSID +" \n
BSSID :"+wifi.BSSID+"\n Status :"+wifi.status+"\n
Priority :"+wifi.priority,Toast.LENGTH_LONG).show();
}
}
}
LocationManager :
This class provides access to the system location services. These services allow applications to
obtain periodic updates of the device's geographical location, or to fire an application-specified Intent
when the device enters the proximity of a given geographical location. You do not instantiate this class
directly; instead, retrieve it through Context.getSystemService(Context.LOCATION_SERVICE).
you need to add the following permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
public void requestLocationUpdates (String provider, long minTime, float minDistance,
LocationListener listener)
Registers the current activity to be notified periodically by the named provider. Periodically, the
supplied LocationListener will be called with the current Location or with status updates.

It may take a while to receive the most recent location. If an immediate location is required,
applications may use the getLastKnownLocation(String) method.
In case the provider is disabled by the user, updates will stop, and the onProviderDisabled(String)
method will be called. As soon as the provider is enabled again, the onProviderEnabled(String) method
will be called and location updates will start again.
The frequency of notification may be controlled using the minTime and minDistance parameters. If
minTime is greater than 0, the LocationManager could potentially rest for minTime milliseconds
between location updates to conserve power. If minDistance is greater than 0, a location will only be
broadcasted if the device moves by minDistance meters. To obtain notifications as frequently as
possible, set both parameters to 0.
Background services should be careful about setting a sufficiently high minTime so that the device
doesn't consume too much power by keeping the GPS or wireless radios on all the time. In particular,
values under 60000ms are not recommended.
The calling thread must be a Looper thread such as the main thread of the calling Activity.
Parameters

provider

the name of the provider with which to register


the minimum time interval for notifications, in milliseconds. This field is only used as a
minTime hint to conserve power, and actual time between location updates may be greater or
lesser than this value.
minDistance the minimum distance interval for notifications, in meters
a {#link LocationListener} whose onLocationChanged(Location) method will be called
listener
for each location update
Sample Code to Work with LocationBasedServices :

package com.mahesh.xml;
import ..............................;

public class LocationTest extends Activity{


LocationManager lManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
lManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
new LocationListener() {
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Latitude value
is :"+l.getLatitude()+"Logitude value is :"+l.getLongitude(), Toast.LENGTH_SHORT).show();
}

});

public void getLocation(View v){


Location l=lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Toast.makeText(getApplicationContext(), "Latitude value is :"+l.getLatitude()
+"Logitude value is :"+l.getLongitude(), Toast.LENGTH_SHORT).show();
}}

ListActivity :
An activity that displays a list of items by binding to a data source such as an array or Cursor,
and exposes event handlers when the user selects an item.
ListActivity hosts a ListView object that can be bound to different data sources, typically either an
array or a Cursor holding query results. Binding, screen layout, and row layout are discussed in the
following sections.
Screen Layout
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen.
However, if you desire, you can customize the screen layout by setting your own view layout with
setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the
id "@android:id/list" (or list if it's in code)
Optionally, your custom view can contain another view object of any type to display when the list view
is empty. This "empty list" notifier must have an id "android:empty". Note that when an empty view is
present, the list view will be hidden when there is no data to display.
The following code demonstrates an (ugly) custom screen layout. It has a list with a green background,
and an alternate red "no data" message.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView id="@id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>

Base Adapter :
Common base class of common implementation for an Adapter that can be used in both
ListView (by implementing the specialized ListAdapter interface} and Spinner (by implementing the
specialized SpinnerAdapter interface.

Sample Program to display image names in SDCARD using ListActivity:

package com.mahesh.xml;
import java.io.File;
import ..................;
public class ListActivityTest extends ListActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
String path=Environment.getExternalStorageDirectory()+"/images";
File f=new File(path);
if(f.exists()){
String[] images=f.list();
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_gallery_item,images);
setListAdapter(adapter);

}else{
Toast.makeText(getApplicationContext(), "There is no file with the given
path",Toast.LENGTH_LONG).show();
}
}
}
Sample program on creating own CustomView Adapter and display image , image name and
image size from SDCARD/images directory:

main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/imageView1"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_toRightOf="@+id/imageView1"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
ListActivityImagesActivity. Java
package com.mahesh.listimages;
import ................;
public class ListActivityImagesActivity extends ListActivity implements
AdapterView.OnItemSelectedListener{

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new MyAdapter(this));
getListView().setOnItemSelectedListener(this);
}
class MyAdapter extends BaseAdapter{
private LayoutInflater inflater;
private Bitmap icon1;
private String[] files;
String path;
public MyAdapter(ListActivityImagesActivity laia) {
inflater=LayoutInflater.from(laia);
icon1=BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
path=Environment.getExternalStorageDirectory()+"/images";

File f=new File(path);


files=f.list();
}
public int getCount() {
// TODO Auto-generated method stub
return files.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View view, ViewGroup view_group) {
// TODO Auto-generated method stub
view=inflater.inflate(R.layout.main,null);
TextView tv1=(TextView) view.findViewById(R.id.textView1);
TextView tv2=(TextView) view.findViewById(R.id.textView2);
ImageView iv1=(ImageView)view.findViewById(R.id.imageView1);
tv1.setText(files[position].toString());
File f=new File(path+"/"+files[position]);
tv2.setText(f.length()/1024+"kb");
iv1.setImageURI(Uri.fromFile(f));
return view;
}
}

public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,


long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "from on Item Selected... ",
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Gallery :
A view that shows items in a center-locked, horizontally scrolling list.
The default values for the Gallery assume you will be using Theme_galleryItemBackground as the
background for each View given to the Gallery from the Adapter. If you are not doing this, you may
need to adjust some Gallery properties, such as the spacing.
Views given to the Gallery should use Gallery.LayoutParams as their layout parameters type.
Sample Code to work with Gallery and CustomView Adapter:

main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ImageView
android:id="@+id/imageView1"
android:paddingLeft="10px"
android:paddingRight="10px"
android:layout_width="100px"
android:layout_height="100px"
android:src="@drawable/ic_launcher" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/imageView1"
android:layout_marginLeft="27dp" />
</RelativeLayout>
Gallery.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Gallery
android:id="@+id/gallery1"
android:layout_width="300px"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="16dp" />
</RelativeLayout>

GalleryTestExActivity.java
package com.mahesh.gallery;
import ...................................;
public class GalleryTestExActivity extends Activity implements OnItemSelectedListener {
ArrayList<String> images_names=new ArrayList<String>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
Gallery g=(Gallery)findViewById(R.id.gallery1);
g.setAdapter(new MyAdapter(this));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> adview, View view, int arg2,
long arg3) {
CheckBox cb1=(CheckBox)findViewById(R.id.checkBox1);
if(cb1.isChecked()){
images_names.add(cb1.getText().toString());
Toast.makeText(getApplicationContext(),cb1.getText(),Toast.LENGTH_LONG).show();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
images_names.size(),Toast.LENGTH_LONG).show();
}

MyAdapter.java :
package com.mahesh.gallery;
import ..................;
public class MyAdapter extends BaseAdapter{
GalleryTestExActivity gta;
LayoutInflater inflater;
String path=Environment.getExternalStorageDirectory()+"/images";
File f=new File(path);
String[] images=f.list();
public MyAdapter(GalleryTestExActivity gtea) {
gta=gtea;
inflater=LayoutInflater.from(gtea);
}
public int getCount() {
return images.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup arg2) {
view=inflater.inflate(R.layout.main, null);

ImageView iv1=(ImageView)view.findViewById(R.id.imageView1);
CheckBox cb1=(CheckBox)view.findViewById(R.id.checkBox1);
cb1.setText(images[position].toString());
File f=new File(path+"/"+images[position]);
Uri uri=Uri.fromFile(f);
iv1.setImageURI(uri);
return view;
}
}

MediaPlayer :
MediaPlayer class can be used to control playback of audio/video files and streams. An example
on how to use the methods in this class can be found in VideoView. Please see Audio and Video for
additional help using MediaPlayer.
Important methods :
Method Name

Valid Sates

Invalid States

Comments

isPlaying

{Idle, Initialized,
Prepared, Started,
Paused, Stopped, {Error}
PlaybackComplete
d}

Successful invoke of this method in a valid state


does not change the state. Calling this method in
an invalid state transfers the object to the Error
state.

pause

{Idle, Initialized,
Prepared,
{Started, Paused} Stopped,
PlaybackComplet
ed, Error}

Successful invoke of this method in a valid state


transfers the object to the Paused state. Calling
this method in an invalid state transfers the object
to the Error state.

prepare

{Initialized,
Stopped}

{Idle, Prepared,
Successful invoke of this method in a valid state
Started, Paused,
transfers the object to the Prepared state. Calling
PlaybackComplet
this method in an invalid state throws an
ed, Error}
IllegalStateException.

setDataSource {Idle}

{Initialized,
Prepared, Started,
Paused, Stopped,
PlaybackComplet
ed, Error}

Successful invoke of this method in a valid state


transfers the object to the Initialized state. Calling
this method in an invalid state throws an
IllegalStateException.

setVolume

{Idle, Initialized,
Stopped, Prepared,
Started, Paused,
{Error}
PlaybackComplete
d}

start

{Prepared, Started,
Paused,
{Idle, Initialized,
PlaybackComplete Stopped, Error}
d}

stop

{Prepared, Started,
Successful invoke of this method in a valid state
Stopped, Paused, {Idle, Initialized,
transfers the object to the Stopped state. Calling
PlaybackComplete Error}
this method in an invalid state transfers the object
d}
to the Error state.

Successful invoke of this method does not change


the state.
Successful invoke of this method in a valid state
transfers the object to the Started state. Calling
this method in an invalid state transfers the object
to the Error state.

You might also like