You are on page 1of 96

RI SHI M S INSTITUTE OF ENGINEERING & TECHNOLOGY

for WOMEN
(Approved by AICTE, New Delhi and Affiliated to JNTUH)
Nizampet Cross Roads, JNTUH Kukatpally Hyderabad – 500085

DEPARTMENT OF INFORMATION TECHNOLOGY

LAB MANUAL

PYTHON PROGRAMMING

B.Tech I YEAR II SEM (R22 REGULATIONS)

ACADEMIC YEAR 2023-24


INDEX

S.NO TOPIC PAGE NO

I List of Experiments ii

II V/M /POs/PSOs/PEOs iv

III Syllabus ix

IV Course Objectives & Course Outcomes xi

i
List of Experiments

Exp. No. Experiment Name Page No.


1. Create an Android application that shows Hello + name of the user and
run it on an emulator.
(b) Create an application that takes the name from a text box and shows
1
hello message along with the
name entered in the text box, when the user clicks the OK button.

222222

Create a screen that has input boxes for User Name, Password, Address,
Gender (radio buttons
for male and female), Age (numeric), Date of Birth (Datepicker), State
(Spinner) and a Submit
22222 2 button. On clicking the submit button, print all the data below the Submit
Button. Use (a) Linear
Layout
(b) Relative Layout and
(c) Grid Layout or Table Layout.

Develop an application that shows names as a list and on selecting a


name it should show the details of the candidate on the next screen with a
“Back” button. If the screen is rotated to landscape mode (width greater
3
than height), then the screen should show list on left fragment and details
on the right fragment instead of the second screen with the back button.
Use Fragment transactions and Rotation event listeners.

Develop an application that uses a menu with 3 options for dialing a number,
opening a website and to send an SMS. On selecting an option, the appropriate
4
action should be invoked using intents.

Develop an application that inserts some notifications into Notification area


and whenever a
5
notification is inserted, it should show a toast with details of the notification.

ii
. Create an application that uses a text file to store usernames and passwords
(tab separated fields and one record per line). When the user submits a login
6 name and password through a screen, the details should be verified with the
text file data and if they match, show a dialog saying that login is successful.
Otherwise, show the dialog with a Login Failed message.

Create a user registration application that stores the user details in a


database table.
7

Create a database and a user table where the details of login names and
8 passwords are stored. Insert some names and passwords initially. Now the
login details entered by the user should be verified with the database and
an appropriate dialog should be shown to the user.

Create an admin application for the user table, which shows all records as a
9 list and the admin can select any record for edit or modify. The results
should be reflected in the table.

Develop an application that shows all contacts of the phone along with
10 details like name, phone number, mobile number etc

11 . Create an application that saves user information like name, age, gender
etc. in shared preference
and retrieves them when the program restarts.

12 Create an alarm that rings every Sunday at 8:00 AM. Modify it to use a
time picker to set alarm time.

iii
RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to JNTUH University, Approved by AICTE)

Department of Information Technology

Vision of the institution:

To be a center of excellence in producing women engineers and scientists who are professionally
competent social leaders to face multi-disciplinary global environment by imparting quality technical
education, values and ethics through innovation methods of teaching and learning.

Mission of the institution:

 To promote women technocrats capable enough to resolve the problems faced by the society using
the knowledge imparted.
 To prepare self-reliant women engineering for technological growth of the nation and society by
laying strong theoretical foundation accompanied by wide practical training.
 To equip the young women with creative thinking capabilities and empowering them towards
innovation.

iv
RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to JNTUH University, Approved by AICTE)

Department of Information Technology

Vision & Mission of Department

Vision of the department

To empower women by providing cutting-edge technology to female technocrats in the fields of


Information Technology, allowing them to develop into competent engineers and entrepreneurs.

Mission of the department

 Adopting creative techniques to nurture and strengthen the core skill of Computer Science.
 Introduce students to the most recent technological advancements.
 Impart quality education, improve the research, entrepreneurial, and employability skills of women
technocrats.
 Instil professional ethics and a sense of social responsibility in students.
 Strengthen the Industry-Academia interface, which will enable graduates to emerge as
academic leaders or inspiring entrepreneurs

v

 RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
 (Affiliated to JNTUH University, Approved by AICTE)

Program outcomes (POs)


1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem Analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to the professional engineering practice.
7. Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
11. Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long Learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.

vi
RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to JNTUH University, Approved by AICTE)

Department of Information Technology

Program specific outcomes (PSOs)

PSO 1: Improve the student's ability to decipher the basic principles and methodology of computer
systems. Improve the students' ability to absorb facts and technical ideas in order to build and
develop software.
PSO 2: The capacity to create novel job routes as an entrepreneur using modern computer languages
and evolving technologies like SDLC, Python, Machine Learning, Social Networks, Cyber
Security, Mobile Apps etc.

vii
RISHI M.S INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Affiliated to JNTUH University, Approved by AICTE)

Department of Information Technology

Program educational objectives (PEOs)

PEO-1: Engineering graduates with excellent fundamental and technical skills will have
successful careers in industry, meeting the needs of Indian and worldwide firms.

PEO-2: With determination, development, self-reliance, leadership, morality, and moral principles,
engineering graduates will become successful entrepreneurs who will leverage employability.

PEO-3: To support personal and organisational progress, engineering graduates will pursue higher
education and engage in lifelong learning.

viii
SYLLABUS
Python Programming Lab
B.TECH I Year II Sem

Week -1:
1.
a) Create an Android application that shows Hello + name of the user and run it on an emulator.
(b) Create an application that takes the name from a text box and shows hello message along
with the
name entered in the text box, when the user clicks the OK button.
Week-2:
2. Create a screen that has input boxes for User Name, Password, Address, Gender (radio buttons
for male and female), Age (numeric), Date of Birth (Datepicker), State (Spinner) and a Submit
button. On clicking the submit button, print all the data below the Submit Button. Use (a) Linear
Layout
(b) Relative Layout and (c) Grid Layout or Table Layout.
Week-3:
3. Develop an application that shows names as a list and on selecting a name it should show the
details of the candidate on the next screen with a “Back” button. If the screen is rotated to landscape
mode (width greater than height), then the screen should show list on left fragment and details on
the right fragment instead of the second screen with the back button. Use Fragment transactions
and Rotation event listeners.

Weeek-4:
4. Develop an application that uses a menu with 3 options for dialing a number, opening a website
and to send an SMS. On selecting an option, the appropriate action should be invoked using intents.
5. Develop an application that inserts some notifications into Notification area and whenever a
notification is inserted, it should show a toast with details of the notification.
Week-5:
6. Create an application that uses a text file to store usernames and passwords (tab separated fields
and one record per line). When the user submits a login name and password through a screen, the
details should be verified with the text file data and if they match, show a dialog saying that login is
successful. Otherwise, show the dialog with a Login Failed message.

ix
7. Create a user registration application that stores the user details in a database table.
8. Create a database and a user table where the details of login names and passwords are stored.
Insert some names and passwords initially. Now the login details entered by the user should be
verified with the database and an appropriate dialog should be shown to the user.
Week-6:
9. Create an admin application for the user table, which shows all records as a list and the admin can
select any record for edit or modify. The results should be reflected in the table.
10. Develop an application that shows all contacts of the phone along with details like name, phone
number, mobile number etc.
11. Create an application that saves user information like name, age, gender etc. in shared preference
and retrieves them when the program restarts.
12. Create an alarm that rings every Sunday at 8:00 AM. Modify it to use a time picker to set alarm time.

TEXT BOOKS:
1. Supercharged Python: Take your code to the next level, Overland
2. Learning Python, Mark Lutz, O'reilly

REFERENCE BOOKS:
1. Python for Data Science, Dr. Mohd. Abdul Hameed, Wiley Publications - 1st Ed. 2021.
2. Python Programming: A Modern Approach, Vamsi Kurama, Pearson
3. Python Programming A Modular Approach with Graphics, Database, Mobile, and
Web Applications, Sheetal Taneja, Naveen Kumar, Pearson
4. Programming with Python, A User’s Book, Michael Dawson, Cengage Learning, India Edition
5. Think Python, Allen Downey, Green Tea Press
6. Core Python Programming, W. Chun, Pearson
7. Introduction to Python, Kenneth A. Lambert, Cengage

x
Course Objectives: To learn
1. Understand the usage of data types, loops and conditional statements and functions.
2. Understand Lists, Dictionaries and Regular expressions in Python.
3. Handle Strings and Files in Python.
4. Learn the implantation of Python modules like Numpy, Plotpy, Turtle

Course Outcomes: After learning the contents of this course the student is able to
CO1. Examine Python syntax and semantics and be fluent in the use of Python flow control
and functions. Demonstrate proficiency in handling Strings and File Systems.
CO2. Create, run and manipulate Python Programs using core data structures like Lists,
Tuples,and Dictionaries.
CO3. Implement exemplary applications related to Numpy, Pandas and matplotlib in Python.

CO - PO MAPPING:

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

Python CO1 3 2 2 2 2 2
Programming
Lab CO2 3 2 3 2 3 3

CO3 3 3 3 3 3 3

CO - PSO MAPPING:

PSO-1 PSO-2
CO1 1 3
CO2 2 3
CO3 2 3

xi
Week 1:
1) a) Create an Android application that shows Hello + name of the user and run it on emulator.
Application Directory Structure

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello +"
android:id="@+id/idtxt" />

12
</LinearLayout>
</RelativeLayout>

MainActivity.java
package com.murali.labexperiment1a;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.idtxt);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String myvar = textView.getText().toString()+"murali";
Toast.makeText(getApplicationContext(),myvar,Toast.LENGTH_SHORT).show();
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.labexperiment1a"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.labexperiment1a.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Input Output Screens

13
Clicking on “Hello+” text… Output as follows

14
1) B) Create an application that takes the name from a text box and shows hello message along
with the name entered in text box, when user clicks OK button.
Application Directory Structure

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="19dp"
android:text="Enter Ur Name :" />
<EditText
android:id="@+id/et"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tv"
android:layout_alignBottom="@+id/tv"
15
android:layout_alignParentRight="true"
android:layout_marginRight="14dp"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/et"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:onClick="onBtnClick"
android:text="Ok" />
<TextView
android:id="@+id/otv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="92dp"
android:text=" " />
</RelativeLayout>

MainActivity.java
package com.murali.labexperiment1b;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
TextView otv;
EditText et;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
otv=(TextView)findViewById(R.id.otv);
et=(EditText)findViewById(R.id.et);
b=(Button)findViewById(R.id.button1);
}
public void onBtnClick(View v){
Editable msg=et.getText();
otv.setText("Hello+"+msg);
}
}

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.labexperiment1b"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.labexperiment1b.MainActivity"
android:label="@string/app_name" >
<intent-filter>

16
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Input Output Screens

Enter your name “murali” in text box

17
After Clicking OK Button

18
Week-2:
2) Create a Screen that has input boxes for User Name, Password, Address, Gender (radio
buttons for male and female), Age (numeric), Date of Birth (Date), State (Spinner) and a
Submit button, print all the data by clicking Submit Button.
a) Linear Layout
Application Directory

19
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:text="Details Form"
android:textSize="25sp"
android:gravity="center"/>
</LinearLayout>
<GridLayout
android:id="@+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"
android:columnCount="2"
android:rowCount="6">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"

20
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="0"
android:text="Name"
android:textSize="20sp"
android:gravity="center"/>
<EditText
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="1"
android:ems="8"
android:inputType="textPersonName" />
<TextView
android:id="@+id/textView2"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="0"
android:text="Password"
android:textSize="20sp"
android:gravity="center" />
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="1"
android:ems="8"
android:inputType="textPassword" >
<requestFocus />
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="0"
android:text="Gender"
android:textSize="20sp"
android:gravity="center" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="1">
<RadioButton
android:id="@+id/male"
android:layout_width="98dp"
android:layout_height="wrap_content"
android:checked="true"
android:text="male" />
<RadioButton
android:id="@+id/female"
android:layout_width="98dp"
android:layout_height="wrap_content"
android:text="female" />
</RadioGroup>
<TextView

21
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="0"
android:text="Password"
android:textSize="20sp"
android:gravity="center" />
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="1"
android:ems="8"
android:inputType="textPassword" >
<requestFocus />
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="0"
android:text="Gender"
android:textSize="20sp"
android:gravity="center" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="1">
<RadioButton
android:id="@+id/male"
android:layout_width="98dp"
android:layout_height="wrap_content"
android:checked="true"
android:text="male" />
<RadioButton
android:id="@+id/female"
android:layout_width="98dp"
android:layout_height="wrap_content"
android:text="female" />
</RadioGroup>
<TextView

android:layout_margin="10dp"
android:layout_row="5"
android:layout_column="1"
android:spinnerMode="dropdown" />
</GridLayout>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Submit" />
</RelativeLayout>
MainActivity.java
package com.murali.labexperiment2a;
import android.os.Bundle;

22
import android.text.Editable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
EditText uname,pwd,age,dob;
RadioGroup rg;
Spinner s;
Button b;
//Editable un,pd,db,st;
//String gender;
//Editable ag;
String un,pd,db,st,gender,ag;
String [] states={"TS","TN","AP","UP","MP"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname=(EditText)findViewById(R.id.username);
pwd=(EditText)findViewById(R.id.password);
rg=(RadioGroup)findViewById(R.id.radioGroup1);

age=(EditText)findViewById(R.id.age);
dob=(EditText)findViewById(R.id.dob);
s=(Spinner)findViewById(R.id.state);
b=(Button)findViewById(R.id.button);
ArrayAdapter adapter= new
ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item,states);
s.setAdapter(adapter);
/*
un=uname.getText();
pd=pwd.getText();
db=dob.getText();
st=(Editable)s.getAdapter();
ag=age.getText(); */
rg.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
switch(arg1){
case R.id.male:
gender="male";
break;
case R.id.female:
gender="female";
break;
}
}
});
//Creating Listener for Button
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Getting the Values from Views(Edittext & Spinner)
un=uname.getText().toString();
pd=pwd.getText().toString();
db=dob.getText().toString();
ag=age.getText().toString();
pd=pwd.getText().toString();
st=s.getSelectedItem().toString();
//Intent For Navigating to Second Activity
Intent i = new
Intent(MainActivity.this,SecondActivity.class);
23
//For Passing the Values to Second Activity
i.putExtra("username_key", un);
i.putExtra("pwd_key",pd);
i.putExtra("gender_key",gender);
i.putExtra("age_key",ag );
i.putExtra("dob_key", db);
i.putExtra("state_key", st);
startActivity(i);
}
});
}
}
SecondActivity.java
package com.murali.labexperiment2a;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.TextView;
public class SecondActivity extends Activity {
TextView t1,t2,t3,t4,t5,t6;
String username,password,gender,age,dob,state;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t1= (TextView) findViewById(R.id.textView1);
t2= (TextView) findViewById(R.id.textView2);
t3= (TextView) findViewById(R.id.textView3);
t4= (TextView) findViewById(R.id.textView4);
t5= (TextView) findViewById(R.id.textView5);
t6= (TextView) findViewById(R.id.textView6);
//Getting the Intent
Intent i = getIntent();
//Getting the Values from First Activity using the Intent received
/*
* i.putExtra("username_key", un);
i.putExtra("pwd_key",pd);
i.putExtra("gender_key",gender);
i.putExtra("age_key",ag );
i.putExtra("dob_key", db);
i.putExtra("state_key", st);

*/
username=i.getStringExtra("username_key");
password=i.getStringExtra("pwd_key");
gender=i.getStringExtra("gender_key");
age=i.getStringExtra("age_key");
dob=i.getStringExtra("dob_key");
state=i.getStringExtra("state_key");
//Setting the Values to Intent
t1.setText(username);
t2.setText(password);
t3.setText(gender);
t4.setText(age);
t5.setText(dob);
t6.setText(state);
}
}
activity_second.xml (Linear Layout)
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.murali.labexperiment2a.SecondActivity"
android:orientation="vertical"
android:gravity="center">
<TextView
24
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView

android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.labexperiment2a"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.labexperiment2a.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"></activity>
</application>
</manifest>

25
Input Output Screens

Enter the details

After Clicking Submit Button (Display output as Linear Layout Format)

26
b) Relative Layout (Just change the code of “activity_second.xml”, Remaining Programs code
as it is)
activity_second.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.murali.labexperiment2b.SecondActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="25dp"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="26dp"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView3"
android:layout_below="@+id/textView3"
android:layout_marginTop="52dp"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"

android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView4"
android:layout_below="@+id/textView4"
android:layout_marginTop="40dp"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/textView5"
android:layout_below="@+id/textView5"
android:layout_marginTop="58dp"
android:textSize="30sp"
android:text="TextView" />
</RelativeLayout>

27
Output Screens
After Clicking Submit Button (Display output as Relative Layout Format)

c) Grid Layout (Just change the code of “activity_second.xml”, Remaining Programs code as
it is)
activity_second.xml
<?xml version="1.0" encoding="UTF-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.murali.labexperiment2c.SecondActivity"
android:columnCount="2"
android:rowCount="3" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="0"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="0"
android:layout_column="1"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="0"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
28
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="1"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="0"
android:textSize="30sp"
android:text="TextView" />
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="2"
android:layout_column="1"
android:textSize="30sp"
android:text="TextView" />
</GridLayout>

Output Screens
After Clicking Submit Button (Display output as Grid Layout Format)

29
a) Table Layout (Just change the code of “activity_second.xml”, Remaining Programs code as
it is)
activity_second.xml
<?xml version="1.0" encoding="UTF-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.murali.labexperiment2d.SecondActivity"
android:stretchColumns="*" >
<TableRow>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
</TableRow>
<TableRoa) Table Layout (Just change the code of “activity_second.xml”, Remaining Programs code as
it is)
activity_second.xml
<?xml version="1.0" encoding="UTF-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.murali.labexperiment2d.SecondActivity"
android:stretchColumns="*" >
<TableRow>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
</TableRow>
<TableRow>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
</TableRow>
30
<TableRow>
<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text="New Text"
android:textSize="30sp"/>
</TableRow>
</TableLayout>

Output Screens
After Clicking Submit Button (Display output as Table Layout Format)

Week-3:
3) Develop an application that shows names as a list and on selecting a name it should show the
details of the candidate on the next screen with a “Back” button. If the screen is rotated to
landscape mode (width greater than height), then the screen should show list on left fragment
and details on right fragment instead of second screen with back button. Use Fragment
transactions and Rotation event listener.
Application Directory Structure

31
activity_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:orientation="vertical" >
<fragment
android:id="@+id/studentnames_list_fragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:name="com.murali.labexperiment3.StudentNamesListFragment"
/>
</LinearLayout>
land\activity_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:orientation="horizontal" >
<fragment
android:id="@+id/studentnames_list_fragment"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:name="com.murali.labexperiment3.StudentNamesListFragment"
/>
<FrameLayout
android:id="@+id/detail_fragment_container"
32
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
>
</FrameLayout>
</LinearLayout>
studentnames_details_activity_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/studentnames_details_fragment_container"
>
</LinearLayout>
studentnames_details_fragment_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/studentnames_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:layout_gravity="center"
android:textColor="@color/blue"
/>
</LinearLayout>
MainActivity.java
package com.murali.labexperiment3;
import
com.murali.labexperiment3.StudentNamesListFragment.ListFragmentItemClickListe
ner;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
public class MainActivity extends Activity implements
ListFragmentItemClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** This method will be executed when the user clicks on an item in the
listview */
@Override
public void onListFragmentItemClick(int position) {
/** Getting the orientation ( Landscape or Portrait ) of the screen
*/
int orientation = getResources().getConfiguration().orientation;
/** Landscape Mode */
if(orientation == Configuration.ORIENTATION_LANDSCAPE ){
/** Getting the fragment manager for fragment related operations
*/
FragmentManager fragmentManager = getFragmentManager();
/** Getting the fragmenttransaction object, which can be used to
add, remove or replace a fragment */
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
/** Getting the existing detailed fragment object, if it already

33
exists.
* The fragment object is retrieved by its tag name
* */
Fragment prevFrag =
fragmentManager.findFragmentByTag("com.murali.labexperiment3.details");
/** Remove the existing detailed fragment object if it exists */
if(prevFrag!=null)
fragmentTransaction.remove(prevFrag);
/** Instantiating the fragment StudentNamesDetailsFragment */
StudentNamesDetailsFragment fragment = new
StudentNamesDetailsFragment();
/** Creating a bundle object to pass the data(the clicked item's
position) from the activity to the fragment */
Bundle b = new Bundle();
/** Setting the data to the bundle object */
b.putInt("position", position);
/** Setting the bundle object to the fragment */
fragment.setArguments(b);
/** Adding the fragment to the fragment transaction */
fragmentTransaction.add(R.id.detail_fragment_container,
fragment,"com.murali.labexperiment3.details");
/** Adding this transaction to backstack */
fragmentTransaction.addToBackStack(null);
/** Making this transaction in effect */
fragmentTransaction.commit();
}else{

/** Portrait Mode or Square mode */


/** Creating an intent object to start the CountryDetailsActivity
*/
Intent intent = new
Intent("com.murali.StudentNamesDetailsActivity");
/** Setting data ( the clicked item's position ) to this intent
*/
intent.putExtra("position", position);
/** Starting the activity by passing the implicit intent */
startActivity(intent);
}
}
}
StudentNames.java
package com.murali.labexperiment3;
public class StudentNames {
/** Array of student names used to display in StudentNamesListFragment
*/
static String name[] = new String[] {
"Rahul",
"Sachin",
"Viru",
"Laxman",
"Rohit",
"Virat",
"Bhumra",
"Murali",
"Mahadev",
"Maanvi",
"Snigdha"
};
}
StudentNamesDetailsActivity.java
package com.murali.labexperiment3;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class StudentNamesDetailsActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
34
/** Setting the layout for this activity */

setContentView(R.layout.studentnames_details_activity_layout);
/** Getting the fragment manager for fragment related operations */
FragmentManager fragmentManager = getFragmentManager();
/** Getting the fragmenttransaction object, which can be used to add,
remove or replace a fragment */
FragmentTransaction fragmentTransacton =
fragmentManager.beginTransaction();
/** Instantiating the fragment StudentNamesDetailsFragment */
StudentNamesDetailsFragment detailsFragment = new
StudentNamesDetailsFragment();
/** Creating a bundle object to pass the data(the clicked item's
position) from the activity to the fragment */
Bundle b = new Bundle();
/** Setting the data to the bundle object from the Intent*/
b.putInt("position", getIntent().getIntExtra("position", 0));
/** Setting the bundle object to the fragment */
detailsFragment.setArguments(b);
/** Adding the fragment to the fragment transaction */
fragmentTransacton.add(R.id.studentnames_details_fragment_container,
detailsFragment);
/** Making this transaction in effect */
fragmentTransacton.commit();
}
}
StudentNamesDetailsFragment.java
package com.murali.labexperiment3;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class StudentNamesDetailsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/** Inflating the layout studentnames_details_fragment_layout to the
view object v */
View v =
inflater.inflate(R.layout.studentnames_details_fragment_layout, null);
/** Getting the textview object of the layout to set the details */
TextView tv = (TextView) v.findViewById(R.id.studentnames_details);
/** Getting the bundle object passed from MainActivity ( in Landscape
mode ) or from
* CountryDetailsActivity ( in Portrait Mode )
* */
Bundle b = getArguments();
/** Getting the clicked item's position and setting corresponding
details in the textview of the detailed fragment */
tv.setText("Details of " + StudentNames.name[b.getInt("position")]);
return v;
}
}

StudentNamesListFragment.java
package com.murali.labexperiment3;
import android.app.Activity;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class StudentNamesListFragment extends ListFragment{
ListFragmentItemClickListener ifaceItemClickListener;
35
/** An interface for defining the callback method */
public interface ListFragmentItemClickListener {
/** This method will be invoked when an item in the ListFragment is
clicked */
void onListFragmentItemClick(int position);
}
/** A callback function, executed when this fragment is attached to an
activity */
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
/** This statement ensures that the hosting activity implements
ListFragmentItemClickListener */
ifaceItemClickListener = (ListFragmentItemClickListener)
activity;
}catch(Exception e){
Toast.makeText(activity.getBaseContext(),
"Exception",Toast.LENGTH_SHORT).show();
}

}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/** Data source for the ListFragment */
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(inflater.getContext(),
android.R.layout.simple_list_item_1, StudentNames.name);
/** Setting the data source to the ListFragment */
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
/** Invokes the implementation of the method onListFragmentItemClick
in the hosting activity */
ifaceItemClickListener.onListFragmentItemClick(position);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.labexperiment3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.labexperiment3.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".StudentNamesDetailsActivity"

android:label="@string/app_name" >
<intent-filter>
<action android:name="com.murali.StudentNamesDetailsActivity"

36
/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Input Output Screens
Clicking on “Sachin” in the Student List on Vertical Input Screen

For that Vertical Output Screen is

Clicking on “Rohit” in the Student List on Horizontal Input Screen

37
For the Horizontal Output Screen is

38
Week-4:
4) Develop an application that uses a menu with 3 options for dialing a number, opening a
website and send an SMS. On selecting an option, the appropriate action should be invoked
using intents.
Application Directory

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="26sp"
android:gravity="center"/>
</RelativeLayout>

res/menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/dialing"
android:title="Dialing a number"/>
<item android:id="@+id/website"
android:title="Opening a WebSite"/>
<item android:id="@+id/sms"
android:title="To send an SMS"/>
39
</menu>

MainActivity.java
package com.murali.labexperiment4aom;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);//Menu Resource, Menu
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.dialing:
//Toast.makeText(getApplicationContext(),"Item 1
Selected",Toast.LENGTH_LONG).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
String num="96xxxxxxx0";
callIntent.setData(Uri.parse("tel:"+num));//change the
number
startActivity(callIntent);
return true;
case R.id.website:
//Toast.makeText(getApplicationContext(),"Item 2
Selected",Toast.LENGTH_LONG).show();
Intent websiteIntent=new Intent(Intent.ACTION_VIEW,
Uri.parse("https://murali4ruall.blogspot.in/"));
startActivity(websiteIntent);
return true;
case R.id.sms:
// Toast.makeText(getApplicationContext(),"Item 3
Selected",Toast.LENGTH_LONG).show();
//Intent smsIntent = new Intent(Intent.ACTION_MAIN);
//smsIntent.addCategory(Intent.CATEGORY_APP_MESSAGING);
//startActivity(smsIntent);
//Getting intent and PendingIntent instance
Intent intent=new
Intent(getApplicationContext(),MainActivity.class);
PendingIntent
pi=PendingIntent.getActivity(getApplicationContext(), 0, intent,0);
//Get the SmsManager instance and call the sendTextMessage
method to send message
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage("96xxxxxxx0", null, "murali from
android app", pi,null);
Toast.makeText(getApplicationContext(), "Message Sent
successfully!",
Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
40
}
}
}

method to send message


SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage("96xxxxxxx0", null, "murali from
android app", pi,null);
Toast.makeText(getApplicationContext(), "Message Sent
successfully!",
Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Input Output Screens
Initial Screen

Screen with Menu Options

Next Screen after clicking “Dialing a number” menu option

41
Next Screen after Clicking “Opening a Website” menu option

After Choosing a Browser App

42
Next Screen after Clicking “To send an SMS” menu option

After clicking Allow Once of previous screen

43
5) Develop an application that inserts some notifications into Notification area and whenever a
notification is inserted, it should show a toast with details of the notification.
Application Directory

activity_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:orientation="vertical" >
<Button
android:id="@+id/btn_displaynotif"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Display Notification"
android:onClick="onClick"/>
</LinearLayout>
MainActivity.java
package com.murali.notifications;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
public class MainActivity extends Activity {
int notificationID = 1;
/** Called when the activity is first created. */

44
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
displayNotification();
}
protected void displayNotification()
{
//---PendingIntent to launch activity if the user selects
// this notification---
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID);
PendingIntent pendingIntent =PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.ic_launcher,"Reminder: Meeting starts in 5 minutes",
System.currentTimeMillis());
CharSequence from = "System Alarm";
CharSequence message = "Meeting with customer at 3pm...";
notif.setLatestEventInfo(this, from, message, pendingIntent);
Toast.makeText(getApplicationContext(),
"System Alarm:Meeting with customer at 3pm...",
Toast.LENGTH_LONG).show();
//---100ms delay, vibrate for 250ms, pause for 100 ms and
// then vibrate for 500ms---
notif.vibrate = new long[] { 100, 250, 100, 500};
nm.notify(notificationID, notif);
}
}
notification.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="Here are the details for the notification..." />
</LinearLayout>
NotificationView.java
package com.murali.notifications;
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
import android.widget.Toast;
public class NotificationView extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
//---look up the notification manager service---
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Toast.makeText(getApplicationContext(),
"toast with details of the notification",
Toast.LENGTH_LONG).show();
//---cancel the notification that we started---
nm.cancel(getIntent().getExtras().getInt("notificationID"));
}
}

45
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.notifications"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.notifications.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NotificationView"
android:label="Details of notification">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Input Output Screens

46
After Clicking “Display Notification” Button

After Dragging down the Notification Status Bar

After Clicking on Notification in the Notification tray

47
Weeek-5:
6) Create an application that uses a text file to store user names and passwords (tab separated
fields and one record per line). When the user submits a login name and password through a
screen, the details should be verified with the text file data and if match, show a dialog saying
that login is successful. Otherwise, show the dialog with Login failed message.
Application Directory

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/signup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:onClick="btnSignUp"
android:text="Sign-Up" />
<Button
android:id="@+id/signin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="130dp"
android:onClick="btnSignIn"
android:text="Sign-In" />
</RelativeLayout>
48
MainActivity.java
package com.murali.labexperiment6;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btnSignUp(View view) {
startActivity(new Intent("com.murali.labexperiment6.SignUpActivity"));
}
public void btnSignIn(View view) {
startActivity(new Intent("com.murali.labexperiment6.SignInActivity"));
}
}
register_form.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:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.49" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="36dp"
android:gravity="center"
android:text="Registration Form"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#F00000CC" />
<GridLayout
android:id="@+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="39dp"
android:columnCount="2"
android:gravity="center"
android:rowCount="3" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_margin="10dp"
android:layout_row="0"
android:gravity="center"
android:text="UserID"
android:textSize="20sp" />
<EditText
android:id="@+id/ruserid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_margin="10dp"
android:layout_row="0"

49
android:ems="8" >
<requestFocus />
</EditText>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_margin="10dp"
android:layout_row="1"
android:gravity="center"
android:text="Password"
android:textSize="20sp" />
<EditText
android:id="@+id/rpwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_margin="10dp"
android:layout_row="1"
android:ems="8"
android:inputType="textPassword" />
<TextView
android:id="@+id/cpassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_margin="10dp"
android:layout_row="2"
android:gravity="center"
android:text="CPassword"
android:textSize="20sp" />
<EditText
android:id="@+id/rcpwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_margin="10dp"
android:layout_row="2"
android:ems="8"
android:inputType="textPassword" />
</GridLayout>
<Button
android:id="@+id/register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/gridLayout"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:onClick="onRegister"
android:text="Register" />
</RelativeLayout>
</LinearLayout>
login_form.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:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.49" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
50
android:layout_marginTop="36dp"
android:gravity="center"
android:text="Login Form"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#F00000CC" />
<GridLayout
android:id="@+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="39dp"
android:columnCount="2"
android:gravity="center"
android:rowCount="2" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_row="0"
android:gravity="center"
android:text="UserID"
android:textSize="20sp" />
<EditText
android:id="@+id/luid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_margin="10dp"
android:layout_row="0"
android:ems="8" >
<requestFocus />
</EditText>

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="0"
android:layout_margin="10dp"
android:layout_row="1"
android:gravity="center"
android:text="Password"
android:textSize="20sp" />
<EditText
android:id="@+id/lpwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_margin="10dp"
android:layout_row="1"
android:ems="8"
android:inputType="textPassword" />
</GridLayout>
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/gridLayout"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:onClick="btnLogin"
android:text="Login" />
</RelativeLayout>
</LinearLayout>
SignUpActivity.java
package com.murali.labexperiment6;

51
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignUpActivity extends Activity {
EditText ruid,rpwd,rcpwd;
Button reg;
String uid,pwd,cpwd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_form);
ruid=(EditText)findViewById(R.id.ruserid);
rpwd=(EditText)findViewById(R.id.rpwd);
rcpwd=(EditText)findViewById(R.id.rcpwd);
reg=(Button)findViewById(R.id.register);
}
public void onRegister(View v){
uid=ruid.getText().toString();
pwd=rpwd.getText().toString();
cpwd=rcpwd.getText().toString();
if(uid.equals("")){
Toast.makeText(getApplicationContext(), "UserID is empty",
Toast.LENGTH_LONG).show();
}
else if(pwd.equals("")){
Toast.makeText(getApplicationContext(), "Password is empty",
Toast.LENGTH_LONG).show();
}
else if(cpwd.equals("")){
Toast.makeText(getApplicationContext(), "CPassword is empty",
Toast.LENGTH_LONG).show();
}
else if(pwd.equalsIgnoreCase(cpwd))
{
Toast.makeText(getApplicationContext(), "Ready to Store",
Toast.LENGTH_LONG).show();
String FILE_NAME = "file22.txt";
String someText=uid+" "+pwd+"\r\n";
try {
FileOutputStream fos = openFileOutput(FILE_NAME,
Context.MODE_APPEND);
fos.write(someText.toString().getBytes());
//Toast.makeText(this, someText, Toast.LENGTH_SHORT).show();
Toast.makeText(this, "registered successful",
Toast.LENGTH_SHORT).show();
fos.close();
startActivity(new
Intent("com.murali.labexperiment6.SignInActivity"));
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(), "CPassword not same as
Password", Toast.LENGTH_LONG).show();
}
}
}

SignInAcativity.java
52
package com.murali.labexperiment6;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignInActivity extends Activity {
EditText luid,lpwd;
Button login;
String uid,pwd,line1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_form);
luid=(EditText)findViewById(R.id.luid);
lpwd=(EditText)findViewById(R.id.lpwd);
login=(Button)findViewById(R.id.login);
}
public void btnLogin(View v){
uid=luid.getText().toString();
pwd=lpwd.getText().toString();
if(uid.isEmpty()){
Toast.makeText(getApplicationContext(), "UserID is empty",
Toast.LENGTH_LONG).show();
}
else if(pwd.isEmpty()){
Toast.makeText(getApplicationContext(), "Password is empty",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Ready to verify",
Toast.LENGTH_LONG).show();
line1=uid+" "+pwd;
try {
int found=0,notfound=0;
String FILE_NAME = "file22.txt";
BufferedReader bReader = new BufferedReader(new
InputStreamReader(openFileInput(FILE_NAME)));
String line;
StringBuffer text = new StringBuffer();
while ((line = bReader.readLine()) != null) {
text.append(line + "\n");
//Toast.makeText(this, line, Toast.LENGTH_SHORT).show();
if(line.equals(line1)){
found++;
//Toast.makeText(this, "login successful",
Toast.LENGTH_SHORT).show();
}else{
notfound++;
//Toast.makeText(this, "login failed",
Toast.LENGTH_SHORT).show();
}
}
if(found>0){
Toast.makeText(this, "login successful",
Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "login failed",
Toast.LENGTH_SHORT).show();
}
// Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}

53
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.labexperiment6"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.labexperiment6.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="SignUp"
android:name=".SignUpActivity" >
<intent-filter >
<action
android:name="com.murali.labexperiment6.SignUpActivity" />
<category
android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:label="SignIn"
android:name=".SignInActivity" >
<intent-filter >
<action
android:name="com.murali.labexperiment6.SignInActivity" />
<category
android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
”file22.txt” will be generated at Choose DDMS option in Eclipse IDE Choose FileExplorerIn
Choose data directoryChoose data directoryChoose application package directory Choose files
directory”file22.txt”

54
Input and Output Screens

Next Screen after Clicking the “Sign-Up” Button

Next screen after clicking “Register” Button

Enter UserID and Password and Click Login


55
After clicking on “Login” Button

If UserId, Password entered was not existed in File then it display’s login failed

56
7) Create a User Registration application that stores the user details (Employee) in a database
table (Insert, Delete, Update, Retrive, and RetriveAll).
Application Directory

EmployeeDBHelper.java
package com.murali.employeedatabaseapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class EmployeeDBHelper {
public static final String EmpId="EmpId";
public static final String EmpName="EmpName";
public static final String EmpSal="EmpSal";
private static final String databasename="EmployeeDB";
private static final String tablename="Employee";
private static final int databaseversion=1;
private static final String create_table="create table Employee (EmpId
integer " +
"primary key autoincrement, "+"EmpName text not null,
EmpSal integer not null);";
private final Context ct;
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public EmployeeDBHelper(Context context)
{
this.ct=context;
dbHelper=new DatabaseHelper(ct);
57
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context c)
{
super(c,databasename,null,databaseversion);
}
@Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
try
{
database.execSQL(create_table);
}
catch(SQLiteException e)
{
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database, int arg1, int
arg2) {
// TODO Auto-generated method stub
database.execSQL("DROP TABLE IF EXITS Employee");
onCreate(database);
}
}
//Declaring the connect() method to connect to the database
public EmployeeDBHelper connect()throws SQLException
{
database=dbHelper.getWritableDatabase();
return this;
}
//Declaring the disconnect() method to close the database
public void disconnect()
{
dbHelper.close();
}
//Declaring the insertEmployee() method to add the employee details
into the database
public long insertEmployee(String empname,int empsal)
{
ContentValues cv=new ContentValues();
cv.put(EmpName, empname);
cv.put(EmpSal, empsal);
this.connect();
return database.insert(tablename, null, cv);
}
//Declaring the retrieveAllEmployees() method to retrieve the details
of all the employees from the database
public Cursor retrieveAllEmployees()
{
this.connect();
return database.query(tablename,new String[] {
EmpId,EmpName,EmpSal}, null,null,null,null,null);
}
//Declaring the retriveEmployee() method to retrieve the details of all
the employee from the database
public Cursor retriveEmployee(long id)throws SQLException
{
this.connect();
Cursor c=database.query(true, tablename, new String[]{EmpId,
EmpName,
EmpSal}, EmpId+"="+id,null,null,null,null,null);
if(c!=null)
{
c.moveToFirst();
}
return c;

58
}
//Declaring the deleteEmployee() method to delete the details of an
Employee
public boolean deleteEmployee(long id)
{
this.connect();
return database.delete(tablename,EmpId+"="+id,null)>0;
}
//Declaring the updateEmployee() method to update the details of an
Employee
public boolean updateEmployee(long id,String empname,int empsal)
{
this.connect();
ContentValues cvalues=new ContentValues();
cvalues.put(EmpName, empname);
cvalues.put(EmpSal, empsal);
return database.update(tablename, cvalues, EmpId+"="+id,null)>0;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/deleteEmp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Delete an Employee" />
<Button
android:id="@+id/updateEmp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/deleteEmp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="26dp"
android:text="Update an Employee" />
<Button
android:id="@+id/selectEmp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/deleteEmp"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp"
android:text="Get an Employee" />
<Button
android:id="@+id/selectAllEmp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/selectEmp"
android:layout_centerHorizontal="true"
android:layout_marginTop="34dp"
android:text="Get All Employees" />
<Button
android:id="@+id/addEmp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/updateEmp"
android:layout_alignLeft="@+id/selectEmp"
android:layout_marginBottom="32dp"
android:text="Add an Employee" />
</RelativeLayout>
59
MainActivity.java
package com.murali.employeedatabaseapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button add_emp, get_all_emp, get_emp, update_emp, delete_emp;
/** called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add_emp=(Button)findViewById(R.id.addEmp);
add_emp.setOnClickListener(this);
get_all_emp=(Button)findViewById(R.id.selectAllEmp);
get_all_emp.setOnClickListener(this);
get_emp=(Button)findViewById(R.id.selectEmp);
get_emp.setOnClickListener(this);
update_emp=(Button)findViewById(R.id.updateEmp);
update_emp.setOnClickListener(this);
delete_emp=(Button)findViewById(R.id.deleteEmp);
delete_emp.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==findViewById(R.id.addEmp))
{
Intent i=new Intent(this,AddEmployee.class);
startActivity(i);
}
if(v==findViewById(R.id.selectAllEmp))
{
final EmployeeDBHelper emphelper=new EmployeeDBHelper(this);
Cursor c=emphelper.retrieveAllEmployees();
if(c.moveToFirst())
{
do
{
Toast.makeText(this,
"Employee Id:"+c.getString(0)+
"\nEmployee Name:"+c.getString(1)+
"\nEmployee Salary:"+c.getString(2),
Toast.LENGTH_LONG).show();
}while(c.moveToNext());
}else{
Toast.makeText(this,
"No Records in the database",
Toast.LENGTH_LONG).show();

60
}
}
if(v==findViewById(R.id.selectEmp))
{
Intent i=new Intent(this,GetEmployee.class);
startActivity(i);
}
if(v==findViewById(R.id.updateEmp))
{
Intent i=new Intent(this,UpdateEmployee.class);
startActivity(i);
}
if(v==findViewById(R.id.deleteEmp))
{
Intent i=new Intent(this,DeleteEmployee.class);
startActivity(i);
}
}
}
addemployee.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the Name of the Employee:" />
<EditText
android:id="@+id/empname"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the Salary of the Employee:" />
<EditText
android:id="@+id/empsal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/addEmp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Employee" />
</LinearLayout>
AddEmployee.java
package com.murali.employeedatabaseapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddEmployee extends Activity {
Button add_emp;
EditText empname, empsal;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
61
setContentView(R.layout.addemployee);
final EmployeeDBHelper empdbhelper=new EmployeeDBHelper(this);
empname=(EditText)findViewById(R.id.empname);
empsal=(EditText)findViewById(R.id.empsal);
add_emp=(Button)findViewById(R.id.addEmp);
add_emp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
String name;
int sal;
name=empname.getText().toString();
sal=(Integer.parseInt(empsal.getText().toString()));
long id=empdbhelper.insertEmployee(name, sal);
Toast.makeText(getBaseContext(), "Your record has been saved successfully with ID :"+
id, Toast.LENGTH_LONG).show();
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
deleteemployee.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the Employee id" />
<EditText
android:id="@+id/empid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn_delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Employee" />
</LinearLayout>
DeleteEmployee.java
package com.murali.employeedatabaseapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DeleteEmployee extends Activity {
EditText empid;
Button delete;
@Override
public void onCreate(Bundle savedInstanceState) {
62
super.onCreate(savedInstanceState);
setContentView(R.layout.deleteemployee);
final EmployeeDBHelper empdbhelper=new EmployeeDBHelper(this);
empid=(EditText)findViewById(R.id.empid);
delete=(Button)findViewById(R.id.btn_delete);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int emp_id=Integer.parseInt(empid.getText().toString());
if(empdbhelper.deleteEmployee(emp_id))
Toast.makeText(getBaseContext(),
"Your record has been deleted",
Toast.LENGTH_LONG).show();
else
Toast.makeText(getBaseContext(),
"Record does not exist",
Toast.LENGTH_LONG).show();
}
});
}
}

getemployee.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the Employee id" />
<EditText
android:id="@+id/empid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn_find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find Employee" />
</LinearLayout>

GetEmployee.java
package com.murali.employeedatabaseapp;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class GetEmployee extends Activity {
Button find_emp;
EditText empid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
63
setContentView(R.layout.getemployee);
final EmployeeDBHelper empdb=new EmployeeDBHelper(this);
empid=(EditText)findViewById(R.id.empid);
find_emp=(Button)findViewById(R.id.btn_find);
find_emp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int emp_id=Integer.parseInt(empid.getText().toString());
Cursor c=empdb.retriveEmployee(emp_id);
if(c.moveToFirst())
{
Toast.makeText(getBaseContext(),
"Employee Id:"+c.getString(0)+
"\nEmployee Name:"+c.getString(1)+
"\nEmployee Salary:"+c.getString(2),
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getBaseContext(),
"No Employee Record Found",
;
}
}
});
}
}
updateemployee.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter the Employee id" />
<EditText
android:id="@+id/empid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Employee Name" />
<EditText
android:id="@+id/empname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Employee Salary" />
<EditText
android:id="@+id/empsal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn_update"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update" />
</LinearLayout>

64
UpdateEmployee.java
package com.murali.employeedatabaseapp;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class UpdateEmployee extends Activity{
EditText empid,empname,empsal;
Button update;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updateemployee);
final EmployeeDBHelper empdb=new EmployeeDBHelper(this);
empid=(EditText)findViewById(R.id.empid);
empname=(EditText)findViewById(R.id.empname);
empsal=(EditText)findViewById(R.id.empsal);
update=(Button)findViewById(R.id.btn_update);
update.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int emp_id=Integer.parseInt(empid.getText().toString());
String empstr=empname.getText().toString();
int intsal=Integer.parseInt(empsal.getText().toString());
if(empdb.updateEmployee(emp_id, empstr, intsal))
{
Toast.makeText(getBaseContext(),
"Record has been updated",
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getBaseContext(),
"Record has not been updated",
Toast.LENGTH_LONG).show();
}
}
});
empid.addTextChangedListener(new TextWatcher()
{
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
@override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
@Override
65
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
empid.setEnabled(false);
int emp_id=Integer.parseInt(empid.getText().toString());
Cursor c=empdb.retriveEmployee(emp_id);
if(c.moveToFirst())
{
empname.setText(c.getString(1));
empsal.setText(c.getString(2));
}
else
{
Toast.makeText(getBaseContext(),
"No Employee Record",
Toast.LENGTH_LONG).show();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.employeedatabaseapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="AddEmployee"
android:label="Add Employee">
</activity>
<activity
android:name="DeleteEmployee"
android:label="Delete Employee">
</activity>
<activity
android:name="EmployeeDBHelper"
android:label="EmployeeDBHelper">
</activity>
<activity
android:name="GetEmployee"
android:label="Get Employee">
</activity>
<activity
android:name="UpdateEmployee"
android:label="Update Employee">
</activity>
<activity
android:name="com.murali.employeedatabaseapp.MainActivity"

66
android:label="@string/app_name" >
<intent-filter>

<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
”EmployeeDB and EmployeeDB-journal” will be generated at Choose DDMS option in Eclipse IDE
Choose FileExplorerIn Choose data directoryChoose data directoryChoose application
package directory Choose databases directory” EmployeeDB and EmployeeDB-journal”files

Input and Output Screens

After Clicking on “Add an Employee” Button of App Home Screen

67
After Clicking on “Get an Employee” Button of App Home Screen

Next clicking on “Find Employee” Button

68
After Clicking on “Get All Employee” Button of App Home Screen

After Clicking on “Update an Employee” Button of App Home Screen

69
Next clicking on “Update” Button

After Clicking on “Delete an Employee” Button of App Home Screen

70
Next clicking on “Delete Employee” Button

After Clicking on “Get All Employee” Button of App Home Screen

71
8) Create a database and a user table where the details of login names and passwords are
stored. Insert some names and an passwords initially. Now the login details entered by the
user should be verified with the database and an appropriate dialog should be shown to the
user.
Application Directory

DataBaseHelper.java
package com.murali.labexperiment8;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,
CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk
//and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db)
{
72
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
// Called when there is a database
//version mismatch meaning that the version
// of the database on disk needs
//to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion,
int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +
_oldVersion + " to " +_newVersion +
", which will destroy all old data");
// Upgrade the existing database to conform
//to the new version. Multiple
// previous versions can be handled by
//comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop
//the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
LoginDataBaseAdapter.java
package com.murali.labexperiment8;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class LoginDataBaseAdapter
{
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+
" integer primary key
autoincrement,"+
"USERNAME text,PASSWORD text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
73
}
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);

// Insert the row into your table


db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved",
// Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where,
new String[]{UserName}) ;
// Toast.makeText(context,
// "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted,
// Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?",
new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password=
cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new
String[]{userName});
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_vertical" >
<Button
android:id="@+id/buttonSignIN"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign In"
android:onClick="signIn"/>
<Button
android:id="@+id/buttonSignUP"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

74
android:text="Sign Up" />
</LinearLayout>

MainActivity.java
package com.murali.labexperiment8;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnSignIn,btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get The Refference Of Buttons
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
btnSignUp=(Button)findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity abd Start The
Activity
Intent intentSignUP=new Intent(getApplicationContext(),
SignUPActivity.class);
startActivity(intentSignUP);
}
});
}
// Methos to handleClick Event of Sign In Button
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the Refferences of views
final EditText editTextUserName=
(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=
(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button
btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String
userName=editTextUserName.getText().toString();
String
password=editTextPassword.getText().toString();
// fetch the Password form database for
respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with
Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(MainActivity.this, "Congrats: Login Successfull",

75
Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(MainActivity.this, "User Name or Password does not match",
Toast.LENGTH_LONG).show();
}
}
});

dialog.show();
}
@Override
protected void onDestroy() {
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}

login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/editTextUserNameToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPasswordToLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
android:hint="Password" />
<Button
android:id="@+id/buttonSignIn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sign In" />
</LinearLayout>
signup.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout
xmlns:android="http://schemas.a android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_vertical" >
<EditText android:id="@+id/editTextUserName"
android:hint="User Name"
android:layout_width="match_parent"
android:layoutheight="wrapcontent"

>
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />

76
<EditText
android:id="@+id/editTextConfirmPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Confirm Password"
android:inputType="textPassword" />
<Button
android:id="@+id/buttonCreateAccount"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Create Account"
android:layout_marginBottom="60dp" />
</LinearLayout>

SignUpActivity.java
package com.murali.labexperiment8;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignUPActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword;
Button btnCreateAccount;
LoginDataBaseAdapter loginDataBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get Refferences of Views
editTextUserName=
(EditText)findViewById(R.id.editTextUserName);
editTextPassword=
(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=
(EditText)findViewById(R.id.editTextConfirmPassword);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String
confirmPassword=editTextConfirmPassword.getText().toString();
// check if any of the fields are vaccant
if(userName.equals("")||password.equals("")||confirmPassword.equals("")
)
{
Toast.makeText(getApplicationContext(), "Field Vaccant",
Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match",
Toast.LENGTH_LONG).show();
return;
}
else
{// Save the Data in Database
loginDataBaseAdapter.insertEntry(userName, password);

77
Toast.makeText(getApplicationContext(), "Account Successfully Created ",
Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.labexperiment8"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.labexperiment8.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.murali.labexperiment8.SignUPActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.signup" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

”login.db and login.db -journal” will be generated at Choose DDMS option in Eclipse IDE Choose
FileExplorerIn Choose data directoryChoose data directoryChoose application package
directory Choose databases directory” login.db and login.db -journal”files

78
Input and Output Screens

Firstly Click on “Sign Up” Button

79
After entering the values click on “CreateAccount” Button

Now, goto Home Screen of the app and click on “Sign In” Button

80
After entering the valied values click on “Sign In” Button

After entering the invalied values click on “Sign In” Button

81
Week-6:

9) Create an admin application for user table which shows all records as a list and the admin can
select any record for edit or modify. The results are reflected in table.(Refer Lab program 7)

Input and Output Screens

Next screen after clicking on “Get an Employee” then enter Employee id value then click on “Find
Employee” Button

After Clicking on “Update an Employee” Button of App Home Screen

82
Next clicking on “Update” Button

After Clicking on “Get All Employee” Button of App Home Screen

83
10) Develop an application that shows all contacts of the phone along with details like name,
phone number, mobile number etc

Application Directory

activity_main.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:textSize="20dp"
android:gravity="center"
android:text="Contacts Information" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_below="@+id/textView"
android:gravity="center"
84
android:text="TextView" />
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView1"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
</ScrollView>

MainActivity.java
package com.murali.labexperiment10;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView outputText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
}
public void fetchContacts() {
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER =
ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI =
ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID =
ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI =
ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID =
ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null,
null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id =
cursor.getString(cursor.getColumnIndex( _ID ));
String name =
cursor.getString(cursor.getColumnIndex(
DISPLAY_NAME ));
int hasPhoneNumber =
Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER
)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
// Query and loop for every phone number of the contact
Cursor phoneCursor =
contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " =
?",
85
new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber =
phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" +
phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCursor =
contentResolver.query(EmailCONTENT_URI,
null, EmailCONTACT_ID+ " = ?"
, new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
email =
emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\nEmail:" + email);
}
emailCursor.close();
}
output.append("\n");
}
outputText.setText(output);
}
}}
Input and Output Screens

86
11) Create an application that saves user information like name, age, gender etc. in shared
preference and retrives them when program restarts.
Application Directory

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linLayou1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000ff"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/captionBox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SharedPreferences Container: User information"
android:layout_margin="5px" android:textStyle="bold">
</TextView>
<EditText
android:id="@+id/txtPref"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10px">
</EditText>
</LinearLayout>
MainActivity.java
package com.murali.labexperiment11;
87
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String MYPREFS = "MySharedPreferences001";
//this data values describe a typical customer record
String userName = "n.a.";
int userAge = 0;
String userGender;
String userQualification;
String userCollege;
TextView captionBox;
EditText txtPref;
final int mode = Activity.MODE_PRIVATE;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtPref = (EditText)findViewById(R.id.txtPref);
captionBox = (TextView) findViewById(R.id.captionBox);
captionBox.setText("SharedPreference Container: \n\n"+
"we are working on user Murali \n" +
"fake an interruption, press 'Back Button' \n" +
"re-execute the application.");
//create a reference to the shared preferences object
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
mode);
// is there an existing Preferences from previous executions of this
app?
if (mySharedPreferences != null &&
mySharedPreferences.contains("userName")) {
//object and key found, show all saved values
showSavedPreferences();
}
else
{
txtPref.setText("mmr");
}
}//onCreate
@Override
protected void onPause() {
//warning: activity is on last state of visibility! We are on the
//edge of been killed! Better save current state in Preference object
savePreferences();
super.onPause();
}
protected void savePreferences(){
//create the shared preferences object
SharedPreferences mySharedPreferences =
getSharedPreferences(MYPREFS, mode);
//obtain an editor to add data to (my)SharedPreferences object
SharedPreferences.Editor myEditor = mySharedPreferences.edit();
//put some <key/value> data in the preferences object
myEditor.putString("userName", "Murali Mohan Reddy");
myEditor.putInt("userAge", 37);
myEditor.putString("userGender", "Male");
myEditor.putString("userQualification","Assistant Professor");
myEditor.putString("userCollege","Vaageswari College of Engineering");
myEditor.commit();
}//savePreferences
public void showSavedPreferences() {
//retrieve the SharedPreferences object
SharedPreferences mySharedPreferences =
getSharedPreferences(MYPREFS, mode);
//extract the <key/value> pairs, use default param for missing
data

88
userName = mySharedPreferences.getString("custName", "Murali
Mohan Reddy");
userAge = mySharedPreferences.getInt("custAge", 37);

userGender = mySharedPreferences.getString("userGender","Male");
userQualification=
mySharedPreferences.getString("userQualification","Assistant Professor");
userCollege=
mySharedPreferences.getString("userCollege","Vaageswari College of
Engineering");
//show saved data on screen
String msg = "Name: " + userName + "\nAge: " + userAge +
"\nGender: " + userGender+"\nQualification: " +
userQualification+
"\nCollege: " + userCollege;
txtPref.setText(msg);
}//loadPreferences
}//Preferences1
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.labexperiment11"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.labexperiment11.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
” MySharedPreferencs001.xml” will be generated at Choose DDMS option in Eclipse IDE Choose
FileExplorerIn Choose data directoryChoose data directoryChoose application package
directory Choose shared_prefs directory”MySharedPreferencs001.xml”files

89
Input and Output Screens
Initial Screen after Intallation on emulator or device

After restart or re-execute the application on emulator or device

90
91
12) Create an alarm that rings every Sunday at 8:00 AM. Modify it to use a time picker to set
alarm time.
Application Directory

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:checked="false"
android:onClick="OnToggleClicked" />
</LinearLayout>

MainActivity.java
package com.murali.alarmsexample1;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;

92
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
TimePicker alarmTimePicker;
PendingIntent pendingIntent;
AlarmManager alarmManager;
ToggleButton tb;
@Override

protected void onCreate(Bundle savedInstanceState)


{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.timePicker);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
tb=(ToggleButton)findViewById(R.id.toggleButton);
}
public void OnToggleClicked(View view)
{
long time;
if (tb.isChecked())
{
Toast.makeText(MainActivity.this, "ALARM ON", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
//finding out day of Week
int dow = calendar.get (Calendar.DAY_OF_WEEK);
time=(calendar.getTimeInMillis()-(calendar.getTimeInMillis()%60000));
if(System.currentTimeMillis()>time && dow == Calendar.MONDAY)
{
if (calendar.AM_PM == 0)
time = time + (1000*60*60*12);

else
time = time + (1000*60*60*24);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 10000, pendingIntent);
}
else
{
alarmManager.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
}

AlarmReceiver.java
93
package com.murali.alarmsexample1;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver
{
Ringtone ringtone;
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(arg0, "Alarm! Wake up! Wake up!",
Toast.LENGTH_LONG).show();
Uri alarmUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null)
{
alarmUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
ringtone = RingtoneManager.getRingtone(arg0, alarmUri);
ringtone.play();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.alarmsexample1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.alarmsexample1.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" >
</receiver>
</application>
</manifest>
Input and Output Screens

94
After assigning alarm and while ringing alarm

Switching off alarm

95

You might also like