Anda di halaman 1dari 148

VAAGESWARI COLLEGE OF ENGINEERING

(affiliated to JNTUH Approved by A.I.C.T.E)


Beside L.M.D Police Station,
Thimmapur, Karimnagar.

ANDROID MOBILE
APPLICATION
DEVELOPMENT
MCA-III Year – I Sem LAB MANUAL

Prepared by:
Mr. M. Murali Mohan Reddy
Assistant Professor
Computer Science Department
ANDROID MOBILE APPLICATION DEVELOPMENT 2017

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"

By Mr. M. Murali Mohan Reddy Page 2


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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" />

</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();
}
});

By Mr. M. Murali Mohan Reddy Page 3


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

By Mr. M. Murali Mohan Reddy Page 4


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

Input Output Screens

Clicking on “Hello+” text… Output as follows

By Mr. M. Murali Mohan Reddy Page 5


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 6


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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"
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>

By Mr. M. Murali Mohan Reddy Page 7


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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);

By Mr. M. Murali Mohan Reddy Page 8


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

By Mr. M. Murali Mohan Reddy Page 9


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Input Output Screens

Enter your name “murali” in text box

By Mr. M. Murali Mohan Reddy Page 10


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
After Clicking OK Button

By Mr. M. Murali Mohan Reddy Page 11


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 12


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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"
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"

By Mr. M. Murali Mohan Reddy Page 13


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 14


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="3"
android:layout_column="0"
android:text="Age"
android:textSize="20sp"
android:gravity="center"/>

<EditText
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="3"
android:layout_column="1"
android:ems="8"
android:inputType="number" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="4"
android:layout_column="0"
android:text="Date Of Birth"
android:textSize="20sp"
android:gravity="center" />

<EditText
android:id="@+id/dob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="4"
android:layout_column="1"
android:ems="8"
android:inputType="date" />

<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_row="5"
android:layout_column="0"
android:text="State"
android:textSize="20sp"
android:gravity="center" />

<Spinner
android:id="@+id/state"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

By Mr. M. Murali Mohan Reddy Page 15


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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;
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);

By Mr. M. Murali Mohan Reddy Page 16


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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);

By Mr. M. Murali Mohan Reddy Page 17


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
//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);

By Mr. M. Murali Mohan Reddy Page 18


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
*/
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
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

By Mr. M. Murali Mohan Reddy Page 19


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

By Mr. M. Murali Mohan Reddy Page 20


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Input Output Screens

Enter the details

By Mr. M. Murali Mohan Reddy Page 21


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
After Clicking Submit Button (Display output as Linear Layout Format)

By Mr. M. Murali Mohan Reddy Page 22


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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"

By Mr. M. Murali Mohan Reddy Page 23


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

By Mr. M. Murali Mohan Reddy Page 24


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Output Screens
After Clicking Submit Button (Display output as Relative Layout Format)

By Mr. M. Murali Mohan Reddy Page 25


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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"
android:layout_margin="10dp"
android:layout_row="1"
android:layout_column="1"
android:textSize="30sp"
android:text="TextView" />

<TextView
android:id="@+id/textView5"

By Mr. M. Murali Mohan Reddy Page 26


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

By Mr. M. Murali Mohan Reddy Page 27


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Output Screens
After Clicking Submit Button (Display output as Grid Layout Format)

By Mr. M. Murali Mohan Reddy Page 28


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

<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>

<TableRow>

<TextView

By Mr. M. Murali Mohan Reddy Page 29


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

By Mr. M. Murali Mohan Reddy Page 30


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Output Screens
After Clicking Submit Button (Display output as Table Layout Format)

By Mr. M. Murali Mohan Reddy Page 31


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 32


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
>

</FrameLayout>

</LinearLayout>

By Mr. M. Murali Mohan Reddy Page 33


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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);
}

By Mr. M. Murali Mohan Reddy Page 34


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
/** 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


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{

By Mr. M. Murali Mohan Reddy Page 35


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
/** 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);

/** Setting the layout for this activity */

By Mr. M. Murali Mohan Reddy Page 36


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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);

By Mr. M. Murali Mohan Reddy Page 37


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
/** 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;

/** 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();
}

By Mr. M. Murali Mohan Reddy Page 38


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
}

@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"

By Mr. M. Murali Mohan Reddy Page 39


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.murali.StudentNamesDetailsActivity"
/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>

</manifest>

By Mr. M. Murali Mohan Reddy Page 40


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

Input Output Screens


Clicking on “Sachin” in the Student List on Vertical Input Screen

For that Vertical Output Screen is

By Mr. M. Murali Mohan Reddy Page 41


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Clicking on “Rohit” in the Student List on Horizontal Input Screen

For the Horizontal Output Screen is

By Mr. M. Murali Mohan Reddy Page 42


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 43


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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"/>

</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);

By Mr. M. Murali Mohan Reddy Page 44


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
}
@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);
}
}
}

By Mr. M. Murali Mohan Reddy Page 45


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.labexperiment4aom"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.labexperiment4aom.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>

By Mr. M. Murali Mohan Reddy Page 46


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Input Output Screens

Initial Screen

Screen with Menu Options

By Mr. M. Murali Mohan Reddy Page 47


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Next Screen after clicking “Dialing a number” menu option

Next Screen after Clicking “Opening a Website” menu option

By Mr. M. Murali Mohan Reddy Page 48


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
After Choosing a Browser App

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

By Mr. M. Murali Mohan Reddy Page 49


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
After clicking Allow Once of previous screen

By Mr. M. Murali Mohan Reddy Page 50


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 51


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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. */
@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",

By Mr. M. Murali Mohan Reddy Page 52


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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",

By Mr. M. Murali Mohan Reddy Page 53


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Toast.LENGTH_LONG).show();

//---cancel the notification that we started---


nm.cancel(getIntent().getExtras().getInt("notificationID"));
}
}

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>

By Mr. M. Murali Mohan Reddy Page 54


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Input Output Screens

After Clicking “Display Notification” Button

By Mr. M. Murali Mohan Reddy Page 55


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
After Dragging down the Notification Status Bar

After Clicking on Notification in the Notification tray

By Mr. M. Murali Mohan Reddy Page 56


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 57


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

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"));
}

By Mr. M. Murali Mohan Reddy Page 58


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

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

By Mr. M. Murali Mohan Reddy Page 59


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

<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"
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>

By Mr. M. Murali Mohan Reddy Page 60


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
<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"
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"

By Mr. M. Murali Mohan Reddy Page 61


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
android:layout_margin="10dp"
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>

By Mr. M. Murali Mohan Reddy Page 62


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
SignUpActivity.java

package com.murali.labexperiment6;

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";

By Mr. M. Murali Mohan Reddy Page 63


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

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);

By Mr. M. Murali Mohan Reddy Page 64


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
}

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();
}

}
}
}

By Mr. M. Murali Mohan Reddy Page 65


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

By Mr. M. Murali Mohan Reddy Page 66


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
”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”

Input and Output Screens

By Mr. M. Murali Mohan Reddy Page 67


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

Next Screen after Clicking the “Sign-Up” Button

Next screen after clicking “Register” Button

By Mr. M. Murali Mohan Reddy Page 68


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Enter UserID and Password and Click Login

After clicking on “Login” Button

By Mr. M. Murali Mohan Reddy Page 69


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
If UserId, Password entered was not existed in File then it display’s login failed

By Mr. M. Murali Mohan Reddy Page 70


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
7) Create a User Registration application that stores the user details (Employee) in a database
table (Insert, Delete, Update, Retrive, and RetriveAll).

Application Directory

By Mr. M. Murali Mohan Reddy Page 71


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

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);
}

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();
}

By Mr. M. Murali Mohan Reddy Page 72


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

@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();
}

By Mr. M. Murali Mohan Reddy Page 73


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
return c;
}

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

By Mr. M. Murali Mohan Reddy Page 74


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

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);

By Mr. M. Murali Mohan Reddy Page 75


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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();
}
}
if(v==findViewById(R.id.selectEmp))
{
Intent i=new Intent(this,GetEmployee.class);
startActivity(i);
}
if(v==findViewById(R.id.updateEmp))
{

By Mr. M. Murali Mohan Reddy Page 76


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

By Mr. M. Murali Mohan Reddy Page 77


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

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);
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();
}
}
});

By Mr. M. Murali Mohan Reddy Page 78


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
}

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

By Mr. M. Murali Mohan Reddy Page 79


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
public void onCreate(Bundle savedInstanceState) {
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"/>

By Mr. M. Murali Mohan Reddy Page 80


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
<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);
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",

By Mr. M. Murali Mohan Reddy Page 81


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Toast.LENGTH_LONG).show();
}

}
});
}

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>

By Mr. M. Murali Mohan Reddy Page 82


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

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();

By Mr. M. Murali Mohan Reddy Page 83


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
}
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 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();

By Mr. M. Murali Mohan Reddy Page 84


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
}
}

});
}
}

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"
android:label="@string/app_name" >
<intent-filter>

By Mr. M. Murali Mohan Reddy Page 85


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
<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

By Mr. M. Murali Mohan Reddy Page 86


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

Input and Output Screens

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

By Mr. M. Murali Mohan Reddy Page 87


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

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

By Mr. M. Murali Mohan Reddy Page 88


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

Next clicking on “Find Employee” Button

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

By Mr. M. Murali Mohan Reddy Page 89


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

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

By Mr. M. Murali Mohan Reddy Page 90


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Next clicking on “Update” Button

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

By Mr. M. Murali Mohan Reddy Page 91


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Next clicking on “Delete Employee” Button

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

By Mr. M. Murali Mohan Reddy Page 92


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 93


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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)
{
_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);
}

By Mr. M. Murali Mohan Reddy Page 94


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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;
}

public void insertEntry(String userName,String password)


{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);

By Mr. M. Murali Mohan Reddy Page 95


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
// 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

By Mr. M. Murali Mohan Reddy Page 96


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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"
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

By Mr. M. Murali Mohan Reddy Page 97


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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",
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

By Mr. M. Murali Mohan Reddy Page 98


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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.android.com/apk/res/android"
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:layout_height="wrap_content"

By Mr. M. Murali Mohan Reddy Page 99


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
>

<requestFocus />
</EditText>

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

<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

By Mr. M. Murali Mohan Reddy Page 100


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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);
Toast.makeText(getApplicationContext(), "Account Successfully Created ",
Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();

loginDataBaseAdapter.close();
}
}

By Mr. M. Murali Mohan Reddy Page 101


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

By Mr. M. Murali Mohan Reddy Page 102


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
”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

Input and Output Screens

By Mr. M. Murali Mohan Reddy Page 103


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Firstly Click on “Sign Up” Button

After entering the values click on “CreateAccount” Button

By Mr. M. Murali Mohan Reddy Page 104


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

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

By Mr. M. Murali Mohan Reddy Page 105


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

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

By Mr. M. Murali Mohan Reddy Page 106


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
After entering the invalied values click on “Sign In” Button

By Mr. M. Murali Mohan Reddy Page 107


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 108


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
After Clicking on “Update an Employee” Button of App Home Screen

Next clicking on “Update” Button

By Mr. M. Murali Mohan Reddy Page 109


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
After Clicking on “Get All Employee” Button of App Home Screen

By Mr. M. Murali Mohan Reddy Page 110


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
10) Develop an application that shows all contacts of the phone along with details like name,
phone number, mobile number etc.

Application Directory

By Mr. M. Murali Mohan Reddy Page 111


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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"
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>

By Mr. M. Murali Mohan Reddy Page 112


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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) {

By Mr. M. Murali Mohan Reddy Page 113


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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 + " =
?",
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);
}
}}

By Mr. M. Murali Mohan Reddy Page 114


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Input and Output Screens

By Mr. M. Murali Mohan Reddy Page 115


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
11) Create an application that saves user information like name, age, gender etc. in shared
preference and retrives them when program restarts.

Application Directory

By Mr. M. Murali Mohan Reddy Page 116


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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;

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);

By Mr. M. Murali Mohan Reddy Page 117


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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
userName = mySharedPreferences.getString("custName", "Murali
Mohan Reddy");
userAge = mySharedPreferences.getInt("custAge", 37);

By Mr. M. Murali Mohan Reddy Page 118


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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>

By Mr. M. Murali Mohan Reddy Page 119


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
” 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

By Mr. M. Murali Mohan Reddy Page 120


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Input and Output Screens

Initial Screen after Intallation on emulator or device

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

By Mr. M. Murali Mohan Reddy Page 121


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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

By Mr. M. Murali Mohan Reddy Page 122


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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;
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

By Mr. M. Murali Mohan Reddy Page 123


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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();


}
}
}

By Mr. M. Murali Mohan Reddy Page 124


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
AlarmReceiver.java

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" >

By Mr. M. Murali Mohan Reddy Page 125


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
<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>

By Mr. M. Murali Mohan Reddy Page 126


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Input and Output Screens

After assigning alarm and while ringing alarm

By Mr. M. Murali Mohan Reddy Page 127


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Switching off alarm

By Mr. M. Murali Mohan Reddy Page 128


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
13) Create an application that shows the given URL (from a text field) in a browser.

Application Directory

By Mr. M. Murali Mohan Reddy Page 129


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
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_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="32dp"
android:text="Enter Ur URL :" />

<EditText
android:id="@+id/url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/tv"
android:layout_marginTop="31dp"
android:ems="100" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/url"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:onClick="onBtnClick"
android:text="Browser" />

</RelativeLayout>

MainActivity.java

package com.murali.labexperiment13;

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

public class MainActivity extends Activity {

EditText et;
Button bt;
String urlAddress;
@Override

By Mr. M. Murali Mohan Reddy Page 130


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=(EditText)findViewById(R.id.url);
bt=(Button)findViewById(R.id.button1);
}

public void onBtnClick(View v){


urlAddress=et.getText().toString();
Intent websiteIntent=new Intent(Intent.ACTION_VIEW,
Uri.parse(urlAddress));
startActivity(websiteIntent);

AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.labexperiment13"
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.labexperiment13.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>

By Mr. M. Murali Mohan Reddy Page 131


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Input and Output Screens

Enter Ur URL address in Edit Text box and click on “Browser” Button

Output screen after clicking on “Browser” Button

By Mr. M. Murali Mohan Reddy Page 132


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
14) Develop an application that shows the current location’s latitude and longitude

Application Directory

By Mr. M. Murali Mohan Reddy Page 133


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_height="wrap_content" android:text="My
Location is:"
android:layout_width="match_parent" android:textSize="16px"
android:textStyle="bold" android:gravity="center_horizontal"
android:layout_marginTop="10dip"
android:layout_marginBottom="10dip" />
<EditText android:layout_height="wrap_content" android:text=""
android:layout_width="match_parent"
android:id="@+id/editTextShowLocation"
android:lines="6" android:gravity="top"/>
<Button android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="@+id/buttonGetLocation"
android:text="Get My Location" android:textSize="15px"
android:textStyle="bold" android:layout_marginTop="10dip" />
</LinearLayout>

MainActivity.java

package com.murali.android_gps_using;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

private EditText editTextShowLocation;


private Button buttonGetLocation;

private LocationManager locManager;


private LocationListener locListener;
private Location mobileLocation;

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


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextShowLocation = (EditText)
findViewById(R.id.editTextShowLocation);

By Mr. M. Murali Mohan Reddy Page 134


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
buttonGetLocation = (Button)
findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buttonGetLocationClick();
}
});
}

/** Gets the current location and update the mobileLocation variable*/
private void getCurrentLocation() {
locManager =
(LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mobileLocation = location;
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, locListener);
}

private void buttonGetLocationClick() {


getCurrentLocation();
// gets the current location and update mobileLocation variable

if (mobileLocation != null) {
locManager.removeUpdates(locListener);
// This needs to stop getting the location data and save the
battery power.

String londitude = "Longitude: " +


mobileLocation.getLongitude();
String latitude = "Latitude: " +
mobileLocation.getLatitude();
String altitiude = "Altitiude: " +
mobileLocation.getAltitude();

By Mr. M. Murali Mohan Reddy Page 135


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
String accuracy = "Accuracy: " +
mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();

editTextShowLocation.setText(londitude + "\n" + latitude +


"\n"
+ altitiude + "\n" + accuracy + "\n" + time);
} else {
editTextShowLocation.setText("Sorry, location is not
determined");
}
}

AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali.android_gps_using"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">

</uses-permission>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.murali.android_gps_using.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>

By Mr. M. Murali Mohan Reddy Page 136


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Input and Output Screens

After Clicking on button “Get My Location”

By Mr. M. Murali Mohan Reddy Page 137


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
15) Create an application that shows the current location on Google maps.
To open Android Studio Editor
Step 1. Goto start menu choose “Android Studio” icon

Step 2. Click on “Start a new Android Studio project”

By Mr. M. Murali Mohan Reddy Page 138


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Step 3. Create New Project – After Configure your New Project Click Next

Step 4. Selecting Target Android Devices Click Next

By Mr. M. Murali Mohan Reddy Page 139


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Step 5. Add Activity to Mobile—Select Google Maps Activity and Click Next

Step 6. Customize the Activity and Click on Finish

By Mr. M. Murali Mohan Reddy Page 140


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Step 7. Click close button on Tip of the day window in Android Studio

Step 8. Copy the link and paste it in browse to get Google Map key from “google_maps_api.xml”

By Mr. M. Murali Mohan Reddy Page 141


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
google_maps_api.xml

<resources>
<!--
TODO: Before you run your application, you need a Google Maps API key.

To get one, follow this link, follow the directions and press "Create" at the end:

https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyTy
pe=CLIENT_SIDE_ANDROID&r=F5:D3:46:71:05:67:41:C9:02:5E:3F:D2:9B:87:2D:16:BE:E1:04:48%3
Bcom.murali4ruall.googlemapsapp22

You can also add your credentials to an existing key, using these values:

Package name:
F5:D3:46:71:05:67:41:C9:02:5E:3F:D2:9B:87:2D:16:BE:E1:04:48

SHA-1 certificate fingerprint:


F5:D3:46:71:05:67:41:C9:02:5E:3F:D2:9B:87:2D:16:BE:E1:04:48

Alternatively, follow the directions here:


https://developers.google.com/maps/documentation/android/start#get-key

Once you have your key (it starts with "AIza"), replace the "google_maps_key"
string in this file.
-->
<string name="google_maps_key" templateMergeStrategy="preserve"
translatable="false">YOUR_KEY_HERE</string>
</resources>

Step 9. After pasting the link login to gmail account and click on “contine” button

By Mr. M. Murali Mohan Reddy Page 142


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Step 10. Click on “Create API Key” button

Step 11. Copy the API Key Created

By Mr. M. Murali Mohan Reddy Page 143


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Step 12. Copied key should be replaced at “YOUR_KEY_HERE” in google_maps_api.xml

<resources>
<!--
TODO: Before you run your application, you need a Google Maps API key.

To get one, follow this link, follow the directions and press "Create" at the end:

https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyTy
pe=CLIENT_SIDE_ANDROID&r=F5:D3:46:71:05:67:41:C9:02:5E:3F:D2:9B:87:2D:16:BE:E1:04:48%3
Bcom.murali4ruall.googlemapsapp22

You can also add your credentials to an existing key, using these values:

Package name:
F5:D3:46:71:05:67:41:C9:02:5E:3F:D2:9B:87:2D:16:BE:E1:04:48

SHA-1 certificate fingerprint:


F5:D3:46:71:05:67:41:C9:02:5E:3F:D2:9B:87:2D:16:BE:E1:04:48

Alternatively, follow the directions here:


https://developers.google.com/maps/documentation/android/start#get-key

Once you have your key (it starts with "AIza"), replace the "google_maps_key"
string in this file.
-->
<string name="google_maps_key" templateMergeStrategy="preserve"
translatable="false">AIzaSyCfYgmQxdMtOCzZ2D2kM1x0JzAw0ruJlTs</string>
</resources>

activity_maps.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.murali4ruall.googlemapsapp22.MapsActivity" />

MapsActivity.java

package com.murali4ruall.googlemapsapp22;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

By Mr. M. Murali Mohan Reddy Page 144


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be
used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera.
* In this case, we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device.
* This method will only be triggered once the user has installed
Google Play services and returned to the app.
*/

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng MuraliPoint = new LatLng(18.4307720, 79.1126980);
mMap.addMarker(new

MarkerOptions().position(MuraliPoint).title("murali4ruall.blogspot.in"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(MuraliPoint));
}
}

AndroidManifest.xml

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.murali4ruall.googlemapsapp22">

<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the

By Mr. M. Murali Mohan Reddy Page 145


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
APK.
You need a different API key for each encryption key, including the
release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/
and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />

<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

Output Screen
Click “Run ‘app’” in Run option

By Mr. M. Murali Mohan Reddy Page 146


ANDROID MOBILE APPLICATION DEVELOPMENT 2017
Select the AVD Device to Deploy

Next click “ok” button

By Mr. M. Murali Mohan Reddy Page 147


ANDROID MOBILE APPLICATION DEVELOPMENT 2017

Output of the given app

By Mr. M. Murali Mohan Reddy Page 148

Anda mungkin juga menyukai