Android Practical Program Soluation For GTU MCA Student

Document Sample
Android Practical Program Soluation For GTU MCA Student Powered By Docstoc
					                                                    SL-MC( 650017)

Name:  Keval.M.Nagaria                   Enrollment No. : 095370693050
 
                             Index
Sr              Particular   Page No   Remark             Sign

    1   Exercise -1          2

    2   Exercise -2          3

    3   Exercise -3          7

    4   Exercise -4          11

    5   Exercise -5          15

    6   Exercise -6          19

    7   Exercise -7          21

    8   Exercise -8          23

    9   Exercise -9          28

10 Exercise -10              32

11 Exercise -11              37

12 Exercise -12              43

13 Exercise -13              45

14 Exercise -14              47

15 Exercise -15              50

16 Exercise -16              53

17 Exercise -17              56

18 Exercise -18              58

19 Exercise -19              70

20 Exercise -20              75

21 Exercise -21              77

22 Exercise -22              82

23 Exercise -23              83

24 Exercise -24              87

537‐ JVIMS ‐MCA                                         [ Page 1 of 89 ]

 
                                                                       SL-MC( 650017)

Name:  Keval.M.Nagaria                                      Enrollment No. : 095370693050
 
Exercise : 1
Create “Hello World” application. That will display “Hello World” in the middle of the
screen in the red color with white background.


Screen Shot:




XML :

main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/bgcolor" android:orientation="horizontal">
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" android:layout_gravity="center_vertical"
android:gravity="center_horizontal" android:textColor="@color/fgcolor"/>
</LinearLayout>




537‐ JVIMS ‐MCA                                                            [ Page 2 of 89 ]

 
                                                                     SL-MC( 650017)

Name:  Keval.M.Nagaria                                    Enrollment No. : 095370693050
 
JAVA :

FirstActivity.java :

package keval.first;

import android.app.Activity;
import android.os.Bundle;

public class FirstActivity extends Activity
{
    /** @author Y@@D */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Exercise : 2
To understand Activity, Intent
a. Create sample application with login module.(Check username and password)
b. On successful login, go to next screen. And on failing login, alert user using
Toast.
c. Also pass username to next screen


Screen Shot:




                                                                                             


537‐ JVIMS ‐MCA                                                          [ Page 3 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




                                                                                      

XML :

main.xml :

<?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"
    >
    <RelativeLayout android:layout_width="match_parent"
android:id="@+id/relativeLayout1" android:layout_height="match_parent"
android:background="@color/bgcolor">
        <TextView android:id="@+id/textView1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentTop="true" android:layout_alignParentLeft="true"
android:layout_marginTop="45dp" android:text="Enter User Name
:"></TextView>
        <EditText android:layout_width="wrap_content"
android:layout_height="wrap_content" android:inputType="textPersonName"
android:layout_below="@+id/textView1" android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" android:id="@+id/txtusername"
android:hint="Enter UserName">
            <requestFocus></requestFocus>
        </EditText>
        <TextView android:id="@+id/textView2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_below="@+id/txtusername"
537‐ JVIMS ‐MCA                                                   [ Page 4 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
android:layout_alignParentLeft="true" android:layout_marginTop="20dp"
android:text="Enter Password :"></TextView>
        <EditText android:layout_width="wrap_content"
android:layout_height="wrap_content" android:inputType="textPassword"
android:layout_below="@+id/textView2" android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" android:id="@+id/txtpassword"
android:hint="Enter Password"></EditText>
        <Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnlogin"
android:layout_toRightOf="@+id/textView1" android:text="Clear"
android:id="@+id/btnclear"></Button>
        <Button android:id="@+id/btnlogin"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Login" android:layout_below="@+id/txtpassword"
android:layout_alignRight="@+id/textView2"
android:layout_marginRight="33dp" android:layout_marginTop="21dp"></Button>
    </RelativeLayout>
</LinearLayout>


JAVA :

SecondActivity.java :

package kmn.Second;

import   android.app.Activity;
import   android.content.Intent;
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 SecondActivity extends Activity implements OnClickListener
{
    /** @author Y@@D */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button login = (Button)findViewById(R.id.btnlogin);
        Button clear = (Button)findViewById(R.id.btnclear);
        login.setOnClickListener(this);
        clear.setOnClickListener(this);
    }
    public void onClick(View v)
    {
      EditText username = (EditText)findViewById(R.id.txtusername);
      EditText password =(EditText)findViewById(R.id.txtpassword);
      if(v.getId()==R.id.btnlogin)
      {
            if(username.getText().toString().equals("keval") &&
      password.getText().toString().equals("nagaria"))
            {
                  //Toast.makeText(this, "ok", Toast.LENGTH_LONG).show();
                  Intent i = new Intent(this,S2.class);
                  i.putExtra("username", username.getText().toString());
537‐ JVIMS ‐MCA                                                   [ Page 5 of 89 ]

 
                                                                  SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
                      startActivity(i);
              }
              else
              {
                      Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
              }
         }
         if(v.getId()==R.id.btnclear)
         {
               username.setText("");
               password.setText("");
         }
    }
}

S2.java :

package kmn.Second;

import   android.app.Activity;
import   android.content.Intent;
import   android.graphics.Color;
import   android.os.Bundle;
import   android.view.View;
import   android.view.ViewGroup.LayoutParams;
import   android.widget.Button;
import   android.widget.LinearLayout;
import   android.widget.TextView;

public class S2 extends Activity
{
    /** @author Y@@D */
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent i = getIntent();
        //Toast.makeText(this, "Welcome",Toast.LENGTH_LONG).show();
        String username=i.getStringExtra("username");
        TextView tv=new TextView(this);
        Button btnBack = new Button(this);
        btnBack.setText("Back");
        tv.setText("Welcome "+username+" !");
        tv.setTextColor(Color.rgb(255, 255, 100));
        tv.setTextSize(25);
        LinearLayout ll = new LinearLayout(this);
        ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
      LayoutParams.FILL_PARENT));
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.addView(tv);
        ll.addView(btnBack);
        setContentView(ll);

          btnBack.setOnClickListener(new Button.OnClickListener()
          {
              public void onClick(View v)
              {
                    setContentView(R.layout.main);
              }
537‐ JVIMS ‐MCA                                                       [ Page 6 of 89 ]

 
                                                                   SL-MC( 650017)

Name:  Keval.M.Nagaria                                  Enrollment No. : 095370693050
 
           });
       }

}

Exercise : 3
Create login application where you will have to validate EmailID(UserName). Till
the username and password is not validated , login button should remain disabled.


Screen Shot:




                                                                                           




537‐ JVIMS ‐MCA                                                        [ Page 7 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




XML :

main.xml :

<?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"
    >
    <RelativeLayout android:background="@color/bgcolor"
android:layout_width="match_parent" android:id="@+id/relativeLayout1"
android:layout_height="match_parent">
        <TextView android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" android:text="User Name :"
android:layout_marginTop="35dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView1" android:layout_height="wrap_content"
android:layout_width="wrap_content"></TextView>
        <EditText android:layout_alignParentLeft="true"
android:inputType="textEmailAddress" android:id="@+id/txtemail"
android:layout_below="@+id/textView1"
android:layout_alignParentRight="true" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:hint="Enter User
Name"></EditText>
        <TextView android:layout_alignParentLeft="true"
android:text="Password :" android:layout_marginTop="15dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_below="@+id/txtemail" android:id="@+id/textView2"

537‐ JVIMS ‐MCA                                                   [ Page 8 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
android:layout_height="wrap_content"
android:layout_width="wrap_content"></TextView>
        <EditText android:inputType="textPassword"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_below="@+id/textView2" android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" android:id="@+id/txtpassword"
android:hint="Enter Password">
            <requestFocus></requestFocus>
        </EditText>
        <Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_centerVertical="true"
android:layout_toRightOf="@+id/textView1" android:id="@+id/btnlogin"
android:text="Login" android:textSize="20px"
android:enabled="false"></Button>
    </RelativeLayout>

</LinearLayout>


JAVA :

ThirdActivity.java :

package kmn.Third;

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

public class ThirdActivity extends Activity implements
OnClickListener,TextWatcher
{
    /**@author Y@@D */
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EditText txtemail = (EditText)findViewById(R.id.txtemail);
        EditText txtpassword = (EditText)findViewById(R.id.txtpassword);
        txtemail.addTextChangedListener(this);
        txtpassword.addTextChangedListener(this);
        Button btn = (Button)findViewById(R.id.btnlogin);
        btn.setOnClickListener(this);
    }
    public void onClick(View v)
    {
      EditText txte = (EditText)findViewById(R.id.txtemail);
        EditText txtp = (EditText)findViewById(R.id.txtpassword);

         if(txte.getText().toString().equals("keval") &&
         txtp.getText().toString().equals("nagaria"))
         {
537‐ JVIMS ‐MCA                                                      [ Page 9 of 89 ]

 
                                                                  SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
                Intent i = new Intent(this,S2.class);
                i.putExtra("txte", txte.getText().toString());
                startActivity(i);

                //Toast.makeText(this, "Login...",Toast.LENGTH_LONG).show();
         }
         else
         {
                Toast.makeText(this, "Invalid",Toast.LENGTH_LONG).show();
         }
    }
    public void afterTextChanged(Editable s)
    {
      EditText txte = (EditText)findViewById(R.id.txtemail);
        EditText txtp = (EditText)findViewById(R.id.txtpassword);
        Button btn = (Button)findViewById(R.id.btnlogin);
        if(txte.getText().toString().equals("keval") &&
txtp.getText().toString().equals("nagaria"))
      {
            btn.setEnabled(true);
      }
      else
      {
            btn.setEnabled(false);
      }
    }
      public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                  int arg3) {
            // TODO Auto-generated method stub

      }
      public void onTextChanged(CharSequence arg0, int arg1, int arg2, int
arg3) {
            // TODO Auto-generated method stub

         }
}

S2.java :

package kmn.Third;

import    android.app.Activity;
import    android.content.Intent;
import    android.graphics.Color;
import    android.os.Bundle;
import    android.view.View;
import    android.view.ViewGroup.LayoutParams;
import    android.widget.Button;
import    android.widget.LinearLayout;
import    android.widget.TextView;

public class S2 extends Activity
{
    /**@author Y@@D */
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
537‐ JVIMS ‐MCA                                                      [ Page 10 of 89 ]

 
                                                                    SL-MC( 650017)

Name:  Keval.M.Nagaria                                   Enrollment No. : 095370693050
 
        Intent i= getIntent();
        //Toast.makeText(this,"Welcome",Toast.LENGTH_LONG).show();
        String txte=i.getStringExtra("txte");
        TextView tv=new TextView(this);
        Button btnBack = new Button(this);
        btnBack.setText("Back");
        tv.setText("Welcome "+txte+" !");
        tv.setTextColor(Color.rgb(255, 255, 100));
        tv.setTextSize(25);
        LinearLayout ll = new LinearLayout(this);
        ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.addView(tv);
        ll.addView(btnBack);
        setContentView(ll);

         btnBack.setOnClickListener(new Button.OnClickListener()
         {
             public void onClick(View v)
             {
                   //setContentView(R.layout.main);
                   finish();
             }
         });
    }
}


Exercise : 4
Create and Login application as above . On successful login , open browser with
any URL.


Screen Shot:




537‐ JVIMS ‐MCA                                                        [ Page 11 of 89 ]

 
                                     SL-MC( 650017)

Name:  Keval.M.Nagaria    Enrollment No. : 095370693050
 




                                                             




537‐ JVIMS ‐MCA                         [ Page 12 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
XML :

main.xml :

<?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"
    >
    <RelativeLayout android:layout_width="match_parent"
android:id="@+id/relativeLayout1" android:layout_height="match_parent"
android:background="@color/bgcolor">
        <TextView android:layout_height="wrap_content"
android:id="@+id/textView1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content" android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" android:layout_marginTop="33dp"
android:text="UserName :"></TextView>
        <EditText android:layout_height="wrap_content"
android:inputType="textPersonName" android:layout_width="wrap_content"
android:layout_below="@+id/textView1" android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" android:id="@+id/txtusername"
android:hint="Enter User Name">
            <requestFocus></requestFocus>
        </EditText>
        <TextView android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content" android:layout_below="@+id/txtusername"
android:layout_alignParentLeft="true" android:layout_marginTop="14dp"
android:text="Password :"></TextView>
        <EditText android:layout_height="wrap_content"
android:inputType="textPassword" android:layout_width="wrap_content"
android:layout_below="@+id/textView2" android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" android:id="@+id/txtpassword"
android:hint="Enter Password"></EditText>
        <Button android:layout_height="wrap_content"
android:textSize="20px" android:text="Login Me"
android:layout_width="wrap_content" android:layout_centerVertical="true"
android:layout_alignParentLeft="true" android:layout_marginLeft="88dp"
android:enabled="false" android:id="@+id/btnlogin"></Button>
    </RelativeLayout>
</LinearLayout>




537‐ JVIMS ‐MCA                                                  [ Page 13 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
JAVA :

FourthActivity.java :

package kmn.Fourth;

import   android.app.Activity;
import   android.content.Intent;
import   android.net.Uri;
import   android.os.Bundle;
import   android.text.Editable;
import   android.text.TextWatcher;
import   android.view.View;
import   android.view.View.OnClickListener;
import   android.widget.Button;
import   android.widget.EditText;

public class FourthActivity extends Activity implements
OnClickListener,TextWatcher
{
    /** @author Y@@D */
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EditText username = (EditText)findViewById(R.id.txtusername);
        EditText password = (EditText)findViewById(R.id.txtpassword);
        username.addTextChangedListener(this);
        password.addTextChangedListener(this);
        Button login = (Button)findViewById(R.id.btnlogin);
        login.setOnClickListener(this);
    }
    public void onClick(View v)
    {
      Intent i= new Intent("android.intent.action.VIEW");
            i.setData(Uri.parse("http://www.kevalnagaria.blogspot.com"));
            startActivity(i);
    }
    public void afterTextChanged(Editable s)
    {
      EditText e = (EditText)findViewById(R.id.txtusername);
      EditText p = (EditText)findViewById(R.id.txtpassword);
      Button b = (Button)findViewById(R.id.btnlogin);
      if(e.getText().toString().equals("keval") &&
p.getText().toString().equals("nagaria"))
      {
            b.setEnabled(true);
      }
      else
      {
            b.setEnabled(false);
      }
    }
      public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                  int arg3) {
            // TODO Auto-generated method stub

         }

537‐ JVIMS ‐MCA                                                  [ Page 14 of 89 ]

 
                                                                    SL-MC( 650017)

Name:  Keval.M.Nagaria                                   Enrollment No. : 095370693050
 
      public void onTextChanged(CharSequence arg0, int arg1, int arg2, int
arg3) {
            // TODO Auto-generated method stub

       }
}

Exercise : 5
Create an application that will pass some number to the next screen , and on the
next screen that number of items should be display in the list.


Screen Shot:




                                                                                            




537‐ JVIMS ‐MCA                                                        [ Page 15 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




                                                                                      

XML :

main.xml :

<?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"
    >
    <RelativeLayout android:id="@+id/relativeLayout1"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/bgcolor">
        <TextView
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/textView1" android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" android:layout_marginTop="40dp"
android:text="Enter No Of Item Display On Next Screen"></TextView>
        <EditText android:inputType="number"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_below="@+id/textView1" android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" android:hint="Enter No Of Item"
android:id="@+id/txtitem">
            <requestFocus></requestFocus>
        </EditText>
        <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/txtitem"
android:layout_centerHorizontal="true" android:id="@+id/btnnext"
android:text="Add Item To Next Screen"></Button>
537‐ JVIMS ‐MCA                                                  [ Page 16 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
    </RelativeLayout>
</LinearLayout>


main1.xml :

<?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:background="@color/bgcolor" android:id="@layout/main1">
    <TextView android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content" android:id="@+id/textView2"
android:text="No Of Item Entered Are As follows"></TextView>
    <ListView android:layout_height="wrap_content"
android:layout_width="match_parent" android:id="@+id/@android:id/list"
android:longClickable="true" android:fastScrollEnabled="false"></ListView>
</LinearLayout>


JAVA :

FifthActivity.java :

package kmn.Fifth;

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

public class FifthActivity extends Activity implements OnClickListener
{
    /** @author Y@@D */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b = (Button)findViewById(R.id.btnnext);
        b.setOnClickListener(this);
    }
    public void onClick(View v)
    {
      Intent i = new Intent(this,S2.class);
      EditText item = (EditText)findViewById(R.id.txtitem);
      i.putExtra("item", item.getText().toString());
      startActivity(i);
    }
}




537‐ JVIMS ‐MCA                                                  [ Page 17 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
S2.java :

package kmn.Fifth;

import java.util.ArrayList;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class S2 extends ListActivity
{
    /** @author Y@@D */
      ArrayList<String> arr=new ArrayList<String>();
      ArrayAdapter<String> a;
      int i=0;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);
        a = new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 ,arr);
        setListAdapter(a);
        for(i=1; i<= Integer.parseInt(getIntent().getStringExtra("item"));
i++)
        {
            arr.add("Item : "+i);
        }
        //Toast.makeText(this, "Welcome", Toast.LENGTH_LONG).show();
    }
}




537‐ JVIMS ‐MCA                                                  [ Page 18 of 89 ]

 
                                                                     SL-MC( 650017)

Name:  Keval.M.Nagaria                                    Enrollment No. : 095370693050
 
Exercise : 6
Understand resource folders :
a. Create spinner with strings taken from resource folder(res >> value folder).
b. On changing spinner value, change image.


Screen Shot:




XML :

main.xml :

<?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:background="@color/bgcolor" android:weightSum="1">
    <RelativeLayout android:layout_width="match_parent"
android:id="@+id/relativeLayout1" android:layout_height="match_parent">
        <Spinner android:id="@+id/spinner1"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_alignParentTop="true" android:layout_alignParentLeft="true"
android:layout_marginTop="42dp" android:layout_alignParentRight="true"
android:entries="@array/Spiner"></Spinner>
        <ImageView android:id="@+id/imageView1"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:src="@drawable/keval1" android:layout_below="@+id/spinner1"

537‐ JVIMS ‐MCA                                                          [ Page 19 of 89 ]

 
                                                                SL-MC( 650017)

Name:  Keval.M.Nagaria                               Enrollment No. : 095370693050
 
android:layout_alignParentLeft="true"
android:layout_marginTop="14dp"></ImageView>
    </RelativeLayout>
</LinearLayout>


JAVA :

SixActivity.java :

package kmn.Six;

import   android.app.Activity;
import   android.os.Bundle;
import   android.view.View;
import   android.widget.AdapterView;
import   android.widget.ImageView;
import   android.widget.Spinner;
import   android.widget.Toast;
import   android.widget.AdapterView.OnItemSelectedListener;

public class SixActivity extends Activity implements OnItemSelectedListener
{
    /** @author Y@@D */

         Integer[] imageIDs =
         {
               R.drawable.keval1,
               R.drawable.keval2,
               R.drawable.keval3,
               R.drawable.keval4,
               R.drawable.keval5
         };

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Spinner s = (Spinner)findViewById(R.id.spinner1);
        s.setOnItemSelectedListener(this);
    }
      public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                  long arg3)
      {
            Toast.makeText(this, "Selected Item is = "+
arg0.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            ImageView i = (ImageView)findViewById(R.id.imageView1);
            i.setImageResource(imageIDs[arg2]);
      }
      public void onNothingSelected(AdapterView<?> arg0)
      {

         }
}




537‐ JVIMS ‐MCA                                                    [ Page 20 of 89 ]

 
                                                                     SL-MC( 650017)

Name:  Keval.M.Nagaria                                    Enrollment No. : 095370693050
 


Exercise : 7
Understand Menu option.
a. Create an application that will change color of the screen, based on selected
options from the menu.


Screen Shot:




XML :

main.xml :

<?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:weightSum="1">
    <RelativeLayout android:id="@+id/relativeLayout1"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:layout_weight="1.09"
android:background="@color/bgcolor"></RelativeLayout>
</LinearLayout>




537‐ JVIMS ‐MCA                                                         [ Page 21 of 89 ]

 
                                                                   SL-MC( 650017)

Name:  Keval.M.Nagaria                                  Enrollment No. : 095370693050
 
JAVA :

SeventhActivity.java :

package kmn.Seventh;

import   android.app.Activity;
import   android.graphics.Color;
import   android.os.Bundle;
import   android.view.Menu;
import   android.view.MenuItem;
import   android.widget.RelativeLayout;

public class SeventhActivity extends Activity
{
    /** @author Y@@D */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public boolean onCreateOptionsMenu(Menu menu)
    {
      super.onCreateOptionsMenu(menu);
      CreateMenu(menu);
      return true;
    }
    public boolean onOptionsItemSelected(MenuItem item)
    {
      return MenuChoice(item);
    }
    private void CreateMenu(Menu menu)
    {
      MenuItem mnu1 = menu.add(0, 0, 0, "Red");
      {
            mnu1.setAlphabeticShortcut('r');
            mnu1.setIcon(R.drawable.icon);
      }
      MenuItem mnu2 = menu.add(0, 1, 0, "Green");
      {
            mnu2.setAlphabeticShortcut('g');
            mnu2.setIcon(R.drawable.icon);
      }
      MenuItem mnu3 = menu.add(0, 2, 0, "White");
      {
            mnu3.setAlphabeticShortcut('w');
            mnu3.setIcon(R.drawable.icon);
        }
    }
    private boolean MenuChoice(MenuItem item)
    {
      RelativeLayout l= (RelativeLayout)
findViewById(R.id.relativeLayout1);

         switch (item.getItemId())
         {
               case 0:
                     l.setBackgroundColor(Color.RED);
537‐ JVIMS ‐MCA                                                       [ Page 22 of 89 ]

 
                                                                      SL-MC( 650017)

Name:  Keval.M.Nagaria                                     Enrollment No. : 095370693050
 
                    return true;
              case 1:
                    l.setBackgroundColor(Color.GREEN);
                    return true;
              case 2:
                    l.setBackgroundColor(Color.WHITE);
                    return true;
        }
              return false;
    }
}

Exercise : 8
Create an application that will display toast(Message) on specific interval of time.


Screen Shot:




537‐ JVIMS ‐MCA                                                          [ Page 23 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
XML :

main.xml :

<?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:background="@color/bgcolor">
    <Button android:layout_height="wrap_content"
android:id="@+id/btnfinish" android:layout_width="match_parent"
android:text="Press Me"></Button>
</LinearLayout>


JAVA :

EightActivity.java :

package kmn.Eight;

import   java.util.Timer;
import   java.util.TimerTask;
import   android.app.Activity;
import   android.os.Bundle;
import   android.os.Handler;
import   android.view.View;
import   android.widget.Button;
import   android.widget.Toast;

public class EightActivity extends Activity
{
    /** @author Y@@D */

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final Handler h = new Handler();
        final Runnable r = new Runnable()
        {
            public void run()
            {
                  Toast.makeText(getBaseContext(), "Y@@D",
Toast.LENGTH_SHORT).show();
            }
      };
      Timer t = new Timer();
      t.scheduleAtFixedRate(new TimerTask()
      {
                  public void run()
                  {
                        h.post(r);
                  }
            }, 1000, 5000);
      Button b = (Button)findViewById(R.id.btnfinish);

537‐ JVIMS ‐MCA                                                     [ Page 24 of 89 ]

 
                                                                      SL-MC( 650017)

Name:  Keval.M.Nagaria                                     Enrollment No. : 095370693050
 
        b.setOnClickListener(new View.OnClickListener()
        {
                    public void onClick(View arg0)
                    {
                          finish();

        android.os.Process.killProcess(android.os.Process.myPid());
                    }
              });
    }
}




                                         OR


Exercise : 8
Create an application that will display toast(Message) on specific interval of time.

Screen Shot:




                                                                                              




537‐ JVIMS ‐MCA                                                          [ Page 25 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




XML :

main.xml :

<?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:weightSum="1" android:background="@color/bgcolor">
    <Chronometer android:id="@+id/chronometer1" android:text="Chronometer"
android:layout_height="wrap_content" android:layout_width="match_parent"
android:layout_weight="0.05" android:visibility="invisible"></Chronometer>
    <EditText android:id="@+id/editText1"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:enabled="false">
        <requestFocus></requestFocus>
    </EditText>
</LinearLayout>




537‐ JVIMS ‐MCA                                                  [ Page 26 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
JAVA :

Chronometer.java :

package kmn.Chronometer;

import   android.app.Activity;
import   android.os.Bundle;
import   android.widget.Chronometer;
import   android.widget.Chronometer.OnChronometerTickListener;
import   android.widget.EditText;
import   android.widget.Toast;

public class ChronometerActivity extends Activity
{
    /** @author Y@@D */
    int i=0;
    int Duration=10;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Chronometer chn = (Chronometer)findViewById(R.id.chronometer1);
        chn.start();
        chn.setOnChronometerTickListener(new OnChronometerTickListener()
        {
                  public void onChronometerTick(Chronometer arg0)
                  {
                        EditText txt =
(EditText)findViewById(R.id.editText1);
                        txt.setText("Message Will Be Display After
["+(Duration-(i+1))+"] Seconds");
                        i++;
                        if(i>=Duration)
                        {
                              Toast.makeText(ChronometerActivity.this,
"Message"+(i/10), 10000).show();
                              Duration+=10;
                        }
                  }
            });
    }
}




537‐ JVIMS ‐MCA                                                     [ Page 27 of 89 ]

 
                                                                      SL-MC( 650017)

Name:  Keval.M.Nagaria                                     Enrollment No. : 095370693050
 
Exercise : 9
Create a background application that will open activity on specific time.


Screen Shot:




537‐ JVIMS ‐MCA                                                          [ Page 28 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




XML :

main.xml :

<?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"
    >
    <RelativeLayout android:id="@+id/relativeLayout1"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/bgcolor">
        <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button1"
android:layout_alignParentTop="true" android:layout_centerHorizontal="true"
android:layout_marginTop="180dp" android:text="Start Service"></Button>
        <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/button2"
android:layout_below="@+id/button1" android:layout_alignLeft="@+id/button1"
android:layout_marginTop="18dp" android:text="Stop Service"></Button>
        <TextView android:id="@+id/textView1"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content" android:text="BG Service Demo"
android:layout_alignParentTop="true" android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"></TextView>
    </RelativeLayout>
</LinearLayout>


537‐ JVIMS ‐MCA                                                  [ Page 29 of 89 ]

 
                                                                SL-MC( 650017)

Name:  Keval.M.Nagaria                               Enrollment No. : 095370693050
 
JAVA :

MyService.java

package kmn.Nine;

import    kmn.servicedemo.R;
import    android.app.Service;
import    android.content.Intent;
import    android.media.MediaPlayer;
import    android.os.IBinder;
import    android.util.Log;
import    android.widget.Toast;

public class MyService extends Service
{
      /** @author Y@@D */
      private static final String TAG = "MyService";
      MediaPlayer player;

         public IBinder onBind(Intent intent)
         {
               return null;
         }

      public void onCreate()
      {
            Toast.makeText(this, "My Service Created",
Toast.LENGTH_LONG).show();
            Log.d(TAG, "onCreate");

              player = MediaPlayer.create(this, R.raw.braincandy);
              player.setLooping(false); // Set looping
         }

      public void onDestroy()
      {
            Toast.makeText(this, "My Service Stopped",
Toast.LENGTH_LONG).show();
            Log.d(TAG, "onDestroy");
            player.stop();
      }

      public void onStart(Intent intent, int startid)
      {
            Toast.makeText(this, "My Service Started",
Toast.LENGTH_LONG).show();
            Log.d(TAG, "onStart");
            player.start();
      }
}




537‐ JVIMS ‐MCA                                                    [ Page 30 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
Nine.java

package kmn.Nine;

import   kmn.servicedemo.R;
import   android.app.Activity;
import   android.content.Intent;
import   android.os.Bundle;
import   android.util.Log;
import   android.view.View;
import   android.view.View.OnClickListener;
import   android.widget.Button;

public class Nine extends Activity implements OnClickListener
{
    /** @author Y@@D */
    private static final String TAG = "ServicesDemo";
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button start = (Button)findViewById(R.id.button1);
        Button stop = (Button)findViewById(R.id.button2);
        start.setOnClickListener(this);
        stop.setOnClickListener(this);
    }

         public void onClick(View v)
         {
               if(v.getId()==R.id.button1)
               {
                     Log.d(TAG, "onClick: starting srvice");
                     startService(new Intent(this, MyService.class));
                     //break;
               }
               if(v.getId()==R.id.button2)
               {
                     Log.d(TAG, "onClick: stopping srvice");
                     stopService(new Intent(this, MyService.class));
                     //break;
               }
         }
}




537‐ JVIMS ‐MCA                                                     [ Page 31 of 89 ]

 
                                                                        SL-MC( 650017)

Name:  Keval.M.Nagaria                                       Enrollment No. : 095370693050
 
Exercise : 10
Create an application that will have spinner with list of animation names. On
selecting animation name , that animation should affect on the images displayed
below.


Screen Shot:




                                                                                                




537‐ JVIMS ‐MCA                                                            [ Page 32 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




XML :

main.xml :

<?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"
    >
    <RelativeLayout android:id="@+id/relativeLayout1"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/bgcolor">
        <Spinner android:id="@+id/spinner1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentTop="true" android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:entries="@array/Animation"></Spinner>
        <ImageView android:layout_width="wrap_content"
android:src="@drawable/icon" android:layout_height="wrap_content"
android:id="@+id/imageView1" android:layout_centerVertical="true"
android:layout_centerHorizontal="true"></ImageView>
    </RelativeLayout>
</LinearLayout>




537‐ JVIMS ‐MCA                                                  [ Page 33 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
~> in this problem we make “anim” folder to res. Directory and
create an xml file like following:

alpha.xml :

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
       <alpha
             android:fromAlpha="0"
             android:toAlpha="1.0"
             android:fillAfter="true"
             android:duration="7000"
       />
</set>

rotate.xml :

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate
       android:fromDegrees="0"
       android:toDegrees="-360"
       android:pivotX="50%"
       android:pivotY="50%"
       android:duration="7000"
    />
</set>

scale.xml :

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
       <scale
             android:pivotX="50%"
             android:pivotY="50%"
             android:fromXScale="1.0"
             android:fromYScale="1.0"
             android:toXScale="2.0"
             android:toYScale="2.0"
             android:duration="2500"
       />
</set>

spin.xml :

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
  <rotate
  android:fromDegrees="0"
  android:toDegrees="360"
  android:duration="2000"
  android:pivotX="50%"
  android:pivotY="50%"
  android:repeatCount="infinite"
  />
</set>


537‐ JVIMS ‐MCA                                                  [ Page 34 of 89 ]

 
                                                                SL-MC( 650017)

Name:  Keval.M.Nagaria                               Enrollment No. : 095370693050
 
translate.xml :

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
       <translate
             android:fromXDelta="110"
             android:toXDelta="-120"
             android:duration="4000"
             android:fillAfter="true"
             android:fromYDelta="190"
             android:toYDelta="0"
       />
</set>

JAVA :

TenActivity.java :

package kmn.Ten;

import   android.app.Activity;
import   android.os.Bundle;
import   android.view.View;
import   android.view.animation.Animation;
import   android.view.animation.AnimationUtils;
import   android.widget.AdapterView;
import   android.widget.AdapterView.OnItemSelectedListener;
import   android.widget.ImageView;
import   android.widget.Spinner;

public class TenActivity extends Activity implements OnItemSelectedListener
{
    /** @author Y@@D */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Spinner s = (Spinner)findViewById(R.id.spinner1);
        s.setOnItemSelectedListener(this);
    }

      public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                  long arg3)
      {
            ImageView i = (ImageView)findViewById(R.id.imageView1);
            if(arg3==1)
            {
                  Animation a = AnimationUtils.loadAnimation(this,
R.anim.alpha);
                  i.startAnimation(a);
            }
            if(arg3==2)
            {
                  Animation a = AnimationUtils.loadAnimation(this,
R.anim.rotate);
                  i.startAnimation(a);
            }
            if(arg3==3)
537‐ JVIMS ‐MCA                                                    [ Page 35 of 89 ]

 
                                                                  SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
              {
                      Animation a = AnimationUtils.loadAnimation(this,
R.anim.scale);
                   i.startAnimation(a);
            }
            if(arg3==4)
            {
                   Animation a = AnimationUtils.loadAnimation(this,
R.anim.spin);
                   i.startAnimation(a);
            }
            if(arg3==5)
            {
                   Animation a = AnimationUtils.loadAnimation(this,
R.anim.translate);
                   i.startAnimation(a);
            }
      }

       public void onNothingSelected(AdapterView<?> arg0)
       {

       }
}




537‐ JVIMS ‐MCA                                                      [ Page 36 of 89 ]

 
                                                                        SL-MC( 650017)

Name:  Keval.M.Nagaria                                       Enrollment No. : 095370693050
 
Exercise : 11
Understanding of UI :
a. Create an UI such that , one screen have list of all the types of cars.
b. On selecting of any car name, next screen should show Car details like : name ,
launched date ,company name, images(using gallery) if available, show different
colors in which it is available.


Screen Shot:




537‐ JVIMS ‐MCA                                                            [ Page 37 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




XML :

main.xml :

<?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:background="@color/bgcolor">
    <ListView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/lv"
    android:entries="@array/carname"
    />
</LinearLayout>


Main1.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:background="@color/bgcolor">

  <TableLayout android:orientation="vertical" android:gravity="center"
android:layout_width="fill_parent" android:layout_height="wrap_content">


537‐ JVIMS ‐MCA                                                  [ Page 38 of 89 ]

 
                                                                SL-MC( 650017)

Name:  Keval.M.Nagaria                               Enrollment No. : 095370693050
 
      <TableRow android:layout_width="fill_parent"
android:layout_height="wrap_content">
      <Gallery android:id="@+id/examplegallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></Gallery>
      </TableRow >

      <TableRow android:layout_width="fill_parent"
android:layout_height="wrap_content">
      <TextView android:id="@+id/tv"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  />
      </TableRow>
  </TableLayout>



</LinearLayout>




JAVA :

ElevenActivity.java :

package kmn.Eleven;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ElevenActivity extends Activity implements OnItemClickListener
{
    /** @author Y@@D */
    ListView lv;
      @Override
    public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        lv=(ListView) findViewById(R.id.lv);
        lv.setClickable(true);
        lv.setOnItemClickListener(this);
    }

      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
      {
            try
            {
                  Integer itn=Integer.valueOf(arg2);
                  String ext=itn.toString();

537‐ JVIMS ‐MCA                                                    [ Page 39 of 89 ]

 
                                                                   SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
                      Intent i = new Intent(this,CarInfo.class);
                      i.putExtra("CarPos", ext);
                      startActivity(i);
            }
            catch(Exception e)
            {
                  Toast.makeText(this, e.getMessage()+"         OnItemClick",
Toast.LENGTH_LONG).show();
            }
      }
}

CarInfo.java

package kmn.Eleven;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

public class CarInfo extends Activity
{
      /** @author Y@@D */
      TextView tv;
      private Gallery gallery;
      @Override
      public void onCreate(Bundle savedInstanceState)
       {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main1);

              tv=(TextView) findViewById(R.id.tv);
              Intent i=this.getIntent();
              String str =i.getStringExtra("CarPos");
              gallery = (Gallery) findViewById(R.id.examplegallery);
              gallery.setAdapter(new AddImgAdp(this,str));
              if(str.equals("0"))
              {
                  tv.setText("Name:Maruti Suzuki 800"+"\n"+"Launched
Date:1/3/1987"+"\n"+"Company Name:Maruti Suzuki"+"\nColors
Available:\nWhite\nBlue\nRed\nLight Yellow");
              }
              else if(str.equals("1"))
              {
                  tv.setText("Name:Hyundai Accent Executive"+"\n"+"Launched
Date:15/10/2010"+"\n"+"Company Name:Hyundai"+"\nColors
Available:\nGray\nOcean Blue\nMidnight Black\nMaganta Blue");
              }
              else if(str.equals("2"))
              {



537‐ JVIMS ‐MCA                                                      [ Page 40 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
                   tv.setText("Name:Chevrolet Beat"+"\n"+"Launched
Date:11/11/2011"+"\n"+"Company Name:Chevrolet"+"\nColors
Available:\nMidnight Black\nAmazon Green\nRoyal Gold\nSport Red");
              }
              else
              {
                   tv.setText("No car available");
              }
       }
}
class AddImgAdp extends BaseAdapter
{
      int GalItemBg;
      private Context cont;
      String positionLast;
      private Integer[] Imgidb = {R.drawable.b1, R.drawable.b2,
R.drawable.b3, R.drawable.b4};
      private Integer[] Imgidh = {R.drawable.h1, R.drawable.h2,
R.drawable.h3, R.drawable.h4};
      private Integer[] Imgidm = {R.drawable.m1, R.drawable.m2,
R.drawable.m3, R.drawable.m4};

      public AddImgAdp(Context c,String pos)
      {
      cont = c;
      positionLast=pos;
      TypedArray typArray =
c.obtainStyledAttributes(R.styleable.GalleryTheme);
      GalItemBg =
typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackgrou
nd, 0);

       typArray.recycle();
       }

       public int getCount()
       {
       if(positionLast.equals("0"))
       {
             return Imgidm.length;
       }
       else if(positionLast.equals("1"))
       {
             return Imgidh.length;
       }
       else if(positionLast.equals("2"))
       {
             return Imgidb.length;
       }
       else
       {
             return Imgidm.length;
       }
       }

       public Object getItem(int position) {
       return position;
       }


537‐ JVIMS ‐MCA                                                  [ Page 41 of 89 ]

 
                                                               SL-MC( 650017)

Name:  Keval.M.Nagaria                              Enrollment No. : 095370693050
 
       public long getItemId(int position) {
       return position;
       }

       public View getView(int position, View convertView, ViewGroup parent)
       {
       ImageView imgView = new ImageView(cont);
       if(positionLast.equals("0"))
       {
             imgView.setImageResource(Imgidm[position]);
       }
       else if(positionLast.equals("1"))
       {
             imgView.setImageResource(Imgidh[position]);
       }
       else if(positionLast.equals("2"))
       {
             imgView.setImageResource(Imgidb[position]);
       }
       else
       {
             imgView.setImageResource(Imgidm[position]);
       }
       // Fixing width & height for image to display
       imgView.setLayoutParams(new Gallery.LayoutParams(200, 200));
       imgView.setScaleType(ImageView.ScaleType.FIT_XY);
       imgView.setBackgroundResource(GalItemBg);
       return imgView;
       }
}




537‐ JVIMS ‐MCA                                                   [ Page 42 of 89 ]

 
                                                                   SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
Exercise : 12
Understanding content providers and permissions:
a. Read phonebook contacts using content providers and display in list.


Screen Shot:




XML :

main.xml :

<?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"
    >
    <ListView android:id="@+id/listView1"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/bgcolor"></ListView>
</LinearLayout>




537‐ JVIMS ‐MCA                                                       [ Page 43 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
JAVA :

TwelveActivity.java :

package kmn.Twelve;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class TwelveActivity extends Activity
{
    /** @author Y@@D */
      private ArrayList<String> list;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        int j=0;
        Cursor
c=getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null,null,null);
        list= new ArrayList<String>();
        while(c.moveToNext())
        {
            int nameindex=c.getColumnIndex(PhoneLookup.DISPLAY_NAME);
            String name=c.getString(nameindex);
            list.add(name);
            Log.d("Contacts:",name);
        }
        ListView l=(ListView)findViewById(R.id.listView1);
        ArrayAdapter<String> aa=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
        l.setAdapter(aa);
    }
}




537‐ JVIMS ‐MCA                                                  [ Page 44 of 89 ]

 
                                                                    SL-MC( 650017)

Name:  Keval.M.Nagaria                                  Enrollment No. : 095370693050
 
Exercise : 13
Read messages from the mobile and display it on the screen.


Screen Shot:




XML :

main.xml :

<?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">
</LinearLayout>




537‐ JVIMS ‐MCA                                                        [ Page 45 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
JAVA :

ThirteenActivity.java :

package kmn.Thirteen;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

public class ThirteenActivity extends Activity
{
      /** @author Y@@D */
      public void onCreate(Bundle savedInstanceState)
      {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            TextView view = new TextView(this);
            Uri uriSMS = Uri.parse("content://sms/inbox");
            Cursor c = getContentResolver().query(uriSMS, null, null,
null,null);
            String sms = "";
            while (c.moveToNext())
            {
                sms += "From :" + c.getString(2) + " : " +
c.getString(11)+"\n";
            }
            view.setText(sms);
            view.setBackgroundColor(Color.BLUE);
            view.setTextColor(Color.WHITE);
            setContentView(view);
      }
}




537‐ JVIMS ‐MCA                                                  [ Page 46 of 89 ]

 
                                                                     SL-MC( 650017)

Name:  Keval.M.Nagaria                                    Enrollment No. : 095370693050
 
Exercise : 14
Create an application to call specific entered number by user in the EditText


Screen Shot:




537‐ JVIMS ‐MCA                                                          [ Page 47 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




XML :

main.xml :

<?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:gravity="center" android:background="@color/bgcolor">
    <TableLayout android:layout_height="wrap_content"
android:id="@+id/tableLayout1" android:layout_width="match_parent">
        <TableRow android:id="@+id/tableRow1"
android:layout_width="wrap_content" android:layout_height="wrap_content">
            <TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textView1"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Phone #"></TextView>
            <EditText android:layout_height="wrap_content"
android:layout_width="240dp" android:inputType="phone"
android:id="@+id/txtnumber" android:hint="eg. 9998622949"></EditText>
        </TableRow>
    </TableLayout>
    <Button android:layout_height="wrap_content" android:id="@+id/btncall"
android:layout_width="wrap_content" android:text="Make Call"></Button>
</LinearLayout>




537‐ JVIMS ‐MCA                                                  [ Page 48 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
JAVA :

FourteenActivity.java :

package kmn.Fourteen;

import   android.app.Activity;
import   android.content.Intent;
import   android.net.Uri;
import   android.os.Bundle;
import   android.view.View;
import   android.widget.Button;
import   android.widget.EditText;

public class FourteenActivity extends Activity
{
    /** @author Y@@D */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button call = (Button)findViewById(R.id.btncall);
        call.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                  EditText txt = (EditText)findViewById(R.id.txtnumber);
                  Uri uri=Uri.parse("tel:"+txt.getText().toString());
                        Intent intent=new Intent(Intent.ACTION_CALL, uri);
                        startActivity(intent);
            }
        });
    }
}




537‐ JVIMS ‐MCA                                                  [ Page 49 of 89 ]

 
                                                                      SL-MC( 650017)

Name:  Keval.M.Nagaria                                     Enrollment No. : 095370693050
 
Exercise : 15
Create an application that will create database with table of User credential.


Screen Shot:




XML :

main.xml :

<?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:background="@color/bgcolor">
</LinearLayout>


JAVA :

FifteenActivity.java :

apackage kmn.Fifteen;

import   android.app.Activity;
import   android.database.Cursor;
import   android.database.sqlite.SQLiteDatabase;
import   android.graphics.Color;

537‐ JVIMS ‐MCA                                                          [ Page 50 of 89 ]

 
                                                                  SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class FifteenActivity extends Activity
{
      /** @author Y@@D */
      @Override
      public void onCreate(Bundle savedInstanceState)
      {
            super.onCreate(savedInstanceState);

              SQLiteDatabase myDB= null;
              String TableName = "myTable";

              String Data="";

            /* Create a Database. */
            try
            {
                  myDB = this.openOrCreateDatabase("DatabaseName",
MODE_PRIVATE, null);

                  /* Create a Table in the Database. */
                  myDB.execSQL("CREATE TABLE IF NOT EXISTS " + TableName +
" (Field1 VARCHAR, Field2 INT(3));");
                  /* Insert data to a Table*/
                  myDB.execSQL("INSERT INTO " + TableName + " (Field1,
Field2)" + " VALUES ('Y@@D', 22);");
                  /*retrieve data from database */
                  Cursor c = myDB.rawQuery("SELECT * FROM " + TableName ,
null);

                      int Column1 = c.getColumnIndex("Field1");
                      int Column2 = c.getColumnIndex("Field2");

                      // Check if our result was valid.
                      c.moveToFirst();
                      if (c != null)
                      {
                            // Loop through all Results
                            do
                            {
                                 String Name = c.getString(Column1);
                                 int Age = c.getInt(Column2);
                                 Data =Data +Name+"/"+Age+"\n";
                            }while(c.moveToNext());
                      }
                      TextView tv = new TextView(this);
                      tv.setBackgroundColor(Color.BLUE);
                      tv.setTextColor(Color.WHITE);
                      tv.setText(Data);
                      setContentView(tv);
              }
              catch(Exception e)
              {
                    Log.e("Error", "Error", e);
              }
              finally

537‐ JVIMS ‐MCA                                                      [ Page 51 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
              {
                      if (myDB != null)
                            myDB.close();
              }
         }
}

DropTb.java :

package kmn.Fifteen;

import   android.app.Activity;
import   android.database.sqlite.SQLiteDatabase;
import   android.os.Bundle;
import   android.util.Log;

public class DropTb extends Activity
{

         /** @author Y@@D */
         @Override
         public void onCreate(Bundle savedInstanceState)
         {
               super.onCreate(savedInstanceState);

              SQLiteDatabase myDB= null;
              String TableName = "myTable";

            /**
            * Create a Database.
            * */
            try
            {
                  myDB = this.openOrCreateDatabase("DatabaseName",
MODE_PRIVATE, null);
                  myDB.execSQL("DROP TABLE IF EXISTS "+TableName+";");

              }
              catch(Exception e)
              {
                    Log.e("Error", "Error", e);
              }
              finally
              {
                    if (myDB != null)
                          myDB.close();
              }
         }
}




537‐ JVIMS ‐MCA                                                     [ Page 52 of 89 ]

 
                                                                      SL-MC( 650017)

Name:  Keval.M.Nagaria                                     Enrollment No. : 095370693050
 
Exercise : 16
Create an application to read file from asset folder and copy it in memory card.


Screen Shot:




XML :

s1.xml :

<?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:weightSum="1" android:background="@color/bgcolor">
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content" android:text="TextView"
android:layout_weight="0.17" android:layout_width="match_parent"
android:id="@+id/showTxt"></TextView>
</LinearLayout>




537‐ JVIMS ‐MCA                                                          [ Page 53 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
JAVA :

SixteenActivity.java :

package kmn.Sixteen;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class SixteenActivity extends Activity
{
      /** @author Y@@D */

       FileOutputStream fos ;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.s1);

         try
               {
                  String destPath = "/sdcard/kmn.txt";
                  File f = new File(destPath);
                  if (!f.exists())
                  {
                        CopyDB(
getBaseContext().getAssets().open("file.txt"),new
FileOutputStream(destPath));
                  }
                  Intent i = new
Intent(SixteenActivity.this,screen1.class);
            startActivity(i);
            }
            catch (Exception e)
            {
                  Toast.makeText(SixteenActivity.this, " "+e.toString(),
Toast.LENGTH_LONG).show();
            }
      }
    public void CopyDB(InputStream inputStream,OutputStream
outputStream)throws IOException
    {
            //---copy 1K bytes at a time---
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0)
            {
                  outputStream.write(buffer, 0, length);
            }
            inputStream.close();
            outputStream.close();
537‐ JVIMS ‐MCA                                                     [ Page 54 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
    }
}

screen1.java :

package kmn.Sixteen;

import   java.io.DataInputStream;
import   java.io.File;
import   java.io.FileInputStream;
import   android.app.Activity;
import   android.os.Bundle;
import   android.os.Environment;
import   android.widget.TextView;
import   android.widget.Toast;

public class screen1 extends Activity
{
      /** @author Y@@D */

      public void onCreate(Bundle b)
      {
            super.onCreate(b);
            setContentView(R.layout.s1);
            try
            {
                  File fileDir = Environment.getExternalStorageDirectory();
            File directory = new File(fileDir.getAbsolutePath());
            File file = new File(directory , "kmn.txt");
            FileInputStream fis = new FileInputStream(file);
                  String str = null;
                  StringBuffer sbuffer = new StringBuffer();
                  DataInputStream dataio = new DataInputStream(fis);
                  while((str = dataio.readLine()) != null)
                  {
                        sbuffer.append(str + "\n");
                  }
                  TextView txt=(TextView)findViewById(R.id.showTxt);
                  txt.setText(sbuffer);
            }
            catch (Exception e)
            {
                  Toast.makeText(this, " "+e.toString(),
Toast.LENGTH_LONG).show();
            }
      }
}




537‐ JVIMS ‐MCA                                                  [ Page 55 of 89 ]

 
                                                                       SL-MC( 650017)

Name:  Keval.M.Nagaria                                      Enrollment No. : 095370693050
 
Exercise : 17
Create an application that will play a media file from the memory card.


Screen Shot:




XML :

main.xml :

<?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:weightSum="1">
<RelativeLayout android:id="@+id/relativeLayout1"
android:layout_width="match_parent" android:background="@color/bgcolor"
android:layout_height="match_parent">
    <Button android:id="@+id/button2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/button1"
android:layout_alignLeft="@+id/button1" android:layout_marginTop="16dp"
android:text="stop"></Button>
    <MediaController android:id="@+id/mediaController1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_above="@+id/button1" android:layout_centerHorizontal="true"
android:layout_marginBottom="21dp"></MediaController>
    <Button android:layout_width="wrap_content" android:id="@+id/button1"
android:text="start" android:layout_height="wrap_content"
537‐ JVIMS ‐MCA                                                           [ Page 56 of 89 ]

 
                                                                  SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
android:layout_alignParentTop="true" android:layout_centerHorizontal="true"
android:layout_marginTop="148dp"></Button>
</RelativeLayout>
</LinearLayout>


JAVA :

SeventeenActivity.java :

package kmn.Seventeen;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class SeventeenActivity extends Activity
{
      /** @author Y@@D */

      MediaPlayer player=null;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button start=(Button)findViewById(R.id.button1);
        Button stop=(Button)findViewById(R.id.button2);
        getSystemService(Context.AUDIO_SERVICE);
        start.setOnClickListener(new View.OnClickListener() {

                      public void onClick(View arg0)
                      {

                           try
                           {
                                  player=null;
                                  player=new MediaPlayer();

                              String
audioFilePath="/sdcard/braincandy.mp3";
                              player.setDataSource(audioFilePath);
                              player.prepare();
                              player.start();
                        }
                        catch(Exception e)
                        {

       Toast.makeText(SeventeenActivity.this,""+e,Toast.LENGTH_LONG).show();

                           }
                      }
             });
         stop.setOnClickListener(new View.OnClickListener()
         {
                   public void onClick(View arg0)
537‐ JVIMS ‐MCA                                                      [ Page 57 of 89 ]

 
                                                                    SL-MC( 650017)

Name:  Keval.M.Nagaria                                   Enrollment No. : 095370693050
 
               {
                         player.stop();
                         }
               });
     }
}

~>step to add a mp3 file to sdcard

1)goto the ddms

2)click on push button

3)and select the given mp3 file.



Enjoy.................



Exercise : 18
Create an application to make Insert , update , Delete and retrieve operation on
the database.


Screen Shot:




537‐ JVIMS ‐MCA                                                        [ Page 58 of 89 ]

 
                                     SL-MC( 650017)

Name:  Keval.M.Nagaria    Enrollment No. : 095370693050
 




537‐ JVIMS ‐MCA                         [ Page 59 of 89 ]

 
                                     SL-MC( 650017)

Name:  Keval.M.Nagaria    Enrollment No. : 095370693050
 




537‐ JVIMS ‐MCA                         [ Page 60 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
XML :

main.xml :

<?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:id="@+id/LL">
<RelativeLayout android:layout_width="match_parent"
android:id="@+id/relativeLayout1" android:layout_height="match_parent"
android:background="@color/bgcolor">
    <TextView android:layout_width="wrap_content"
android:id="@+id/textView1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" android:text="Name:"></TextView>
    <EditText android:inputType="textPersonName"
android:layout_height="wrap_content" android:layout_below="@+id/textView1"
android:layout_alignParentLeft="true" android:layout_width="match_parent"
android:id="@+id/txtName">
        <requestFocus></requestFocus>
    </EditText>
    <TextView android:layout_width="wrap_content"
android:id="@+id/textView2"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content" android:layout_below="@+id/txtName"
android:layout_alignParentLeft="true" android:layout_marginTop="24dp"
android:text="Age:"></TextView>
    <EditText android:inputType="phone"
android:layout_height="wrap_content" android:layout_below="@+id/textView2"
android:layout_alignParentLeft="true" android:layout_width="match_parent"
android:id="@+id/txtAge"></EditText>
    <Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_below="@+id/txtAge"
android:layout_toRightOf="@+id/textView1" android:layout_marginTop="24dp"
android:id="@+id/btnInsert" android:text="Insert"></Button>
    <Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/btnInsert"
android:layout_toRightOf="@+id/btnInsert" android:layout_marginLeft="26dp"
android:id="@+id/btnClear" android:text="Clear"></Button>
</RelativeLayout>

</LinearLayout>




537‐ JVIMS ‐MCA                                                  [ Page 61 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
search.xml :

<?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:id="@+id/LL" android:weightSum="1"
android:background="@color/bgcolor">
<RelativeLayout android:layout_width="match_parent" android:gravity="left"
android:layout_height="wrap_content" android:id="@+id/rlSearch">
    <TextView android:layout_width="wrap_content"
android:id="@+id/textView1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_alignParentLeft="true" android:text="Search by ID
:"></TextView>
    <EditText android:inputType="textPersonName"
android:layout_height="wrap_content" android:layout_below="@+id/textView1"
android:id="@+id/txtSearch" android:layout_width="250dp"></EditText>
    <Button android:layout_width="wrap_content" android:text="Search"
android:id="@+id/btnSearch" android:layout_height="wrap_content"
android:layout_alignTop="@+id/txtSearch"
android:layout_toRightOf="@+id/txtSearch"></Button>
</RelativeLayout>

<RelativeLayout android:layout_height="312dp"
android:gravity="center_vertical" android:layout_width="match_parent"
android:layout_gravity="center_vertical" android:id="@+id/rlRecord">
    <TextView android:layout_width="wrap_content" android:text="Name:"
android:id="@+id/textView1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
android:layout_height="wrap_content"></TextView>
    <EditText android:layout_width="match_parent" android:id="@+id/txtName"
android:inputType="textPersonName" android:layout_below="@+id/textView1"
android:layout_alignParentLeft="true" android:layout_height="wrap_content">
        <requestFocus></requestFocus>
    </EditText>
    <EditText android:layout_width="match_parent" android:id="@+id/txtAge"
android:inputType="phone" android:layout_below="@+id/textView2"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"></EditText>
    <Button android:text="Delete" android:id="@+id/btnDelete"
android:layout_height="wrap_content" android:layout_alignTop="@+id/btnEdit"
android:layout_toRightOf="@+id/btnEdit"
android:layout_width="160dp"></Button>
    <Button android:layout_width="160dp" android:text="Edit"
android:id="@+id/btnEdit" android:layout_height="wrap_content"
android:layout_below="@+id/txtAge" android:layout_alignParentLeft="true"
android:layout_marginTop="30dp"></Button>
    <TextView android:layout_width="wrap_content" android:text="Age:"
android:id="@+id/textView2"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content" android:layout_below="@+id/txtName"
android:layout_alignParentLeft="true"
android:layout_marginTop="14dp"></TextView>
</RelativeLayout></LinearLayout>
537‐ JVIMS ‐MCA                                                  [ Page 62 of 89 ]

 
                                                                  SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
JAVA :

EighteenActivity.java :

package kmn.Eighteen;

import   java.util.Locale;
import   android.app.Activity;
import   android.content.Intent;
import   android.database.sqlite.SQLiteDatabase;
import   android.os.Bundle;
import   android.view.Menu;
import   android.view.MenuItem;
import   android.view.View;
import   android.view.View.OnClickListener;
import   android.widget.Button;
import   android.widget.EditText;
import   android.widget.Toast;

public class EighteenActivity extends Activity
{
    /** @author Y@@D * */
      SQLiteDatabase db;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        createDB();
      //do insert
            Button btnInsert=(Button)findViewById(R.id.btnInsert );
        btnInsert.setOnClickListener(new OnClickListener()
        {

                      public void onClick(View arg0)
                      {

                           insert();
                      }
             });
         Button btnClear=(Button)findViewById(R.id.btnClear );
         btnClear.setOnClickListener(new OnClickListener()
         {
                   public void onClick(View arg0)
                   {
                         clear();
                   }
             });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
      super.onCreateOptionsMenu(menu);
      CreateMenu(menu);
      return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
537‐ JVIMS ‐MCA                                                      [ Page 63 of 89 ]

 
                                                                  SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
        return MenuChoice(item);
    }

    private void CreateMenu(Menu menu)
    {
      MenuItem mnu1 = menu.add(0, 0, 0, "Insert");
      {
            mnu1.setAlphabeticShortcut('i');

        }
        MenuItem mnu2 = menu.add(0, 1, 1, "Search");
        {
              mnu2.setAlphabeticShortcut('s');

        }
        MenuItem mnu3 = menu.add(0, 2, 2, "Delete");
        {
              mnu3.setAlphabeticShortcut('d');
              //mnu3.setIcon(R.drawable.icon);
        }
        MenuItem mnu4 = menu.add(0, 3, 3, "View");
        {
              mnu4.setAlphabeticShortcut('d');
              //mnu3.setIcon(R.drawable.icon);
        }
     }
    private boolean MenuChoice(MenuItem item)
    {
       Intent intent=new Intent();
       switch (item.getItemId())
       {
             case 0:
                   insert();
                   return true;
             case 1:
                    intent.setClass(EighteenActivity.this, Search.class);
                         startActivity(intent);
                         return true;
             case 2:
       //          intent.setClass(E18Activity.this, SelectRecord.class);
                         startActivity(intent);
                   return true;

              case 3:
                    intent.setClass(EighteenActivity.this, ViewRecord.class);
                    startActivity(intent);
              return true;

        }
        return false;
    }
    public void createDB()
      {
            db=openOrCreateDatabase("Student.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(1);


537‐ JVIMS ‐MCA                                                      [ Page 64 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
            String sql="create table if not exists Stud(id INTEGER PRIMARY
KEY AUTOINCREMENT, name TEXT, age INTEGER)";
            db.execSQL(sql);
      }
      public void insert()
      {
             EditText txtName=(EditText)findViewById(R.id.txtName);
             EditText txtAge=(EditText)findViewById(R.id.txtAge);
             if(txtName.getText().toString().equals(""))
             {
                   Toast.makeText(EighteenActivity.this, "Enter Name.",
Toast.LENGTH_SHORT).show();
           }
             else if (txtAge.getText().toString().equals(""))
             {
                   Toast.makeText(EighteenActivity.this, "Enter Age.",
Toast.LENGTH_SHORT).show();
             }
             else
             {

                   String sql="insert into Stud(name,age) values('"+
txtName.getText().toString() +"',"+txtAge.getText().toString()+")";
                   db.execSQL(sql);
                   clear();
                   Toast.makeText(EighteenActivity.this, "Record
Successfully Inserted.", Toast.LENGTH_SHORT).show();
             }
      }
      public void clear()
      {
            EditText txtName=(EditText)findViewById(R.id.txtName);
             EditText txtAge=(EditText)findViewById(R.id.txtAge);
            txtName.setText("");
            txtAge.setText("");

              txtName.clearFocus();
              txtAge.clearFocus();
              txtName.requestFocus();


      }
      @Override
    public void onDestroy()
      {
            super.onDestroy();
            db.close();
      }
}




537‐ JVIMS ‐MCA                                                  [ Page 65 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
Search.java :

package kmn.Eighteen;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
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;
import android.widget.RelativeLayout;
import android.widget.Toast;
/** @author Y@@D * */
public class Search extends Activity
{
      SQLiteDatabase db;
      EditText txtSearch;
      EditText txtName;
      EditText txtAge;
      Button btnEdit;
      Button btnDelete;
      RelativeLayout rlRecord;
    RelativeLayout rlSearch;
    String recID="0";
      @Override
    public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);

         setContentView(R.layout.search);

         db=openOrCreateDatabase("Student.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);


       txtName = (EditText)findViewById(R.id.txtName);
       txtAge = (EditText)findViewById(R.id.txtAge);
         txtSearch = (EditText)findViewById(R.id.txtSearch);
         btnEdit=(Button)findViewById(R.id.btnEdit);
         btnDelete=(Button)findViewById(R.id.btnDelete);

         txtSearch.requestFocus();
         txtName.setEnabled(false);
         txtAge.setEnabled(false);
         btnEdit.setEnabled(false);
         btnDelete.setEnabled(false);

        Button btnSearch=(Button)findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(new OnClickListener()
        {
                  public void onClick(View arg0) {
                        if (txtSearch.getText().toString().equals(""))
                         {
                               Toast.makeText(Search.this, "Enter value.",
Toast.LENGTH_SHORT).show();
                         }
537‐ JVIMS ‐MCA                                                     [ Page 66 of 89 ]

 
                                                                   SL-MC( 650017)

Name:  Keval.M.Nagaria                                  Enrollment No. : 095370693050
 
                          else
                          {
                                  searchRecord();
                          }
                   }
             });
         //---------------Edit/update---------------------------------
         final Button btnEdit=(Button)findViewById(R.id.btnEdit);
         btnEdit.setOnClickListener(new OnClickListener()
         {
                   public void onClick(View arg0)
                   {

                          if (btnEdit.getText().toString().equals("Edit"))
                           {
                                 btnEdit.setText("Update");
                                 txtName.setEnabled(true);
                             txtAge.setEnabled(true);

                              txtName.requestFocus();

                           btnDelete.setEnabled(false);

                          }
                          else
                          {
                                  txtName.setEnabled(false);
                              txtAge.setEnabled(false);

                           btnDelete.setEnabled(true);

                               btnEdit.setText("Edit");
                               String sql="update Stud set
name='"+txtName.getText().toString()+"',
age="+txtAge.getText().toString()+" where id="+recID;
                             db.execSQL(sql);
                             Toast.makeText(Search.this, " Record Updated
Successfully" , Toast.LENGTH_LONG).show();
                         }
                  }
            });
        //------------------------Delete ---------------------------

         btnDelete.setOnClickListener(new OnClickListener()
         {

                  public void onClick(View arg0)
                  {
                        // TODO Auto-generated method stub
                        AlertDialog.Builder alertbox = new
AlertDialog.Builder(arg0.getContext());

      alertbox.setIcon(android.R.drawable.ic_dialog_alert);
                        alertbox.setTitle("Confirm");
                        alertbox.setMessage("Are You Sure? You want to
delete this record");
                        alertbox.setPositiveButton("Delete", new
DialogInterface.OnClickListener()
                        {

537‐ JVIMS ‐MCA                                                       [ Page 67 of 89 ]

 
                                                                     SL-MC( 650017)

Name:  Keval.M.Nagaria                                    Enrollment No. : 095370693050
 
                                    public void onClick(DialogInterface arg0, int
arg1)
                                    {
                                           // TODO Auto-generated method stub
                                           String sql="Delete from Stud where
id="+recID;
                                  db.execSQL(sql);
                                    Toast.makeText(getApplicationContext(),
"Record Deleted", Toast.LENGTH_LONG).show();
                                    //clear old search result
                                    txtSearch.setText("");
                                    txtName.setText("");
                                    txtAge.setText("");
                                    txtSearch.requestFocus();
                              }
                         });
                  alertbox.setNegativeButton(" Cancel ", new
DialogInterface.OnClickListener()
                  {
                              public void onClick(DialogInterface arg0, int
arg1)
                              {
                                    // TODO Auto-generated method stub

                                    }
                              });
                        alertbox.show();
                    }
              });
    }
      public void searchRecord()
      {
            try
        {
            txtSearch = (EditText)findViewById(R.id.txtSearch);
            txtName = (EditText)findViewById(R.id.txtName);
            txtAge = (EditText)findViewById(R.id.txtAge);
            Cursor c=db.rawQuery("select id,name,age from Stud where id="+
txtSearch.getText().toString(), null);
                if(c.getCount()>0)
            {
                   c.moveToNext();
                   recID= c.getString(0);
                   txtName.setText( c.getString(1));
                 txtAge.setText(c.getString(2));
                 btnEdit.setEnabled(true);
                 btnDelete.setEnabled(true);
            }
            else
            {
                  Toast.makeText(this, "No Record Found" ,
Toast.LENGTH_LONG).show();
            }
        }
        catch(Exception e)
        {
            Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();
        }
      }

537‐ JVIMS ‐MCA                                                         [ Page 68 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
       public void onDestroy()
       {
             super.onDestroy();
             db.close();
       }
}


ViewRecord.java :

package kmn.Eighteen;
/** @author Y@@D **/
import java.util.ArrayList;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;
 public class ViewRecord extends ListActivity
 {
      SQLiteDatabase db;
      @Override
    public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        try
        {
            db=openOrCreateDatabase("Student.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
            Cursor c=db.rawQuery("select id,name,age from Stud", null);
                ArrayList<String> list = new ArrayList<String>();

              int count=c.getCount();

            if(c.getCount()>0)
            {
                   while(c.moveToNext())
                   {
                     list.add(c.getString(0)+" , "+c.getString(1)+" ,
"+c.getString(2));
                   }
                   c.close();
                   Toast.makeText(this,"Total Records: "+count,
Toast.LENGTH_LONG).show();
                   ArrayAdapter<String> adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list);
                   getListView().setAdapter(adapter);
            }
            else
            {
                   Toast.makeText(this, "No Record Found" ,
Toast.LENGTH_LONG).show();
            }
        }
        catch(Exception e)
        {
            Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();
537‐ JVIMS ‐MCA                                                  [ Page 69 of 89 ]

 
                                                                      SL-MC( 650017)

Name:  Keval.M.Nagaria                                     Enrollment No. : 095370693050
 
         }
    }
        public void onDestroy()
        {
              super.onDestroy();
              db.close();
        }
}


Exercise : 19
Create an application to read file from the sdcard and display that file content to
the screen.


Screen Shot:




537‐ JVIMS ‐MCA                                                          [ Page 70 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




XML :

main.xml :

<?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:weightSum="1">
    <RelativeLayout android:id="@+id/relativeLayout1"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/bgcolor">
        <TextView android:id="@+id/textView1"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" android:text="Write Text In Below
TextBox"></TextView>
        <EditText android:layout_width="wrap_content"
android:inputType="textMultiLine" android:layout_below="@+id/textView1"
android:layout_marginTop="26dp" android:layout_alignParentRight="true"
android:layout_alignParentLeft="true" android:id="@+id/txt"
android:layout_height="220dp">
            <requestFocus></requestFocus>
        </EditText>
        <Button android:id="@+id/read" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="3.Read SD File"
android:layout_above="@+id/close"
android:layout_alignLeft="@+id/clear"></Button>

537‐ JVIMS ‐MCA                                                  [ Page 71 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
        <Button android:id="@+id/clear" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="2.Clear Screen"
android:layout_above="@+id/read"
android:layout_centerHorizontal="true"></Button>
        <Button android:id="@+id/write" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="1.Write SD File"
android:layout_above="@+id/clear"
android:layout_alignLeft="@+id/clear"></Button>
        <Button android:id="@+id/close" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="4.Close"
android:layout_alignParentBottom="true" android:layout_marginBottom="18dp"
android:layout_alignLeft="@+id/read"
android:layout_alignRight="@+id/read"></Button>
    </RelativeLayout>
</LinearLayout>


JAVA :

NineteenActivity.java :

package kmn.Ninteen;

import   java.io.BufferedReader;
import   java.io.File;
import   java.io.FileInputStream;
import   java.io.FileOutputStream;
import   java.io.InputStreamReader;
import   java.io.OutputStreamWriter;

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 NineteenActivity extends Activity
{
    /** @author Y@@D */
    EditText txtData;
      Button btnWriteSDFile;
      Button btnReadSDFile;
      Button btnClearScreen;
      Button btnClose;
    public void onCreate(Bundle savedInstanceState)
    {

         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         txtData = (EditText) findViewById(R.id.txt);
         btnWriteSDFile = (Button)findViewById(R.id.write);
         btnWriteSDFile.setOnClickListener(new OnClickListener()
         {
                   public void onClick(View V)
                   {
                         try
                         {
537‐ JVIMS ‐MCA                                                     [ Page 72 of 89 ]

 
                                                                  SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
                                  File myFile = new
File("/sdcard/mysdfile.txt");
                                  myFile.createNewFile();
                                  Toast.makeText(NineteenActivity.this,
"Created",1000);
                                  FileOutputStream fOut = new
FileOutputStream(myFile);
                                  OutputStreamWriter myOutWriter = new
OutputStreamWriter(fOut);
                              myOutWriter.append(txtData.getText());
                              myOutWriter.close();
                              fOut.close();
                              Toast.makeText(getBaseContext(),"Done writing
SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
                        }
                        catch (Exception e)
                        {
                              Toast.makeText(getBaseContext(),
e.getMessage(),Toast.LENGTH_SHORT).show();
                        }
                  }
            });
        btnReadSDFile = (Button) findViewById(R.id.read);
            btnReadSDFile.setOnClickListener(new OnClickListener() {

            public void onClick(View v)
            {
                  // write on SD card file data in the text box
            try
            {
                  File myFile = new File("/sdcard/mysdfile.txt");
                  FileInputStream fIn = new FileInputStream(myFile);
                  BufferedReader myReader = new BufferedReader(new
InputStreamReader(fIn));
                  String aDataRow = "";
                  String aBuffer = "";
                  while ((aDataRow = myReader.readLine()) != null) {
                        aBuffer += aDataRow + "\n";
                  }
                  txtData.setText(aBuffer);
                  myReader.close();
                  Toast.makeText(getBaseContext(),"Done reading SD
'mysdfile.txt'",Toast.LENGTH_SHORT).show();
            }
            catch (Exception e)
            {
                  Toast.makeText(getBaseContext(),
e.getMessage(),Toast.LENGTH_SHORT).show();
            }
            }// onClick
            }); // btnReadSDFile

              btnClearScreen = (Button) findViewById(R.id.clear);
              btnClearScreen.setOnClickListener(new OnClickListener()
              {

                      public void onClick(View v)
                      {
                            // clear text box

537‐ JVIMS ‐MCA                                                      [ Page 73 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
                           txtData.setText("");
                     }
               }); // btnClearScreen

               btnClose = (Button) findViewById(R.id.close);
               btnClose.setOnClickListener(new OnClickListener()
               {
                     public void onClick(View v)
                     {
                           // clear text box
                           finish();
                     }
               }); // btnClose
     }
}

*Step to create SDcard...

~>First goto command promt.

~>Then gotofollowing directory.

    C:\Android\android-sdk_r11-windows\android-sdk-windows\tools

~> Then type following command.

    mksdcard 1024M sdcard.iso

~>It will create sdcard.iso file in tools folder.

~>Finally Now go to AVD mananger using eclipse and edit avd or create
new

at that time attach sdcard.iso file to create sdcard using browse option.



Thanks...............................

Y@@D




537‐ JVIMS ‐MCA                                                     [ Page 74 of 89 ]

 
                                                                     SL-MC( 650017)

Name:  Keval.M.Nagaria                                    Enrollment No. : 095370693050
 
Exercise : 20
Create an application to draw line on the screen as user drag his finger.


Screen Shot:




XML :

main.xml :

<?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"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>




537‐ JVIMS ‐MCA                                                          [ Page 75 of 89 ]

 
                                                               SL-MC( 650017)

Name:  Keval.M.Nagaria                              Enrollment No. : 095370693050
 
JAVA :

TwentyActivity.java :

package kmn.Twenty;
import android.app.Activity;
import android.os.Bundle;
public class TwentyActivity extends Activity
{
      /** @author Y@@D */
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
            super.onCreate(savedInstanceState);
            setContentView(new ExploreTouchEvent(this, null));
      }
}


ExploreTouchEvent.java :

package kmn.Twenty;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/** @author Y@@D */
public class ExploreTouchEvent extends View
{
      private Paint paint = new Paint();
      private Path path = new Path();
      public ExploreTouchEvent(Context context, AttributeSet attrs)
      {
            super(context, attrs);
            paint.setAntiAlias(true);
            paint.setStrokeWidth(6f);
            paint.setColor(Color.WHITE);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
      }
      protected void onDraw(Canvas canvas)
      {
            canvas.drawColor(Color.BLUE);
            canvas.drawPath(path, paint);

       }
       public boolean onTouchEvent(MotionEvent event)
       {
             float eventX = event.getX();
             float eventY = event.getY();
             switch (event.getAction())
             {
                   case MotionEvent.ACTION_DOWN:
                         path.moveTo(eventX, eventY);

537‐ JVIMS ‐MCA                                                   [ Page 76 of 89 ]

 
                                                                  SL-MC( 650017)

Name:  Keval.M.Nagaria                                 Enrollment No. : 095370693050
 
                            return true;
                      case MotionEvent.ACTION_MOVE:
                            path.lineTo(eventX, eventY);
                            break;
                      case MotionEvent.ACTION_UP:
                            // nothing to do
                            break;
                      default:
                            return false;
              }
              // Schedules a repaint.
              invalidate();
              return true;
       }
}

Exercise : 21
Create an application to send message between two emulators.


Screen Shot:




537‐ JVIMS ‐MCA                                                      [ Page 77 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
XML :

main.xml :

<?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:background="@color/bgcolor">
        <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Enter the phone number of recipient"
        />
    <EditText
        android:id="@+id/txtPhoneNo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Message"
        />
    <EditText
        android:id="@+id/txtMessage"
        android:layout_width="fill_parent"
        android:layout_height="150px"
        android:gravity="top"
        />
    <Button
        android:id="@+id/btnSendSMS"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />
</LinearLayout>


JAVA :

TwentyOneActivity.java :

package kmn.TwentyOne;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


537‐ JVIMS ‐MCA                                                  [ Page 78 of 89 ]

 
                                                               SL-MC( 650017)

Name:  Keval.M.Nagaria                              Enrollment No. : 095370693050
 
public class TwentyOneActivity extends Activity
{
      /** @author Y@@D */
      Button btnSendSMS;
      EditText txtPhoneNo;
      EditText txtMessage;

      //@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);

         /*
         Intent sendIntent = new Intent(Intent.ACTION_VIEW);
         sendIntent.putExtra("sms_body", "Content of the SMS goes here...");
         sendIntent.setType("vnd.android-dir/mms-sms");
         startActivity(sendIntent);
         */

         btnSendSMS.setOnClickListener(new View.OnClickListener()
         {
             public void onClick(View v)
             {
                   String phoneNo = txtPhoneNo.getText().toString();
                   String message = txtMessage.getText().toString();

                if (phoneNo.length()>0 && message.length()>0)
                    sendSMS(phoneNo, message);
                else
                  Toast.makeText(getBaseContext(),"Please enter both phone
number and message.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //---sends a SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {

       String SENT = "SMS_SENT";
       String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new
Intent(SENT),0);


        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
Intent(DELIVERED), 0);

         //---when the SMS has been sent---
         registerReceiver(new BroadcastReceiver()
         {
             //    @Override
                   public void onReceive(Context arg0, Intent arg1)
                   {

537‐ JVIMS ‐MCA                                                   [ Page 79 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
                        switch (getResultCode())
                        {
                            case Activity.RESULT_OK:
                                  Toast.makeText(getBaseContext(), "SMS
sent",Toast.LENGTH_SHORT).show();
                                  break;
                            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                                  Toast.makeText(getBaseContext(), "Generic
failure",   Toast.LENGTH_SHORT).show();
                                  break;
                            case SmsManager.RESULT_ERROR_NO_SERVICE:
                                  Toast.makeText(getBaseContext(), "No
service",Toast.LENGTH_SHORT).show();
                                  break;
                            case SmsManager.RESULT_ERROR_NULL_PDU:
                                  Toast.makeText(getBaseContext(), "Null
PDU",Toast.LENGTH_SHORT).show();
                                  break;
                            case SmsManager.RESULT_ERROR_RADIO_OFF:
                                  Toast.makeText(getBaseContext(), "Radio
off",Toast.LENGTH_SHORT).show();
                                  break;
                        }
                  }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver()
        {
                  //@Override
                  public void onReceive(Context arg0, Intent arg1)
                  {
                        switch (getResultCode())
                        {
                            case Activity.RESULT_OK:
                                  Toast.makeText(getBaseContext(), "SMS
delivered", Toast.LENGTH_SHORT).show();
                                  break;
                            case Activity.RESULT_CANCELED:
                                  Toast.makeText(getBaseContext(), "SMS not
delivered", Toast.LENGTH_SHORT).show();
                                  break;
                        }
                  }
        }, new IntentFilter(DELIVERED));

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI,
deliveredPI);
    }
}




537‐ JVIMS ‐MCA                                                   [ Page 80 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
SmsReceiver.java :

package kmn.TwentyOne;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver
{
      /** @author Y@@D */
      //@Override
      public void onReceive(Context context, Intent intent)
      {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }
      }
}

Step to Creat two emulator and send sms.



1)goto windows->Android SDK and AVD Mangaer.

2)creat two emulator and give the different name.

3)start emulator by clicking start button

3)now enter the emulator number to phone number and send it.



Note:- see the give OutPut Image..



Enjoy.........
537‐ JVIMS ‐MCA                                                  [ Page 81 of 89 ]

 
                                                                       SL-MC( 650017)

Name:  Keval.M.Nagaria                                      Enrollment No. : 095370693050
 
Exercise : 22
Create an application to take picture using native application.


Screen Shot:




XML :

main.xml :

<?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"
    >
</LinearLayout>




537‐ JVIMS ‐MCA                                                           [ Page 82 of 89 ]

 
                                                                    SL-MC( 650017)

Name:  Keval.M.Nagaria                                   Enrollment No. : 095370693050
 
JAVA :

TwentyTwoActivity.java :

package kmn.TwentyTwo;

import   java.io.File;
import   android.app.Activity;
import   android.content.Intent;
import   android.net.Uri;
import   android.os.Bundle;
import   android.os.Environment;
import   android.provider.MediaStore;

public class TwentyTwoActivity extends Activity
{
    /** @author Y@@D */
    String path;
      @Override
    public void onCreate(Bundle savedInstanceState)
      {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        path = Environment.getExternalStorageDirectory() + File.separator +
"make_machine_example.jpg";
        File file = new File( path );
        Uri outputFileUri = Uri.fromFile( file );

        Intent intent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
        intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

         startActivityForResult( intent, 0 );

    }
}

Exercise : 23
Create an application to pick up any image from the native application gallery and
display it on the screen.


Screen Shot:




537‐ JVIMS ‐MCA                                                        [ Page 83 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 




XML :

main.xml :

<?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:background="@color/bgcolor">
<TextView android:layout_height="wrap_content" android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/txtTitle" android:layout_width="match_parent"></TextView>
<ImageView android:src="@drawable/icon" android:id="@+id/myImg"
android:layout_width="match_parent"
android:layout_height="456dp"></ImageView>
</LinearLayout>




537‐ JVIMS ‐MCA                                                  [ Page 84 of 89 ]

 
                                                                 SL-MC( 650017)

Name:  Keval.M.Nagaria                                Enrollment No. : 095370693050
 
JAVA :

TwentythreeActivity.java :

package kmn.Twentythree;
import java.io.File;
import java.io.FileInputStream;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class TwentythreeActivity extends Activity
{
      /** @author Y@@D **/
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

         setContentView(R.layout.main);
         try
         {

            String[] projection={Media.DISPLAY_NAME, Media.DATA,
Media.SIZE};
            Cursor c=managedQuery(Media.EXTERNAL_CONTENT_URI, projection,
null, null, null);
            ImageView ivImage=(ImageView)findViewById(R.id.myImg);
            File file = null;
            String imgName = null ;

            if(c.getCount()>0)
            {
                  while(c.moveToNext())
                  {
                        file=new File(c.getString(1));      //after
completing loop, it take last image from native Gallery to display.
                        imgName=c.getString(0);
                  }
                  c.close();
                        FileInputStream fis=new FileInputStream(file);
                        byte[] buffer=new byte[fis.available()];
                        fis.read(buffer);
                        Bitmap bm=BitmapFactory.decodeByteArray(buffer, 0,
buffer.length);

                        TextView
txtTitle=(TextView)findViewById(R.id.txtTitle);
                        txtTitle.setText(imgName.toString());
                        ivImage.setImageBitmap(bm);
            }
        }
        catch(Exception e)
537‐ JVIMS ‐MCA                                                     [ Page 85 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
         {
            Toast.makeText(TwentythreeActivity.this, "Error: "+e,
Toast.LENGTH_LONG).show();
        }
    }
}

Step To store images on sdcard and scanning in to the emulator.



1)click on push on file onto the device button

2)now select the iamge an upload it

3)goto the "Dev Tools" on your emulator and click on "Media Scanner".

4)now check your image in "gallery"

5)run your program



Enjoy..........




537‐ JVIMS ‐MCA                                                  [ Page 86 of 89 ]

 
                                                                     SL-MC( 650017)

Name:  Keval.M.Nagaria                                    Enrollment No. : 095370693050
 
Exercise : 24
Create an application to open any URL inside the application and clicking on any
link from that URl should not open Native browser but that URL should open the
same screen.


Screen Shot:




XML :

main.xml :

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:id="@+id/LinearLayout01"
      android:layout_width="fill_parent"
android:layout_height="fill_parent"
      xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:gravity="center"
android:padding="10px" android:background="@color/bgcolor">
       <WebView android:id="@+id/webview"
        android:layout_width="fill_parent"
            android:layout_height="fill_parent"
android:background="@color/bgcolor"/>
</LinearLayout>




537‐ JVIMS ‐MCA                                                          [ Page 87 of 89 ]

 
                                                              SL-MC( 650017)

Name:  Keval.M.Nagaria                             Enrollment No. : 095370693050
 
JAVA :

TwentyFourActivity.java :

package kmn.TwentyFour;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class TwentyFourActivity extends Activity
{     @Override
      public void onCreate(Bundle savedInstanceState)
      {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            WebView webView = (WebView) findViewById(R.id.webview);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.loadUrl("http://www.gtumcappt.blogspot.com");
            webView.setWebViewClient(new HelloWebViewClient());
      }
}

HelloWebViewClient.java :

package kmn.TwentyFour;

import android.webkit.WebView;
import android.webkit.WebViewClient;

public class HelloWebViewClient extends WebViewClient
{     @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url)
      {
            view.loadUrl(url);
            return true;
      }

}




537‐ JVIMS ‐MCA                                                  [ Page 88 of 89 ]

 
                                     SL-MC( 650017)

Name:  Keval.M.Nagaria    Enrollment No. : 095370693050
 




537‐ JVIMS ‐MCA                         [ Page 89 of 89 ]

 

				
DOCUMENT INFO
Shared By:
Stats:
views:105
posted:8/25/2012
language:Latin
pages:89
Description: Android Practical Program Soluation For GTU MCA Student