SlideShare ist ein Scribd-Unternehmen logo
1 von 64
Downloaden Sie, um offline zu lesen
BuildersEngineeringCollege
LAB MANUAL
Subject Code : CS6611
Subject Name : MOBILE APPLICATION DEVELOPMENT
LABORATORY
Year : III
Sem : VI
Prepared by
Mr. S. GOBINATH, AP/CSE
BuildersEngineeringCollege
CS6611- MOBILE APPLICATION DEVELOPMENT LABORATORY L T P C
0 0 3 2
OBJECTIVES:
The student should be made to:
• Know the components and structure of mobile application development frameworks
for Android and windows OS based mobiles.
• Understand how to work with various mobile application development frameworks.
• Learn the basic and important design concepts and issues of development of mobile
applications.
• Understand the capabilities and limitations of mobile devices.
LIST OF EXPERIMENTS:
1. Develop an application that uses GUI components, Font and Colours.
2. Develop an application that uses Layout Managers and event listeners.
3. Develop a native calculator application.
4. Write an application that draws basic graphical primitives on the screen.
5. Develop an application that makes use of database.
6. Develop an application that makes use of RSS Feed.
7. Implement an application that implements Multi threading.
8. Develop a native application that uses GPS location information.
9. Implement an application that writes data to the SD card.
10. Implement an application that creates an alert upon receiving a message.
11. Write a mobile application that creates alarm clock.
TOTAL: 45
PERIODS
OUTCOMES:
At the end of the course, the student should be able to:
• Design and Implement various mobile applications using emulators.
• Deploy applications to hand-held devices.
LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS
Standalone desktops with Windows or Android or iOS or Equivalent Mobile Application
Development Tools with appropriate emulators and debuggers – 30 Nos.
BuildersEngineeringCollege
1
Ex.No: 1 Develop an application that uses GUI components, Font and Colours
Date:
Aim:
To develop an android application that uses GUI components, Font and Colours
using android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.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"
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="helloapp.example.com.demoapp.MainActivity"
android:background="#03acda"
android:clickable="false"
android:id="@+id/canvas">
<TextView
BuildersEngineeringCollege
2
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Username"
android:id="@+id/txtUsername"
android:textColorHighlight="#4d77e2"
android:textIsSelectable="true"
android:typeface="serif"
android:textStyle="bold|italic"
android:textColor="#ffffff"
android:textSize="20dp"
android:layout_marginBottom="5dp"
android:layout_above="@+id/edtUsername"
android:layout_alignParentLeft="true"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/edtUsername"
android:hint="Enter Your Username"
android:textColorHint="#7a7a7a"
android:layout_above="@+id/txtPassword"
android:layout_alignLeft="@id/txtPassword"
android:layout_alignRight="@+id/imageView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Password"
android:id="@+id/txtPassword"
android:textStyle="bold|italic"
android:typeface="serif"
android:textColor="#ffffff"
android:textIsSelectable="false"
android:textSize="20dp"
android:layout_centerVertical="true"
android:layout_alignRight="@+id/txtUsername" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/edtPassword"
android:hint="Enter Your Password"
android:textColorHint="#7a7a7a"
android:layout_below="@+id/txtPassword"
android:layout_alignLeft="@+id/txtPassword"
android:layout_alignRight="@+id/textView" />
<Button
android:layout_width="wrap_content"
BuildersEngineeringCollege
3
android:layout_height="wrap_content"
android:text="Change Background Color"
android:id="@+id/btnLogin"
android:typeface="serif"
android:layout_below="@+id/edtPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Note: Username &quot;CSE&quot; and Password &quot;EBET&quot;"
android:id="@+id/textView"
android:textStyle="normal|italic"
android:typeface="serif"
android:textColor="#fbfbfb"
android:layout_below="@+id/btnLogin"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/ebetlogo"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_above="@+id/txtUsername" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Font"
android:id="@+id/btnFont"
android:layout_below="@+id/textView"
android:layout_alignLeft="@+id/btnLogin"
android:layout_alignStart="@+id/btnLogin"
android:layout_alignRight="@+id/btnLogin"
android:layout_alignEnd="@+id/btnLogin" />
</RelativeLayout>
mainactivity.java
package com.sg.gui;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
BuildersEngineeringCollege
4
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button btnLogin;
Button btnFont;
EditText edtUsername, edtPassword;
RelativeLayout canvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnFont = (Button)findViewById(R.id.btnFont);
edtUsername = (EditText)findViewById(R.id.edtUsername);
edtPassword =(EditText)findViewById(R.id.edtPassword);
canvas = (RelativeLayout)findViewById(R.id.canvas);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String username=null, password=null;
username = edtUsername.getText().toString();
password = edtPassword.getText().toString();
if(username.equals("CSE") && password.equals("EBET")){
Toast.makeText(getApplicationContext(),"User
authenticated!",Toast.LENGTH_LONG).show();
canvas.setBackgroundResource(R.color.bgcolor);
}else{
Toast.makeText(getApplicationContext(),"Please check your
Credentials",Toast.LENGTH_LONG).show();
}
}
});
btnFont.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextView tx = (TextView)findViewById(R.id.textView);
Typeface custom_font = Typeface.createFromAsset(getAssets(),
"fonts/sansbold.ttf");
tx.setTypeface(custom_font);
BuildersEngineeringCollege
5
}
});
}
}
Output:
BuildersEngineeringCollege
6
Result:
Thus the android application that uses GUI components, Font and Colours is
developed and tested using android studio.
BuildersEngineeringCollege
7
Ex.No: 2 Develop an application that uses Layout Managers and event listeners
Date:
Aim:
To develop an android application that uses Layout Managers and event listeners
using android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Layout and Listener Program"
BuildersEngineeringCollege
8
android:id="@+id/txtSample"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/txtSample"
android:layout_centerHorizontal="true">
<ImageView
android:layout_width="111dp"
android:layout_height="111dp"
android:id="@+id/imageView"
android:layout_gravity="center_horizontal"
android:src="@drawable/number1" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tableRow"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:id="@+id/btnClick" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Long Click Me"
android:id="@+id/btnLongClick" />
</TableRow>
</TableLayout>
<GridLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:id="@+id/lytGrid">
<Button
android:layout_width="202dp"
android:layout_height="156dp"
android:text="Click or Long CLick n Me"
android:id="@+id/btnAll"
BuildersEngineeringCollege
9
android:layout_column="3"
android:layout_row="0"
android:layout_columnSpan="1"
android:layout_rowSpan="2" />
<Button
android:layout_width="143dp"
android:layout_height="match_parent"
android:text="Show nMy nName"
android:id="@+id/btnShowName"
android:layout_row="1"
android:layout_column="2"
android:layout_rowSpan="3" />
<EditText
android:layout_width="match_parent"
android:layout_height="62dp"
android:id="@+id/txtName"
android:layout_row="3"
android:layout_column="3"
android:hint="Enter your Name"
android:layout_columnSpan="1"
android:layout_rowSpan="1" />
</GridLayout>
</LinearLayout>
</RelativeLayout>
Program: mainactivity.java
package com.sg.layout;
import android.content.ClipData;
import android.content.ClipDescription;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.DragEvent;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.sg.layout.R;
public class MainActivity extends AppCompatActivity {
BuildersEngineeringCollege
10
Button clickBtn, longClickBtn, allBtn, btnShow;
TextView sample;
EditText nameTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickBtn = (Button) findViewById(R.id.btnClick);
longClickBtn = (Button) findViewById(R.id.btnLongClick);
allBtn = (Button) findViewById(R.id.btnAll);
btnShow = (Button) findViewById(R.id.btnShowName);
sample = (TextView) findViewById(R.id.txtSample);
nameTxt = (EditText) findViewById(R.id.txtName);
clickBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Click event!",
Toast.LENGTH_SHORT).show();
}
});
longClickBtn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), "Long click event!",
Toast.LENGTH_SHORT).show();
return false;
}
});
allBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "You Just Clicked Me!",
Toast.LENGTH_SHORT).show();
}
});
allBtn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), "You clicked me for long!",
Toast.LENGTH_SHORT).show();
return false;
}
});
BuildersEngineeringCollege
11
btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sample.setText(nameTxt.getText().toString());
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
BuildersEngineeringCollege
12
Output:
Result:
Thus the android application that Layout Managers and event listeners is developed
and tested using android studio.
BuildersEngineeringCollege
13
Ex.No: 3 Develop a native calculator application
Date:
Aim:
To develop a native calculator application using android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:layout_width="fill_parent"
android:layout_height="77dp"
BuildersEngineeringCollege
14
android:id="@+id/txtScreen"
android:inputType="number|numberDecimal|numberSigned"
android:textSize="@dimen/activity_vertical_margin"/>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="@+id/btn1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:id="@+id/btn2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:id="@+id/btn3" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:id="@+id/btn4" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5"
android:id="@+id/btn5" />
<Button
android:layout_width="wrap_content"
BuildersEngineeringCollege
15
android:layout_height="wrap_content"
android:text="6"
android:id="@+id/btn6" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7"
android:id="@+id/btn7" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8"
android:id="@+id/btn8" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:id="@+id/btn9" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="@+id/btn0" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="."
android:id="@+id/btnDot" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C"
android:id="@+id/btnClear" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
BuildersEngineeringCollege
16
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:id="@+id/btnAdd" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="-"
android:id="@+id/btnSubtract" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="/"
android:id="@+id/btnDivide" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="*"
android:id="@+id/btnMultiply" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:id="@+id/btnEquals"
android:layout_span="4" />
</TableRow>
</TableLayout>
</LinearLayout>
</RelativeLayout>
mainactivity.java
package com.sg.calculator;
import android.annotation.TargetApi;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
BuildersEngineeringCollege
17
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.sg.calculator.R;
public class MainActivity extends ActionBarActivity {
private EditText Scr;
private float NumberBf=0, NumAf, result=0;
private String Operation, mod="replace";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Scr = (EditText) findViewById(R.id.txtScreen);
Scr.setText("");
int idList[] = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn2, R.id.btn3, R.id.btn4,
R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9,
R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide,
R.id.btnClear,R.id.btnEquals, R.id.btnDot, };
for(int id:idList) {
View v = (View) findViewById(id);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onButtonClick(v);
}
});
}
}
public void mMath(String str) {
mResult();
try {
NumberBf = Float.parseFloat(Scr.getText().toString());
Operation = str;
}catch (Exception e) {
Toast.makeText(getApplicationContext(),(CharSequence) e,
Toast.LENGTH_SHORT).show();
Scr.setText("SYNTAX ERROR");
mod="replace";
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void mResult() {
NumAf = 0;
BuildersEngineeringCollege
18
if(!Scr.getText().toString().trim().isEmpty())
NumAf = Float.parseFloat(Scr.getText().toString());
result = NumAf;
try {
switch (Operation) {
case "+":
result = NumAf + NumberBf;
break;
case "-":
result = NumberBf - NumAf;
break;
case "*":
result = NumAf * NumberBf;
break;
case "/":
result = NumberBf / NumAf;
break;
default:
result = NumAf;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Scr.setText(String.valueOf(result));
mod = "replace";
}
public void getKeyboard(String str) {
String ScrTxt = Scr.getText().toString();
ScrTxt += str;
if(mod.equals("add"))
Scr.setText(ScrTxt);
else
Scr.setText(str);
mod = "add";
}
public void onButtonClick(View v) {
switch (v.getId()) {
case R.id.btnClear: //Clear
Scr.setText("");
NumberBf = 0;
Operation = "";
break;
case R.id.btnAdd:
mMath("+");
break;
BuildersEngineeringCollege
19
case R.id.btnSubtract:
if(mod.equals("replace")) {
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
}
else mMath("-");
break;
case R.id.btnMultiply:
mMath("*");
break;
case R.id.btnDivide:
mMath("/");
break;
case R.id.btnEquals:
mResult();
Operation = "";
NumberBf = 0;
break;
default:
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
break;
}
}
}
BuildersEngineeringCollege
20
Output:
Result:
Thus the native calculator application is developed and tested using android studio.
BuildersEngineeringCollege
21
Ex.No: 4 Write an application that draws basic graphical
Date: primitives on the screen
Aim:
To write an application that draws basic graphical primitives on the screen using
android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java and
create samplecanvas.java files and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.sg.graphic.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
BuildersEngineeringCollege
22
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
mainactivity.java
package com.sg.graphic;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
com.sg.graphic.Canvas1 drawView = new Canvas1(this);
setContentView(drawView);
}
}
Canvas.java
package com.sg.graphic;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class Canvas1 extends View{
Paint paint = new Paint();
BuildersEngineeringCollege
23
public Canvas1(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
paint.setColor(Color.BLUE);
paint.setStrokeWidth(0);
canvas.drawRect(100, 100, 300, 300, paint);
paint.setColor(Color.GREEN);
canvas.drawCircle(200, 400, 75, paint);
paint.setColor(Color.MAGENTA);
paint.setStrokeWidth(4);
canvas.drawLine(100, 540, 300, 540, paint);
paint.setColor(getResources().getColor(R.color.teal_blue));
canvas.drawText("Graphical Primitive",100,50,paint);
paint.setColor(Color.RED);
paint.setStrokeWidth(6);
canvas.drawPoint(200,600,paint);
}
}
BuildersEngineeringCollege
24
Output:
Result:
Thus the application that draws basic graphical primitives on the screen is developed
and tested using android studio.
BuildersEngineeringCollege
25
Ex.No: 5 Develop an application that makes use of database
Date:
Aim:
To develop an application that makes use of database using android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLayout"
android:stretchColumns="0"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:text="@string/title"
android:layout_x="110dp"
android:layout_y="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:text="@string/roll_no"
android:layout_x="30dp"
android:layout_y="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="@+id/editRollno"
android:inputType="number"
BuildersEngineeringCollege
26
android:layout_x="150dp"
android:layout_y="50dp"
android:layout_width="150dp"
android:layout_height="40dp"/>
<TextView android:text="@string/name"
android:layout_x="30dp"
android:layout_y="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="@+id/editName"
android:inputType="text"
android:layout_x="150dp"
android:layout_y="100dp"
android:layout_width="150dp"
android:layout_height="40dp"/>
<TextView android:text="@string/marks"
android:layout_x="30dp"
android:layout_y="150dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="@+id/editMarks"
android:inputType="number"
android:layout_x="150dp"
android:layout_y="150dp"
android:layout_width="150dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnAdd"
android:text="@string/add"
android:layout_x="30dp"
android:layout_y="200dp"
android:layout_width="100dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnDelete"
android:text="@string/delete"
android:layout_x="150dp"
android:layout_y="200dp"
android:layout_width="100dp"
android:layout_height="40dp"/>n
<Button android:id="@+id/btnModify"
android:text="@string/modify"
android:layout_x="30dp"
android:layout_y="250dp"
android:layout_width="100dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnView"
android:text="@string/view"
android:layout_x="150dp"
android:layout_y="250dp"
android:layout_width="100dp"
android:layout_height="40dp"/>
<Button android:id="@+id/btnViewAll"
android:text="@string/view_all"
android:layout_x="30dp"
BuildersEngineeringCollege
27
android:layout_y="300dp"
android:layout_width="100dp"
android:layout_height="40dp"/>
</AbsoluteLayout>
mainactivity.java
package com.sg.database;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener
{
EditText editRollno,editName,editMarks;
Button btnAdd,btnDelete,btnModify,btnView,btnViewAll,btnShowInfo;
SQLiteDatabase db;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editRollno=(EditText)findViewById(R.id.editRollno);
editName=(EditText)findViewById(R.id.editName);
editMarks=(EditText)findViewById(R.id.editMarks);
btnAdd=(Button)findViewById(R.id.btnAdd);
btnDelete=(Button)findViewById(R.id.btnDelete);
btnModify=(Button)findViewById(R.id.btnModify);
btnView=(Button)findViewById(R.id.btnView);
btnViewAll=(Button)findViewById(R.id.btnViewAll);
btnAdd.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnModify.setOnClickListener(this);
btnView.setOnClickListener(this);
btnViewAll.setOnClickListener(this);
db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name
VARCHAR,marks VARCHAR);");
}
public void onClick(View view)
{
if(view==btnAdd)
{
BuildersEngineeringCollege
28
if(editRollno.getText().toString().trim().length()==0||
editName.getText().toString().trim().length()==0||
editMarks.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter all values");
return;
}
db.execSQL("INSERT INTO student
VALUES('"+editRollno.getText()+"','"+editName.getText()+
"','"+editMarks.getText()+"');");
showMessage("Success", "Record added");
clearText();
}
if(view==btnDelete)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE
rollno='"+editRollno.getText()+"'");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Rollno");
}
clearText();
}
if(view==btnModify)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
db.execSQL("UPDATE student SET
name='"+editName.getText()+"',marks='"+editMarks.getText()+
"' WHERE rollno='"+editRollno.getText()+"'");
showMessage("Success", "Record Modified");
}
else
{
showMessage("Error", "Invalid Rollno");
BuildersEngineeringCollege
29
}
clearText();
}
if(view==btnView)
{
if(editRollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+editRollno.getText()+"'", null);
if(c.moveToFirst())
{
editName.setText(c.getString(1));
editMarks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
if(view==btnViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"n");
buffer.append("Name: "+c.getString(1)+"n");
buffer.append("Marks: "+c.getString(2)+"nn");
}
showMessage("Student Details", buffer.toString());
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
editRollno.setText("");
BuildersEngineeringCollege
30
editName.setText("");
editMarks.setText("");
editRollno.requestFocus();
}
}
Output:
Result:
Thus the application that makes use of database is developed and tested using
android studio.
BuildersEngineeringCollege
31
Ex.No: 6 Develop an application that makes use of RSS Feed
Date:
Aim:
To develop an application that makes use of RSS Feed using android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code also create supporting layout files.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code also create the supporting java codes.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.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"
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="com.linuxpert.mitcourses.MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lstMain" />
</RelativeLayout>
BuildersEngineeringCollege
32
activity_rss_loader.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"
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="com.linuxpert.mitcourses.RssLoader">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lstRssFeed"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/feedProgress"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:indeterminate="false" />
</RelativeLayout>
main_list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="1"
android:id="@+id/txtIndex"
android:textStyle="normal"
android:textSize="20sp"
android:layout_marginRight="10dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Title"
BuildersEngineeringCollege
33
android:id="@+id/txtTitle"
android:textSize="20sp"
android:textStyle="normal" />
</LinearLayout>
rss_list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Title"
android:id="@+id/txtTitle"
android:textStyle="bold"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="http://www.example.com/post1"
android:id="@+id/txtLink" />
</LinearLayout>
mainactivity.java
package com.sg.mitcourses;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Course> courses = new ArrayList<Course>();
public static String rss_path = "http://192.168.1.254/mit/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*ADD THE COURSES TO LIST*/
courses.add(new Course("Aeronautics and Astronautics", "mit-aeronautics-and-
astronautics.xml"));
BuildersEngineeringCollege
34
courses.add(new Course("Anthropology","mit-anthropology.xml"));
courses.add(new Course("Architecture","mit-architecture.xml"));
courses.add(new Course("Athletics, Physical Education and Recreation","mit-athletics-
physical-education-and-recreation.xml"));
courses.add(new Course("Biological Engineering","mit-biological-engineering.xml"));
courses.add(new Course("Biology","mit-biology.xml"));
/*END OF LIST*/
ListView mainList = (ListView)findViewById(R.id.lstMain);
MainListAdapter adapter = new
MainListAdapter(this,R.layout.main_list_layout,courses);
mainList.setAdapter(adapter);
MainListItemClickListener listener = new MainListItemClickListener(courses,this);
mainList.setOnItemClickListener(listener);
}
}
MainListAdapter.java
package com.sg.mitcourses;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class MainListAdapter extends ArrayAdapter<Course> {
int layoutResourceId;
Context context;
ArrayList<Course> list;
public MainListAdapter(Context context, int resource, ArrayList<Course> objects) {
super(context, resource, objects);
this.layoutResourceId = resource;
this.context = context;
this.list = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
BuildersEngineeringCollege
35
MainListHolder holder = null;
if(row==null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId,parent,false);
holder = new MainListHolder();
holder.indexTxt = (TextView)row.findViewById(R.id.txtIndex);
holder.titleTxt = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
holder = (MainListHolder)row.getTag();
Course course = list.get(position);
holder.indexTxt.setText(String.valueOf(position+1));
holder.titleTxt.setText(course.getTitle());
return row;
}
static class MainListHolder{
TextView indexTxt,titleTxt;
}
}
MainListItemClickListener.java
package com.sg.mitcourses;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
public class MainListItemClickListener implements AdapterView.OnItemClickListener {
ArrayList<Course> list;
Activity activity;
public MainListItemClickListener(ArrayList<Course> list, Activity activity) {
this.list = list;
this.activity = activity;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Course course = list.get(position);
BuildersEngineeringCollege
36
Intent intent = new Intent(activity,RssLoader.class);
intent.putExtra("title",course.getTitle());
intent.putExtra("link",MainActivity.rss_path+course.getUrl());
/*Remember we set the rss_path variable private so it can be called by 'dot' (.)
operator.*/
activity.startActivity(intent);
}
}
RssItem.java
package com.sg.mitcourses;
public class RssItem {
private String title,link;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
RssItemClickListener.java
package com.sg.mitcourses;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import java.util.ArrayList;
public class RssItemClickListener implements AdapterView.OnItemClickListener {
Activity activity;
ArrayList<RssItem> list;
BuildersEngineeringCollege
37
public RssItemClickListener(Activity activity, ArrayList<RssItem> list) {
this.activity = activity;
this.list = list;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(list.get(position).getLink()));
activity.startActivity(intent);
//opens the link in a new browser window
}
}
RssListAdapter.java
package com.sg.mitcourses;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class RssListAdapter extends ArrayAdapter<RssItem> {
int layoutResourceId;
Context context;
ArrayList<RssItem> list;
public RssListAdapter(Context context, int resource, ArrayList<RssItem> objects) {
super(context, resource, objects);
this.layoutResourceId = resource;
this.context = context;
this.list = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RssItemHolder holder = null;
if(row==null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
BuildersEngineeringCollege
38
row = inflater.inflate(layoutResourceId,parent,false);
holder = new RssItemHolder();
holder.titleTxt = (TextView)row.findViewById(R.id.txtTitle);
holder.linkTxt = (TextView)row.findViewById(R.id.txtLink);
row.setTag(holder);
}
else
holder = (RssItemHolder)row.getTag();
RssItem item = list.get(position);
holder.titleTxt.setText(item.getTitle());
holder.linkTxt.setText(item.getLink());
return row;
}
static class RssItemHolder{
TextView titleTxt,linkTxt;
}
}
RssLoader.java
package com.sg.mitcourses;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.util.ArrayList;
public class RssLoader extends AppCompatActivity {
Activity local;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rss_loader);
local = this;
BuildersEngineeringCollege
39
progressBar = (ProgressBar) findViewById(R.id.feedProgress);
Intent i = getIntent();
//gets the root intent
String title = i.getStringExtra("title");
//gets the String supplied with the tag title
String url = i.getStringExtra("link");
//gets the String supplied with the tag link
getRssData getRssData = new getRssData();
getRssData.execute(url);
//actionbar
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private class getRssData extends AsyncTask<String,Void,ArrayList<RssItem>>{
@Override
protected ArrayList<RssItem> doInBackground(String... params) {
try {
RssReader rssReader = new RssReader(params[0]);
//create rss reader
return rssReader.getItems();
//returns items parsed from rss file
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(ArrayList<RssItem> rssItems) {
if(rssItems!=null) {
ListView rssList = (ListView) findViewById(R.id.lstRssFeed);
RssListAdapter adapter = new RssListAdapter(local, R.layout.rss_list_layout,
rssItems);
rssList.setAdapter(adapter);
rssList.setOnItemClickListener(new RssItemClickListener(local,rssItems));
Toast.makeText(local, "Feed Loaded", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(local,"Could not load feed. Check your network
connections.",Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
BuildersEngineeringCollege
40
}
@Override
protected void onPreExecute() {
Toast.makeText(local,"Loading Feed",Toast.LENGTH_LONG).show();
}
}
}
RssParseHandler.java
package com.sg.mitcourses;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
public class RssParseHandler extends DefaultHandler {
private ArrayList<RssItem> rssItems; //list to store rss items parsed
private RssItem currentItem; //stores the currently parsing RssItem
private boolean parsingTitle, parsingLink; //parsing title/link indicators
public RssParseHandler() {
rssItems = new ArrayList<>();
}
public ArrayList<RssItem> getRssItems() {
return rssItems;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes
attributes) throws SAXException {
if("item".equals(qName)){
currentItem = new RssItem(); //create a new RssItem to store data
} else if ("title".equals(qName)){
parsingTitle = true;
}
else if ("link".equals(qName)){
parsingLink = true;
}
//sets the current item to rss item when parsing item
//sets appropriate indicators to true when opening tags are processed
}
BuildersEngineeringCollege
41
@Override
public void endElement(String uri, String localName, String qName) throws
SAXException {
if("item".equals(qName)){
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)){
parsingTitle = false;
}
else if ("link".equals(qName)){
parsingLink = false;
}
//adds the current item to list
//sets appropriate indicators to false when closing tags are processed
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if(parsingTitle){
if(currentItem!=null) {
currentItem.setTitle(new String(ch, start, length)); //sets title of the current item
}
} else if (parsingLink){
if (currentItem!=null){
currentItem.setLink(new String(ch, start, length)); //sets link of the current item
}
}
/*
* Here we used if(parsingTitle), if(parsingLink).
* These indicators indicate whether title or link is executed.
* It helps to avoid the handler from parsing other unwanted characters inside other rss
tags.
*/
}
}
RssReader.java
package com.sg.mitcourses;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class RssReader {
private String rssUrl;
BuildersEngineeringCollege
42
public RssReader(String rssUrl) {
this.rssUrl = rssUrl;
}
public ArrayList<RssItem> getItems() throws Exception{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
RssParseHandler handler = new RssParseHandler();
parser.parse(rssUrl,handler);
//parse the rss file located at rssUrl using the parsing handler 'handler'.
return handler.getRssItems();
//returns the list of items parsed
}
}
Course.java
package com.blogspot.shuttereditz.mitcourses;
public class Course {
private String title,url;
public Course(String title, String url) {
this.title = title;
this.url = url;
}
public String getTitle() {
return title;
}
public String getUrl() {
return url;
}
}
BuildersEngineeringCollege
43
Output:
Result:
Thus the application that makes use of RSS Feed is developed and tested using
android studio.
BuildersEngineeringCollege
44
Ex.No: 7 Implement an application that implements Multithreading
Date:
Aim:
To implement an application that implements Multithreading using android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.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" >
<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="4dip" >
</ProgressBar>
<TextView
BuildersEngineeringCollege
45
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" >
</TextView>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startProgress"
android:text="Start Progress" >
</Button>
</LinearLayout>
Mainactivity.java
package com.sg.multithread;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private ProgressBar progress;
private TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
text = (TextView) findViewById(R.id.textView1);
}
public void startProgress(View view) {
// do something long
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
doFakeWork();
progress.post(new Runnable() {
@Override
public void run() {
text.setText("Loading");
progress.setProgress(value);
}
});
BuildersEngineeringCollege
46
}
}
};
new Thread(runnable).start();
}
// Simulating something timeconsuming
private void doFakeWork() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
Result:
Thus the application that implements Multithreading is implemented and tested
using android studio.
BuildersEngineeringCollege
47
Ex.No: 8 Develop a native application that uses GPS location information
Date:
Aim:
To develop a native application that uses GPS location information using android
studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/show_Location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show_Location"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
BuildersEngineeringCollege
48
Mainactivity.java
package com.sg.gps;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPStrace extends Service implements
LocationListener{
private final Context context;
boolean isGPSEnabled=false;
boolean canGetLocation=false;
boolean isNetworkEnabled=false;
Location location;
double latitude;
double longtitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10;
private static final long MIN_TIME_BW_UPDATES=1000*60*1;
protected LocationManager locationManager;
public GPStrace(Context context)
{
this.context=context;
getLocation();
}
public Location getLocation()
{
try{
locationManager=(LocationManager)
context.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManag
er.GPS_PROVIDER);
application that draws
basic graphical primitives
on the screen in android
Develop
a native
calculator
application
Implement an application
that creates an alert
upon receiving a
message in android
BuildersEngineeringCollege
49
Develop
an
application that makes
use of RSS Feed
isNetworkEnabled=locationManager.isProviderEnabled(LocationM
anager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled){
}else{
this.canGetLocation=true;
if(isNetworkEnabled){
Develop
an
application that makes
use of database
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
}
if(locationManager!=null){
Write a
mobile
application that creates
alarm clock in android
location=locationManager.getLastKnownLocation(LocationManager
.NETWORK_PROVIDER);
if(location !=null){
latitude=location.getLatitude();
longtitude=location.getLongitude();
FAMOUS QUOTES
}
}
}
if(isGPSEnabled){
if(location==null){
locationManager.requestLocationUpdates(LocationManager.GPS_PR
OVIDER,MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this);
if(locationManager!=null){
location=locationManager.getLastKnownLocation(LocationManager
.GPS_PROVIDER);
if(location!=null){
latitude=location.getLatitude();
longtitude=location.getLongitude();
}
Androidmaifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sg.gps">
<application
BuildersEngineeringCollege
50
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Output:
Result:
Thus the application native application that uses GPS location information is
developed and tested using android studio.
BuildersEngineeringCollege
51
Ex.No: 9 Implement an application that writes data to the SD card
Date:
Aim:
To implement an application that writes data to the SD card using android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.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"
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="com.linuxpert.myfileapp.MainActivity">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/txtWrite"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
BuildersEngineeringCollege
52
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Write"
android:id="@+id/btnWrite"
android:layout_below="@+id/txtWrite"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
android:id="@+id/btnRead"
android:layout_below="@+id/txtWrite"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/txtRead"
android:layout_below="@+id/btnWrite"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp" />
</RelativeLayout>
Mainactivity.java
package com.sg.myfileapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
EditText txtWrite;
Button btnWrite,btnRead;
TextView txtRead;
@Override
protected void onCreate(Bundle savedInstanceState) {
BuildersEngineeringCollege
53
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtWrite = (EditText)findViewById(R.id.txtWrite);
txtRead = (TextView)findViewById(R.id.txtRead);
btnWrite = (Button)findViewById(R.id.btnWrite);
btnRead = (Button)findViewById(R.id.btnRead);
btnWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = txtWrite.getText().toString();//read data from text field
try {
FileOutputStream ofStream = new FileOutputStream(new
File(getFilesDir(),"demo"));
/*
* file output stream which writes into a new file named demo with the path we
get from
* getFilesDir() function which corresponds to internal memory.
* - getCacheDir() - cache memory
*/
OutputStreamWriter osWriter = new OutputStreamWriter(ofStream);
//create a new writer from ofStream
osWriter.write(text);
//writes data into the file
osWriter.close();
ofStream.close();
//closing stream and writer
} catch (IOException e) {
e.printStackTrace();
}
}
});
btnRead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileInputStream ifStream = new FileInputStream(new File(getFilesDir(),"demo"));
/* creates input stream for reading from the file*/
BufferedReader bReader = new BufferedReader(new
InputStreamReader(ifStream));
/* Here we created a new InputStreamReader from the ifStream.
* (Like we created an OutputStreamWriter from ofStream).
* And we've created a BufferedReader from this InputStreamReader.
* The buffered reader is used to read data from a file as Strings.
*/
String read=""; //creating an empty string to save the read data from file.
String line;
/* Here we read the file line by line so String line is used to store the data
* of the current line the reader pointer is positioned at.
*/
while((line=bReader.readLine())!=null){
/*confirms the line is not null so as to execute loop.*/
BuildersEngineeringCollege
54
/*If it is null it means the pointer is at the end of file*/
read+=line+"n";
}
bReader.close();
ifStream.close();
//closing stream and reader
txtRead.setText(read); //setting the text of the text view
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Output:
Result:
Thus the application that writes data to the SD card is implemented and tested using
android studio.
BuildersEngineeringCollege
55
Ex.No: 10 Implement an application that creates an alert upon
Date: receiving a message
Aim:
To implement an application that creates an alert upon receiving a message using
android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.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:id="@+id/simpleDialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alert Dialog" />
<Button
BuildersEngineeringCollege
56
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Alert Dialog"
android:layout_below="@+id/simpleDialog"
android:layout_marginTop="16dp"
android:onClick="showDialog"/>
</RelativeLayout>
Mainactivity.java
package com.sg.alertdialog;
// Simple android alert dialog example
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showDialog(View view){
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Welcome to EBETi");
// Alert dialog button
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Alert dialog action goes here
// onClick button code here
dialog.dismiss();// use dismiss to cancel alert dialog
}
});
alertDialog.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
BuildersEngineeringCollege
57
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Output:
Result:
Thus the application that creates an alert upon receiving a message is implemented
and tested using android studio.
BuildersEngineeringCollege
58
Ex.No: 11 Write a mobile application that creates alarm clock
Date:
Aim:
To write a mobile application that creates alarm clock using android studio.
Procedure:
1. Open eclipse or android studio and select new android project.
2. Give project name and select next.
3. Choose the android version. Choose the lowest android version(Android 2.2) and
select next.
4. Enter the package name. Package name must be two word separated by comma and
click finish.
5. Go to package explorer in the left hand side. Select the project.
6. Go to “res“ folder and select layout. Double click the activitymain.xml file.
7. Now you can see the Graphics layout window.
8. Click the activitymain.xml file and type the code.
9. Go to project explorer and select “src” folder. Now select mainactivity.java file
and type the code.
10. Go to activitymain.xml and right click. Select run as option and select run
configuration.
11. Android output is present in the android emulator.
Program: activitymain.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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MyActivity">
<TimePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/alarmTimePicker"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
BuildersEngineeringCollege
59
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Alarm On/Off"
android:id="@+id/alarmToggle"
android:layout_centerHorizontal="true"
android:layout_below="@+id/alarmTimePicker"
android:onClick="onToggleClicked" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="@+id/alarmText"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_below="@+id/alarmToggle" />
</RelativeLayout>
Alarmactivity.java
package com.sg.alarm;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;
import java.util.Calendar;
public class AlarmActivity extends Activity {
AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static AlarmActivity inst;
private TextView alarmTextView;
public static AlarmActivity instance() {
return inst;
}
BuildersEngineeringCollege
60
@Override
public void onStart() {
super.onStart();
inst = this;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmTextView = (TextView) findViewById(R.id.alarmText);
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void onToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
setAlarmText("");
Log.d("MyActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}
}
Alarmreceiver.java
package com.sg.alarm;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.content.WakefulBroadcastReceiver;
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
BuildersEngineeringCollege
61
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("Alarm! Wake up! Wake up!");
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Alarmservice.java
package com.sg.alarm;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
@Override
public void onHandleIntent(Intent intent) {
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
BuildersEngineeringCollege
62
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmActivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new
NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}
}
Output:
Result:
Thus the application alarm clock is developed and tested using android studio.

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

python project ppt.pptx
python project ppt.pptxpython project ppt.pptx
python project ppt.pptx
 
Layouts in android
Layouts in androidLayouts in android
Layouts in android
 
Android intents
Android intentsAndroid intents
Android intents
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Unit IOT NETCONF.pptx
Unit IOT NETCONF.pptxUnit IOT NETCONF.pptx
Unit IOT NETCONF.pptx
 
Notification android
Notification androidNotification android
Notification android
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
Java swing
Java swingJava swing
Java swing
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
Importance & Principles of Modeling from UML Designing
Importance & Principles of Modeling from UML DesigningImportance & Principles of Modeling from UML Designing
Importance & Principles of Modeling from UML Designing
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
Architecture of .net framework
Architecture of .net frameworkArchitecture of .net framework
Architecture of .net framework
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Android User Interface
Android User InterfaceAndroid User Interface
Android User Interface
 
[Android] Widget Event Handling
[Android] Widget Event Handling[Android] Widget Event Handling
[Android] Widget Event Handling
 
CHAPTER 6 REQUIREMENTS MODELING: SCENARIO based Model , Class based moddel
CHAPTER 6 REQUIREMENTS MODELING: SCENARIO based Model , Class based moddelCHAPTER 6 REQUIREMENTS MODELING: SCENARIO based Model , Class based moddel
CHAPTER 6 REQUIREMENTS MODELING: SCENARIO based Model , Class based moddel
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
 

Ähnlich wie CS6611 Mobile Application Development Lab Manual-2018-19

Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
Utkarsh Mankad
 
Android Development
Android DevelopmentAndroid Development
Android Development
Daksh Semwal
 

Ähnlich wie CS6611 Mobile Application Development Lab Manual-2018-19 (20)

Android
AndroidAndroid
Android
 
Android activity, service, and broadcast recievers
Android activity, service, and broadcast recieversAndroid activity, service, and broadcast recievers
Android activity, service, and broadcast recievers
 
Mobile Worshop Lab guide
Mobile Worshop Lab guideMobile Worshop Lab guide
Mobile Worshop Lab guide
 
React native: building shared components for Android and iOS
React native: building shared components for Android and iOSReact native: building shared components for Android and iOS
React native: building shared components for Android and iOS
 
Ap quiz app
Ap quiz appAp quiz app
Ap quiz app
 
Ios - Introduction to platform & SDK
Ios - Introduction to platform & SDKIos - Introduction to platform & SDK
Ios - Introduction to platform & SDK
 
Android Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_androidAndroid Bootcamp Tanzania:understanding ui in_android
Android Bootcamp Tanzania:understanding ui in_android
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android Lab Mannual 18SUITSP5.docx
Android Lab Mannual 18SUITSP5.docxAndroid Lab Mannual 18SUITSP5.docx
Android Lab Mannual 18SUITSP5.docx
 
Week 5 slides
Week 5 slides Week 5 slides
Week 5 slides
 
Android Intro
Android IntroAndroid Intro
Android Intro
 
Notes Unit4.pptx
Notes Unit4.pptxNotes Unit4.pptx
Notes Unit4.pptx
 
Android Tutorial
Android TutorialAndroid Tutorial
Android Tutorial
 
MOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app developmentMOPCON 2014 - Best software architecture in app development
MOPCON 2014 - Best software architecture in app development
 
Android Application Development - Level 1
Android Application Development - Level 1Android Application Development - Level 1
Android Application Development - Level 1
 
Chapter 01
Chapter 01Chapter 01
Chapter 01
 
Android Development
Android DevelopmentAndroid Development
Android Development
 
Industrial Training in Android Application
Industrial Training in Android ApplicationIndustrial Training in Android Application
Industrial Training in Android Application
 
Xamarin.Android Introduction
Xamarin.Android IntroductionXamarin.Android Introduction
Xamarin.Android Introduction
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgets
 

Mehr von Gobinath Subramaniam

Mehr von Gobinath Subramaniam (20)

CCW332-Digital Marketing Unit-5 Notes
CCW332-Digital Marketing Unit-5 NotesCCW332-Digital Marketing Unit-5 Notes
CCW332-Digital Marketing Unit-5 Notes
 
CCW332-Digital Marketing Unit-4 Notes
CCW332-Digital Marketing Unit-4 NotesCCW332-Digital Marketing Unit-4 Notes
CCW332-Digital Marketing Unit-4 Notes
 
CCW332-Digital Marketing Unit-3 Notes
CCW332-Digital Marketing Unit-3 NotesCCW332-Digital Marketing Unit-3 Notes
CCW332-Digital Marketing Unit-3 Notes
 
CCCW332-Digital Marketing Unit-2 Notes
CCCW332-Digital Marketing Unit-2 NotesCCCW332-Digital Marketing Unit-2 Notes
CCCW332-Digital Marketing Unit-2 Notes
 
CCW332-Digital Marketing Unit-1 Notes
CCW332-Digital Marketing Unit-1 NotesCCW332-Digital Marketing Unit-1 Notes
CCW332-Digital Marketing Unit-1 Notes
 
CCW332-DIGITAL MARKETING.pdf
CCW332-DIGITAL MARKETING.pdfCCW332-DIGITAL MARKETING.pdf
CCW332-DIGITAL MARKETING.pdf
 
CS878 Green Computing Anna University Question Paper
CS878 Green Computing Anna University Question Paper CS878 Green Computing Anna University Question Paper
CS878 Green Computing Anna University Question Paper
 
OBM752 Hospital Management Question Bank
OBM752 Hospital Management Question BankOBM752 Hospital Management Question Bank
OBM752 Hospital Management Question Bank
 
CS8078-Green Computing Question Bank
CS8078-Green Computing Question BankCS8078-Green Computing Question Bank
CS8078-Green Computing Question Bank
 
CS8078-Green Computing Notes Unit-3
CS8078-Green Computing Notes Unit-3CS8078-Green Computing Notes Unit-3
CS8078-Green Computing Notes Unit-3
 
CS8078-Green Computing Notes Unit-2
CS8078-Green Computing Notes Unit-2CS8078-Green Computing Notes Unit-2
CS8078-Green Computing Notes Unit-2
 
CS8078-Green Computing Unit-1
CS8078-Green Computing Unit-1CS8078-Green Computing Unit-1
CS8078-Green Computing Unit-1
 
CS8592-OOAD Question Bank
CS8592-OOAD  Question BankCS8592-OOAD  Question Bank
CS8592-OOAD Question Bank
 
CS8592-OOAD Lecture Notes Unit-5
CS8592-OOAD Lecture Notes Unit-5 CS8592-OOAD Lecture Notes Unit-5
CS8592-OOAD Lecture Notes Unit-5
 
CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4CS8592-OOAD Lecture Notes Unit-4
CS8592-OOAD Lecture Notes Unit-4
 
CS8592-OOAD Lecture Notes Unit-3
CS8592-OOAD Lecture Notes Unit-3CS8592-OOAD Lecture Notes Unit-3
CS8592-OOAD Lecture Notes Unit-3
 
CS8592-OOAD Lecture Notes Unit-2
CS8592-OOAD Lecture Notes Unit-2CS8592-OOAD Lecture Notes Unit-2
CS8592-OOAD Lecture Notes Unit-2
 
CS8592-OOAD Lecture Notes Unit-1
CS8592-OOAD Lecture Notes Unit-1CS8592-OOAD Lecture Notes Unit-1
CS8592-OOAD Lecture Notes Unit-1
 
OBM752 Hospital Management Unit-5
OBM752 Hospital Management Unit-5OBM752 Hospital Management Unit-5
OBM752 Hospital Management Unit-5
 
OBM752-Hospital Management Unit:4
OBM752-Hospital Management Unit:4OBM752-Hospital Management Unit:4
OBM752-Hospital Management Unit:4
 

Kürzlich hochgeladen

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Kürzlich hochgeladen (20)

SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

CS6611 Mobile Application Development Lab Manual-2018-19

  • 1. BuildersEngineeringCollege LAB MANUAL Subject Code : CS6611 Subject Name : MOBILE APPLICATION DEVELOPMENT LABORATORY Year : III Sem : VI Prepared by Mr. S. GOBINATH, AP/CSE
  • 2. BuildersEngineeringCollege CS6611- MOBILE APPLICATION DEVELOPMENT LABORATORY L T P C 0 0 3 2 OBJECTIVES: The student should be made to: • Know the components and structure of mobile application development frameworks for Android and windows OS based mobiles. • Understand how to work with various mobile application development frameworks. • Learn the basic and important design concepts and issues of development of mobile applications. • Understand the capabilities and limitations of mobile devices. LIST OF EXPERIMENTS: 1. Develop an application that uses GUI components, Font and Colours. 2. Develop an application that uses Layout Managers and event listeners. 3. Develop a native calculator application. 4. Write an application that draws basic graphical primitives on the screen. 5. Develop an application that makes use of database. 6. Develop an application that makes use of RSS Feed. 7. Implement an application that implements Multi threading. 8. Develop a native application that uses GPS location information. 9. Implement an application that writes data to the SD card. 10. Implement an application that creates an alert upon receiving a message. 11. Write a mobile application that creates alarm clock. TOTAL: 45 PERIODS OUTCOMES: At the end of the course, the student should be able to: • Design and Implement various mobile applications using emulators. • Deploy applications to hand-held devices. LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS Standalone desktops with Windows or Android or iOS or Equivalent Mobile Application Development Tools with appropriate emulators and debuggers – 30 Nos.
  • 3. BuildersEngineeringCollege 1 Ex.No: 1 Develop an application that uses GUI components, Font and Colours Date: Aim: To develop an android application that uses GUI components, Font and Colours using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.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" 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="helloapp.example.com.demoapp.MainActivity" android:background="#03acda" android:clickable="false" android:id="@+id/canvas"> <TextView
  • 4. BuildersEngineeringCollege 2 android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Username" android:id="@+id/txtUsername" android:textColorHighlight="#4d77e2" android:textIsSelectable="true" android:typeface="serif" android:textStyle="bold|italic" android:textColor="#ffffff" android:textSize="20dp" android:layout_marginBottom="5dp" android:layout_above="@+id/edtUsername" android:layout_alignParentLeft="true"/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/edtUsername" android:hint="Enter Your Username" android:textColorHint="#7a7a7a" android:layout_above="@+id/txtPassword" android:layout_alignLeft="@id/txtPassword" android:layout_alignRight="@+id/imageView" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Password" android:id="@+id/txtPassword" android:textStyle="bold|italic" android:typeface="serif" android:textColor="#ffffff" android:textIsSelectable="false" android:textSize="20dp" android:layout_centerVertical="true" android:layout_alignRight="@+id/txtUsername" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="10" android:id="@+id/edtPassword" android:hint="Enter Your Password" android:textColorHint="#7a7a7a" android:layout_below="@+id/txtPassword" android:layout_alignLeft="@+id/txtPassword" android:layout_alignRight="@+id/textView" /> <Button android:layout_width="wrap_content"
  • 5. BuildersEngineeringCollege 3 android:layout_height="wrap_content" android:text="Change Background Color" android:id="@+id/btnLogin" android:typeface="serif" android:layout_below="@+id/edtPassword" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:text="Note: Username &quot;CSE&quot; and Password &quot;EBET&quot;" android:id="@+id/textView" android:textStyle="normal|italic" android:typeface="serif" android:textColor="#fbfbfb" android:layout_below="@+id/btnLogin" android:layout_centerHorizontal="true" android:layout_marginTop="41dp" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" android:src="@drawable/ebetlogo" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_above="@+id/txtUsername" /> <Button style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change Font" android:id="@+id/btnFont" android:layout_below="@+id/textView" android:layout_alignLeft="@+id/btnLogin" android:layout_alignStart="@+id/btnLogin" android:layout_alignRight="@+id/btnLogin" android:layout_alignEnd="@+id/btnLogin" /> </RelativeLayout> mainactivity.java package com.sg.gui; import android.graphics.Typeface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button;
  • 6. BuildersEngineeringCollege 4 import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button btnLogin; Button btnFont; EditText edtUsername, edtPassword; RelativeLayout canvas; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnLogin = (Button)findViewById(R.id.btnLogin); btnFont = (Button)findViewById(R.id.btnFont); edtUsername = (EditText)findViewById(R.id.edtUsername); edtPassword =(EditText)findViewById(R.id.edtPassword); canvas = (RelativeLayout)findViewById(R.id.canvas); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String username=null, password=null; username = edtUsername.getText().toString(); password = edtPassword.getText().toString(); if(username.equals("CSE") && password.equals("EBET")){ Toast.makeText(getApplicationContext(),"User authenticated!",Toast.LENGTH_LONG).show(); canvas.setBackgroundResource(R.color.bgcolor); }else{ Toast.makeText(getApplicationContext(),"Please check your Credentials",Toast.LENGTH_LONG).show(); } } }); btnFont.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TextView tx = (TextView)findViewById(R.id.textView); Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/sansbold.ttf"); tx.setTypeface(custom_font);
  • 8. BuildersEngineeringCollege 6 Result: Thus the android application that uses GUI components, Font and Colours is developed and tested using android studio.
  • 9. BuildersEngineeringCollege 7 Ex.No: 2 Develop an application that uses Layout Managers and event listeners Date: Aim: To develop an android application that uses Layout Managers and event listeners using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Layout and Listener Program"
  • 10. BuildersEngineeringCollege 8 android:id="@+id/txtSample" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="fill_parent" android:layout_below="@+id/txtSample" android:layout_centerHorizontal="true"> <ImageView android:layout_width="111dp" android:layout_height="111dp" android:id="@+id/imageView" android:layout_gravity="center_horizontal" android:src="@drawable/number1" /> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tableRow" android:orientation="horizontal"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" android:id="@+id/btnClick" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Long Click Me" android:id="@+id/btnLongClick" /> </TableRow> </TableLayout> <GridLayout android:layout_width="match_parent" android:layout_height="fill_parent" android:id="@+id/lytGrid"> <Button android:layout_width="202dp" android:layout_height="156dp" android:text="Click or Long CLick n Me" android:id="@+id/btnAll"
  • 11. BuildersEngineeringCollege 9 android:layout_column="3" android:layout_row="0" android:layout_columnSpan="1" android:layout_rowSpan="2" /> <Button android:layout_width="143dp" android:layout_height="match_parent" android:text="Show nMy nName" android:id="@+id/btnShowName" android:layout_row="1" android:layout_column="2" android:layout_rowSpan="3" /> <EditText android:layout_width="match_parent" android:layout_height="62dp" android:id="@+id/txtName" android:layout_row="3" android:layout_column="3" android:hint="Enter your Name" android:layout_columnSpan="1" android:layout_rowSpan="1" /> </GridLayout> </LinearLayout> </RelativeLayout> Program: mainactivity.java package com.sg.layout; import android.content.ClipData; import android.content.ClipDescription; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.DragEvent; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.sg.layout.R; public class MainActivity extends AppCompatActivity {
  • 12. BuildersEngineeringCollege 10 Button clickBtn, longClickBtn, allBtn, btnShow; TextView sample; EditText nameTxt; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); clickBtn = (Button) findViewById(R.id.btnClick); longClickBtn = (Button) findViewById(R.id.btnLongClick); allBtn = (Button) findViewById(R.id.btnAll); btnShow = (Button) findViewById(R.id.btnShowName); sample = (TextView) findViewById(R.id.txtSample); nameTxt = (EditText) findViewById(R.id.txtName); clickBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Click event!", Toast.LENGTH_SHORT).show(); } }); longClickBtn.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "Long click event!", Toast.LENGTH_SHORT).show(); return false; } }); allBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "You Just Clicked Me!", Toast.LENGTH_SHORT).show(); } }); allBtn.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(getApplicationContext(), "You clicked me for long!", Toast.LENGTH_SHORT).show(); return false; } });
  • 13. BuildersEngineeringCollege 11 btnShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sample.setText(nameTxt.getText().toString()); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
  • 14. BuildersEngineeringCollege 12 Output: Result: Thus the android application that Layout Managers and event listeners is developed and tested using android studio.
  • 15. BuildersEngineeringCollege 13 Ex.No: 3 Develop a native calculator application Date: Aim: To develop a native calculator application using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <EditText android:layout_width="fill_parent" android:layout_height="77dp"
  • 16. BuildersEngineeringCollege 14 android:id="@+id/txtScreen" android:inputType="number|numberDecimal|numberSigned" android:textSize="@dimen/activity_vertical_margin"/> <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent"> <TableRow android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1" android:id="@+id/btn1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2" android:id="@+id/btn2" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="3" android:id="@+id/btn3" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="4" android:id="@+id/btn4" /> </TableRow> <TableRow android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="5" android:id="@+id/btn5" /> <Button android:layout_width="wrap_content"
  • 17. BuildersEngineeringCollege 15 android:layout_height="wrap_content" android:text="6" android:id="@+id/btn6" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="7" android:id="@+id/btn7" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="8" android:id="@+id/btn8" /> </TableRow> <TableRow android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="9" android:id="@+id/btn9" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0" android:id="@+id/btn0" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="." android:id="@+id/btnDot" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="C" android:id="@+id/btnClear" /> </TableRow> <TableRow android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal">
  • 18. BuildersEngineeringCollege 16 <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:id="@+id/btnAdd" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-" android:id="@+id/btnSubtract" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="/" android:id="@+id/btnDivide" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="*" android:id="@+id/btnMultiply" /> </TableRow> <TableRow android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="=" android:id="@+id/btnEquals" android:layout_span="4" /> </TableRow> </TableLayout> </LinearLayout> </RelativeLayout> mainactivity.java package com.sg.calculator; import android.annotation.TargetApi; import android.os.Build; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View;
  • 19. BuildersEngineeringCollege 17 import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.sg.calculator.R; public class MainActivity extends ActionBarActivity { private EditText Scr; private float NumberBf=0, NumAf, result=0; private String Operation, mod="replace"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Scr = (EditText) findViewById(R.id.txtScreen); Scr.setText(""); int idList[] = {R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9, R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide, R.id.btnClear,R.id.btnEquals, R.id.btnDot, }; for(int id:idList) { View v = (View) findViewById(id); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onButtonClick(v); } }); } } public void mMath(String str) { mResult(); try { NumberBf = Float.parseFloat(Scr.getText().toString()); Operation = str; }catch (Exception e) { Toast.makeText(getApplicationContext(),(CharSequence) e, Toast.LENGTH_SHORT).show(); Scr.setText("SYNTAX ERROR"); mod="replace"; } } @TargetApi(Build.VERSION_CODES.GINGERBREAD) public void mResult() { NumAf = 0;
  • 20. BuildersEngineeringCollege 18 if(!Scr.getText().toString().trim().isEmpty()) NumAf = Float.parseFloat(Scr.getText().toString()); result = NumAf; try { switch (Operation) { case "+": result = NumAf + NumberBf; break; case "-": result = NumberBf - NumAf; break; case "*": result = NumAf * NumberBf; break; case "/": result = NumberBf / NumAf; break; default: result = NumAf; break; } } catch (Exception e) { e.printStackTrace(); } Scr.setText(String.valueOf(result)); mod = "replace"; } public void getKeyboard(String str) { String ScrTxt = Scr.getText().toString(); ScrTxt += str; if(mod.equals("add")) Scr.setText(ScrTxt); else Scr.setText(str); mod = "add"; } public void onButtonClick(View v) { switch (v.getId()) { case R.id.btnClear: //Clear Scr.setText(""); NumberBf = 0; Operation = ""; break; case R.id.btnAdd: mMath("+"); break;
  • 21. BuildersEngineeringCollege 19 case R.id.btnSubtract: if(mod.equals("replace")) { String numb = ((Button) v).getText().toString(); getKeyboard(numb); } else mMath("-"); break; case R.id.btnMultiply: mMath("*"); break; case R.id.btnDivide: mMath("/"); break; case R.id.btnEquals: mResult(); Operation = ""; NumberBf = 0; break; default: String numb = ((Button) v).getText().toString(); getKeyboard(numb); break; } } }
  • 22. BuildersEngineeringCollege 20 Output: Result: Thus the native calculator application is developed and tested using android studio.
  • 23. BuildersEngineeringCollege 21 Ex.No: 4 Write an application that draws basic graphical Date: primitives on the screen Aim: To write an application that draws basic graphical primitives on the screen using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java and create samplecanvas.java files and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.xml <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context="com.sg.graphic.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
  • 24. BuildersEngineeringCollege 22 android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" /> </android.support.design.widget.CoordinatorLayout> mainactivity.java package com.sg.graphic; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); com.sg.graphic.Canvas1 drawView = new Canvas1(this); setContentView(drawView); } } Canvas.java package com.sg.graphic; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; public class Canvas1 extends View{ Paint paint = new Paint();
  • 25. BuildersEngineeringCollege 23 public Canvas1(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { paint.setColor(Color.BLUE); paint.setStrokeWidth(0); canvas.drawRect(100, 100, 300, 300, paint); paint.setColor(Color.GREEN); canvas.drawCircle(200, 400, 75, paint); paint.setColor(Color.MAGENTA); paint.setStrokeWidth(4); canvas.drawLine(100, 540, 300, 540, paint); paint.setColor(getResources().getColor(R.color.teal_blue)); canvas.drawText("Graphical Primitive",100,50,paint); paint.setColor(Color.RED); paint.setStrokeWidth(6); canvas.drawPoint(200,600,paint); } }
  • 26. BuildersEngineeringCollege 24 Output: Result: Thus the application that draws basic graphical primitives on the screen is developed and tested using android studio.
  • 27. BuildersEngineeringCollege 25 Ex.No: 5 Develop an application that makes use of database Date: Aim: To develop an application that makes use of database using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.xml <?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myLayout" android:stretchColumns="0" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="@string/title" android:layout_x="110dp" android:layout_y="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:text="@string/roll_no" android:layout_x="30dp" android:layout_y="50dp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <EditText android:id="@+id/editRollno" android:inputType="number"
  • 28. BuildersEngineeringCollege 26 android:layout_x="150dp" android:layout_y="50dp" android:layout_width="150dp" android:layout_height="40dp"/> <TextView android:text="@string/name" android:layout_x="30dp" android:layout_y="100dp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <EditText android:id="@+id/editName" android:inputType="text" android:layout_x="150dp" android:layout_y="100dp" android:layout_width="150dp" android:layout_height="40dp"/> <TextView android:text="@string/marks" android:layout_x="30dp" android:layout_y="150dp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <EditText android:id="@+id/editMarks" android:inputType="number" android:layout_x="150dp" android:layout_y="150dp" android:layout_width="150dp" android:layout_height="40dp"/> <Button android:id="@+id/btnAdd" android:text="@string/add" android:layout_x="30dp" android:layout_y="200dp" android:layout_width="100dp" android:layout_height="40dp"/> <Button android:id="@+id/btnDelete" android:text="@string/delete" android:layout_x="150dp" android:layout_y="200dp" android:layout_width="100dp" android:layout_height="40dp"/>n <Button android:id="@+id/btnModify" android:text="@string/modify" android:layout_x="30dp" android:layout_y="250dp" android:layout_width="100dp" android:layout_height="40dp"/> <Button android:id="@+id/btnView" android:text="@string/view" android:layout_x="150dp" android:layout_y="250dp" android:layout_width="100dp" android:layout_height="40dp"/> <Button android:id="@+id/btnViewAll" android:text="@string/view_all" android:layout_x="30dp"
  • 29. BuildersEngineeringCollege 27 android:layout_y="300dp" android:layout_width="100dp" android:layout_height="40dp"/> </AbsoluteLayout> mainactivity.java package com.sg.database; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity implements OnClickListener { EditText editRollno,editName,editMarks; Button btnAdd,btnDelete,btnModify,btnView,btnViewAll,btnShowInfo; SQLiteDatabase db; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editRollno=(EditText)findViewById(R.id.editRollno); editName=(EditText)findViewById(R.id.editName); editMarks=(EditText)findViewById(R.id.editMarks); btnAdd=(Button)findViewById(R.id.btnAdd); btnDelete=(Button)findViewById(R.id.btnDelete); btnModify=(Button)findViewById(R.id.btnModify); btnView=(Button)findViewById(R.id.btnView); btnViewAll=(Button)findViewById(R.id.btnViewAll); btnAdd.setOnClickListener(this); btnDelete.setOnClickListener(this); btnModify.setOnClickListener(this); btnView.setOnClickListener(this); btnViewAll.setOnClickListener(this); db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS student(rollno VARCHAR,name VARCHAR,marks VARCHAR);"); } public void onClick(View view) { if(view==btnAdd) {
  • 30. BuildersEngineeringCollege 28 if(editRollno.getText().toString().trim().length()==0|| editName.getText().toString().trim().length()==0|| editMarks.getText().toString().trim().length()==0) { showMessage("Error", "Please enter all values"); return; } db.execSQL("INSERT INTO student VALUES('"+editRollno.getText()+"','"+editName.getText()+ "','"+editMarks.getText()+"');"); showMessage("Success", "Record added"); clearText(); } if(view==btnDelete) { if(editRollno.getText().toString().trim().length()==0) { showMessage("Error", "Please enter Rollno"); return; } Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+editRollno.getText()+"'", null); if(c.moveToFirst()) { db.execSQL("DELETE FROM student WHERE rollno='"+editRollno.getText()+"'"); showMessage("Success", "Record Deleted"); } else { showMessage("Error", "Invalid Rollno"); } clearText(); } if(view==btnModify) { if(editRollno.getText().toString().trim().length()==0) { showMessage("Error", "Please enter Rollno"); return; } Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+editRollno.getText()+"'", null); if(c.moveToFirst()) { db.execSQL("UPDATE student SET name='"+editName.getText()+"',marks='"+editMarks.getText()+ "' WHERE rollno='"+editRollno.getText()+"'"); showMessage("Success", "Record Modified"); } else { showMessage("Error", "Invalid Rollno");
  • 31. BuildersEngineeringCollege 29 } clearText(); } if(view==btnView) { if(editRollno.getText().toString().trim().length()==0) { showMessage("Error", "Please enter Rollno"); return; } Cursor c=db.rawQuery("SELECT * FROM student WHERE rollno='"+editRollno.getText()+"'", null); if(c.moveToFirst()) { editName.setText(c.getString(1)); editMarks.setText(c.getString(2)); } else { showMessage("Error", "Invalid Rollno"); clearText(); } } if(view==btnViewAll) { Cursor c=db.rawQuery("SELECT * FROM student", null); if(c.getCount()==0) { showMessage("Error", "No records found"); return; } StringBuffer buffer=new StringBuffer(); while(c.moveToNext()) { buffer.append("Rollno: "+c.getString(0)+"n"); buffer.append("Name: "+c.getString(1)+"n"); buffer.append("Marks: "+c.getString(2)+"nn"); } showMessage("Student Details", buffer.toString()); } } public void showMessage(String title,String message) { Builder builder=new Builder(this); builder.setCancelable(true); builder.setTitle(title); builder.setMessage(message); builder.show(); } public void clearText() { editRollno.setText("");
  • 33. BuildersEngineeringCollege 31 Ex.No: 6 Develop an application that makes use of RSS Feed Date: Aim: To develop an application that makes use of RSS Feed using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code also create supporting layout files. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code also create the supporting java codes. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.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" 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="com.linuxpert.mitcourses.MainActivity"> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lstMain" /> </RelativeLayout>
  • 34. BuildersEngineeringCollege 32 activity_rss_loader.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" 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="com.linuxpert.mitcourses.RssLoader"> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/lstRssFeed" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/feedProgress" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:indeterminate="false" /> </RelativeLayout> main_list_layout.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="1" android:id="@+id/txtIndex" android:textStyle="normal" android:textSize="20sp" android:layout_marginRight="10dp" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Title"
  • 35. BuildersEngineeringCollege 33 android:id="@+id/txtTitle" android:textSize="20sp" android:textStyle="normal" /> </LinearLayout> rss_list_layout.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Title" android:id="@+id/txtTitle" android:textStyle="bold" android:textSize="20sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:text="http://www.example.com/post1" android:id="@+id/txtLink" /> </LinearLayout> mainactivity.java package com.sg.mitcourses; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ArrayList<Course> courses = new ArrayList<Course>(); public static String rss_path = "http://192.168.1.254/mit/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /*ADD THE COURSES TO LIST*/ courses.add(new Course("Aeronautics and Astronautics", "mit-aeronautics-and- astronautics.xml"));
  • 36. BuildersEngineeringCollege 34 courses.add(new Course("Anthropology","mit-anthropology.xml")); courses.add(new Course("Architecture","mit-architecture.xml")); courses.add(new Course("Athletics, Physical Education and Recreation","mit-athletics- physical-education-and-recreation.xml")); courses.add(new Course("Biological Engineering","mit-biological-engineering.xml")); courses.add(new Course("Biology","mit-biology.xml")); /*END OF LIST*/ ListView mainList = (ListView)findViewById(R.id.lstMain); MainListAdapter adapter = new MainListAdapter(this,R.layout.main_list_layout,courses); mainList.setAdapter(adapter); MainListItemClickListener listener = new MainListItemClickListener(courses,this); mainList.setOnItemClickListener(listener); } } MainListAdapter.java package com.sg.mitcourses; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; public class MainListAdapter extends ArrayAdapter<Course> { int layoutResourceId; Context context; ArrayList<Course> list; public MainListAdapter(Context context, int resource, ArrayList<Course> objects) { super(context, resource, objects); this.layoutResourceId = resource; this.context = context; this.list = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView;
  • 37. BuildersEngineeringCollege 35 MainListHolder holder = null; if(row==null){ LayoutInflater inflater = ((Activity)context).getLayoutInflater(); row = inflater.inflate(layoutResourceId,parent,false); holder = new MainListHolder(); holder.indexTxt = (TextView)row.findViewById(R.id.txtIndex); holder.titleTxt = (TextView)row.findViewById(R.id.txtTitle); row.setTag(holder); } else holder = (MainListHolder)row.getTag(); Course course = list.get(position); holder.indexTxt.setText(String.valueOf(position+1)); holder.titleTxt.setText(course.getTitle()); return row; } static class MainListHolder{ TextView indexTxt,titleTxt; } } MainListItemClickListener.java package com.sg.mitcourses; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.view.View; import android.widget.AdapterView; import java.util.ArrayList; public class MainListItemClickListener implements AdapterView.OnItemClickListener { ArrayList<Course> list; Activity activity; public MainListItemClickListener(ArrayList<Course> list, Activity activity) { this.list = list; this.activity = activity; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Course course = list.get(position);
  • 38. BuildersEngineeringCollege 36 Intent intent = new Intent(activity,RssLoader.class); intent.putExtra("title",course.getTitle()); intent.putExtra("link",MainActivity.rss_path+course.getUrl()); /*Remember we set the rss_path variable private so it can be called by 'dot' (.) operator.*/ activity.startActivity(intent); } } RssItem.java package com.sg.mitcourses; public class RssItem { private String title,link; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } } RssItemClickListener.java package com.sg.mitcourses; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.view.View; import android.widget.AdapterView; import java.util.ArrayList; public class RssItemClickListener implements AdapterView.OnItemClickListener { Activity activity; ArrayList<RssItem> list;
  • 39. BuildersEngineeringCollege 37 public RssItemClickListener(Activity activity, ArrayList<RssItem> list) { this.activity = activity; this.list = list; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(list.get(position).getLink())); activity.startActivity(intent); //opens the link in a new browser window } } RssListAdapter.java package com.sg.mitcourses; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import org.w3c.dom.Text; import java.util.ArrayList; public class RssListAdapter extends ArrayAdapter<RssItem> { int layoutResourceId; Context context; ArrayList<RssItem> list; public RssListAdapter(Context context, int resource, ArrayList<RssItem> objects) { super(context, resource, objects); this.layoutResourceId = resource; this.context = context; this.list = objects; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; RssItemHolder holder = null; if(row==null){ LayoutInflater inflater = ((Activity)context).getLayoutInflater();
  • 40. BuildersEngineeringCollege 38 row = inflater.inflate(layoutResourceId,parent,false); holder = new RssItemHolder(); holder.titleTxt = (TextView)row.findViewById(R.id.txtTitle); holder.linkTxt = (TextView)row.findViewById(R.id.txtLink); row.setTag(holder); } else holder = (RssItemHolder)row.getTag(); RssItem item = list.get(position); holder.titleTxt.setText(item.getTitle()); holder.linkTxt.setText(item.getLink()); return row; } static class RssItemHolder{ TextView titleTxt,linkTxt; } } RssLoader.java package com.sg.mitcourses; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import java.util.ArrayList; public class RssLoader extends AppCompatActivity { Activity local; ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rss_loader); local = this;
  • 41. BuildersEngineeringCollege 39 progressBar = (ProgressBar) findViewById(R.id.feedProgress); Intent i = getIntent(); //gets the root intent String title = i.getStringExtra("title"); //gets the String supplied with the tag title String url = i.getStringExtra("link"); //gets the String supplied with the tag link getRssData getRssData = new getRssData(); getRssData.execute(url); //actionbar getSupportActionBar().setTitle(title); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private class getRssData extends AsyncTask<String,Void,ArrayList<RssItem>>{ @Override protected ArrayList<RssItem> doInBackground(String... params) { try { RssReader rssReader = new RssReader(params[0]); //create rss reader return rssReader.getItems(); //returns items parsed from rss file } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(ArrayList<RssItem> rssItems) { if(rssItems!=null) { ListView rssList = (ListView) findViewById(R.id.lstRssFeed); RssListAdapter adapter = new RssListAdapter(local, R.layout.rss_list_layout, rssItems); rssList.setAdapter(adapter); rssList.setOnItemClickListener(new RssItemClickListener(local,rssItems)); Toast.makeText(local, "Feed Loaded", Toast.LENGTH_SHORT).show(); } else Toast.makeText(local,"Could not load feed. Check your network connections.",Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.INVISIBLE);
  • 42. BuildersEngineeringCollege 40 } @Override protected void onPreExecute() { Toast.makeText(local,"Loading Feed",Toast.LENGTH_LONG).show(); } } } RssParseHandler.java package com.sg.mitcourses; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.util.ArrayList; public class RssParseHandler extends DefaultHandler { private ArrayList<RssItem> rssItems; //list to store rss items parsed private RssItem currentItem; //stores the currently parsing RssItem private boolean parsingTitle, parsingLink; //parsing title/link indicators public RssParseHandler() { rssItems = new ArrayList<>(); } public ArrayList<RssItem> getRssItems() { return rssItems; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if("item".equals(qName)){ currentItem = new RssItem(); //create a new RssItem to store data } else if ("title".equals(qName)){ parsingTitle = true; } else if ("link".equals(qName)){ parsingLink = true; } //sets the current item to rss item when parsing item //sets appropriate indicators to true when opening tags are processed }
  • 43. BuildersEngineeringCollege 41 @Override public void endElement(String uri, String localName, String qName) throws SAXException { if("item".equals(qName)){ rssItems.add(currentItem); currentItem = null; } else if ("title".equals(qName)){ parsingTitle = false; } else if ("link".equals(qName)){ parsingLink = false; } //adds the current item to list //sets appropriate indicators to false when closing tags are processed } @Override public void characters(char[] ch, int start, int length) throws SAXException { if(parsingTitle){ if(currentItem!=null) { currentItem.setTitle(new String(ch, start, length)); //sets title of the current item } } else if (parsingLink){ if (currentItem!=null){ currentItem.setLink(new String(ch, start, length)); //sets link of the current item } } /* * Here we used if(parsingTitle), if(parsingLink). * These indicators indicate whether title or link is executed. * It helps to avoid the handler from parsing other unwanted characters inside other rss tags. */ } } RssReader.java package com.sg.mitcourses; import java.util.ArrayList; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class RssReader { private String rssUrl;
  • 44. BuildersEngineeringCollege 42 public RssReader(String rssUrl) { this.rssUrl = rssUrl; } public ArrayList<RssItem> getItems() throws Exception{ SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); RssParseHandler handler = new RssParseHandler(); parser.parse(rssUrl,handler); //parse the rss file located at rssUrl using the parsing handler 'handler'. return handler.getRssItems(); //returns the list of items parsed } } Course.java package com.blogspot.shuttereditz.mitcourses; public class Course { private String title,url; public Course(String title, String url) { this.title = title; this.url = url; } public String getTitle() { return title; } public String getUrl() { return url; } }
  • 45. BuildersEngineeringCollege 43 Output: Result: Thus the application that makes use of RSS Feed is developed and tested using android studio.
  • 46. BuildersEngineeringCollege 44 Ex.No: 7 Implement an application that implements Multithreading Date: Aim: To implement an application that implements Multithreading using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.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" > <ProgressBar android:id="@+id/progressBar1" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:indeterminate="false" android:max="10" android:padding="4dip" > </ProgressBar> <TextView
  • 47. BuildersEngineeringCollege 45 android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" > </TextView> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startProgress" android:text="Start Progress" > </Button> </LinearLayout> Mainactivity.java package com.sg.multithread; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; public class MainActivity extends Activity { private ProgressBar progress; private TextView text; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progress = (ProgressBar) findViewById(R.id.progressBar1); text = (TextView) findViewById(R.id.textView1); } public void startProgress(View view) { // do something long Runnable runnable = new Runnable() { @Override public void run() { for (int i = 0; i <= 10; i++) { final int value = i; doFakeWork(); progress.post(new Runnable() { @Override public void run() { text.setText("Loading"); progress.setProgress(value); } });
  • 48. BuildersEngineeringCollege 46 } } }; new Thread(runnable).start(); } // Simulating something timeconsuming private void doFakeWork() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } Output: Result: Thus the application that implements Multithreading is implemented and tested using android studio.
  • 49. BuildersEngineeringCollege 47 Ex.No: 8 Develop a native application that uses GPS location information Date: Aim: To develop a native application that uses GPS location information using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/relativeLayout1" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/show_Location" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show_Location" android:layout_centerVertical="true" android:layout_centerHorizontal="true" /> </RelativeLayout>
  • 50. BuildersEngineeringCollege 48 Mainactivity.java package com.sg.gps; import android.app.AlertDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.provider.Settings; public class GPStrace extends Service implements LocationListener{ private final Context context; boolean isGPSEnabled=false; boolean canGetLocation=false; boolean isNetworkEnabled=false; Location location; double latitude; double longtitude; private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10; private static final long MIN_TIME_BW_UPDATES=1000*60*1; protected LocationManager locationManager; public GPStrace(Context context) { this.context=context; getLocation(); } public Location getLocation() { try{ locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE); isGPSEnabled=locationManager.isProviderEnabled(LocationManag er.GPS_PROVIDER); application that draws basic graphical primitives on the screen in android Develop a native calculator application Implement an application that creates an alert upon receiving a message in android
  • 51. BuildersEngineeringCollege 49 Develop an application that makes use of RSS Feed isNetworkEnabled=locationManager.isProviderEnabled(LocationM anager.NETWORK_PROVIDER); if(!isGPSEnabled && !isNetworkEnabled){ }else{ this.canGetLocation=true; if(isNetworkEnabled){ Develop an application that makes use of database locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this); } if(locationManager!=null){ Write a mobile application that creates alarm clock in android location=locationManager.getLastKnownLocation(LocationManager .NETWORK_PROVIDER); if(location !=null){ latitude=location.getLatitude(); longtitude=location.getLongitude(); FAMOUS QUOTES } } } if(isGPSEnabled){ if(location==null){ locationManager.requestLocationUpdates(LocationManager.GPS_PR OVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); if(locationManager!=null){ location=locationManager.getLastKnownLocation(LocationManager .GPS_PROVIDER); if(location!=null){ latitude=location.getLatitude(); longtitude=location.getLongitude(); } Androidmaifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sg.gps"> <application
  • 53. BuildersEngineeringCollege 51 Ex.No: 9 Implement an application that writes data to the SD card Date: Aim: To implement an application that writes data to the SD card using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.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" 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="com.linuxpert.myfileapp.MainActivity"> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/txtWrite" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" />
  • 54. BuildersEngineeringCollege 52 <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Write" android:id="@+id/btnWrite" android:layout_below="@+id/txtWrite" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Read" android:id="@+id/btnRead" android:layout_below="@+id/txtWrite" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:id="@+id/txtRead" android:layout_below="@+id/btnWrite" android:layout_centerHorizontal="true" android:layout_marginTop="44dp" /> </RelativeLayout> Mainactivity.java package com.sg.myfileapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class MainActivity extends AppCompatActivity { EditText txtWrite; Button btnWrite,btnRead; TextView txtRead; @Override protected void onCreate(Bundle savedInstanceState) {
  • 55. BuildersEngineeringCollege 53 super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtWrite = (EditText)findViewById(R.id.txtWrite); txtRead = (TextView)findViewById(R.id.txtRead); btnWrite = (Button)findViewById(R.id.btnWrite); btnRead = (Button)findViewById(R.id.btnRead); btnWrite.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text = txtWrite.getText().toString();//read data from text field try { FileOutputStream ofStream = new FileOutputStream(new File(getFilesDir(),"demo")); /* * file output stream which writes into a new file named demo with the path we get from * getFilesDir() function which corresponds to internal memory. * - getCacheDir() - cache memory */ OutputStreamWriter osWriter = new OutputStreamWriter(ofStream); //create a new writer from ofStream osWriter.write(text); //writes data into the file osWriter.close(); ofStream.close(); //closing stream and writer } catch (IOException e) { e.printStackTrace(); } } }); btnRead.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { FileInputStream ifStream = new FileInputStream(new File(getFilesDir(),"demo")); /* creates input stream for reading from the file*/ BufferedReader bReader = new BufferedReader(new InputStreamReader(ifStream)); /* Here we created a new InputStreamReader from the ifStream. * (Like we created an OutputStreamWriter from ofStream). * And we've created a BufferedReader from this InputStreamReader. * The buffered reader is used to read data from a file as Strings. */ String read=""; //creating an empty string to save the read data from file. String line; /* Here we read the file line by line so String line is used to store the data * of the current line the reader pointer is positioned at. */ while((line=bReader.readLine())!=null){ /*confirms the line is not null so as to execute loop.*/
  • 56. BuildersEngineeringCollege 54 /*If it is null it means the pointer is at the end of file*/ read+=line+"n"; } bReader.close(); ifStream.close(); //closing stream and reader txtRead.setText(read); //setting the text of the text view } catch (IOException e) { e.printStackTrace(); } } }); } } Output: Result: Thus the application that writes data to the SD card is implemented and tested using android studio.
  • 57. BuildersEngineeringCollege 55 Ex.No: 10 Implement an application that creates an alert upon Date: receiving a message Aim: To implement an application that creates an alert upon receiving a message using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.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:id="@+id/simpleDialog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Alert Dialog" /> <Button
  • 58. BuildersEngineeringCollege 56 android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Show Alert Dialog" android:layout_below="@+id/simpleDialog" android:layout_marginTop="16dp" android:onClick="showDialog"/> </RelativeLayout> Mainactivity.java package com.sg.alertdialog; // Simple android alert dialog example import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showDialog(View view){ AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle("Alert"); alertDialog.setMessage("Welcome to EBETi"); // Alert dialog button alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Alert dialog action goes here // onClick button code here dialog.dismiss();// use dismiss to cancel alert dialog } }); alertDialog.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) {
  • 59. BuildersEngineeringCollege 57 // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } Output: Result: Thus the application that creates an alert upon receiving a message is implemented and tested using android studio.
  • 60. BuildersEngineeringCollege 58 Ex.No: 11 Write a mobile application that creates alarm clock Date: Aim: To write a mobile application that creates alarm clock using android studio. Procedure: 1. Open eclipse or android studio and select new android project. 2. Give project name and select next. 3. Choose the android version. Choose the lowest android version(Android 2.2) and select next. 4. Enter the package name. Package name must be two word separated by comma and click finish. 5. Go to package explorer in the left hand side. Select the project. 6. Go to “res“ folder and select layout. Double click the activitymain.xml file. 7. Now you can see the Graphics layout window. 8. Click the activitymain.xml file and type the code. 9. Go to project explorer and select “src” folder. Now select mainactivity.java file and type the code. 10. Go to activitymain.xml and right click. Select run as option and select run configuration. 11. Android output is present in the android emulator. Program: activitymain.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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MyActivity"> <TimePicker android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/alarmTimePicker" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" />
  • 61. BuildersEngineeringCollege 59 <ToggleButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Alarm On/Off" android:id="@+id/alarmToggle" android:layout_centerHorizontal="true" android:layout_below="@+id/alarmTimePicker" android:onClick="onToggleClicked" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="" android:id="@+id/alarmText" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:layout_below="@+id/alarmToggle" /> </RelativeLayout> Alarmactivity.java package com.sg.alarm; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.TimePicker; import android.widget.ToggleButton; import java.util.Calendar; public class AlarmActivity extends Activity { AlarmManager alarmManager; private PendingIntent pendingIntent; private TimePicker alarmTimePicker; private static AlarmActivity inst; private TextView alarmTextView; public static AlarmActivity instance() { return inst; }
  • 62. BuildersEngineeringCollege 60 @Override public void onStart() { super.onStart(); inst = this; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker); alarmTextView = (TextView) findViewById(R.id.alarmText); ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); } public void onToggleClicked(View view) { if (((ToggleButton) view).isChecked()) { Log.d("MyActivity", "Alarm On"); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour()); calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute()); Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class); pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0); alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); } else { alarmManager.cancel(pendingIntent); setAlarmText(""); Log.d("MyActivity", "Alarm Off"); } } public void setAlarmText(String alarmText) { alarmTextView.setText(alarmText); } } Alarmreceiver.java package com.sg.alarm; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.content.WakefulBroadcastReceiver; public class AlarmReceiver extends WakefulBroadcastReceiver { @Override
  • 63. BuildersEngineeringCollege 61 public void onReceive(final Context context, Intent intent) { //this will update the UI with message AlarmActivity inst = AlarmActivity.instance(); inst.setAlarmText("Alarm! Wake up! Wake up!"); //this will sound the alarm tone //this will sound the alarm once, if you wish to //raise alarm in loop continuously then use MediaPlayer and setLooping(true) Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); if (alarmUri == null) { alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); } Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri); ringtone.play(); //this will send a notification message ComponentName comp = new ComponentName(context.getPackageName(), AlarmService.class.getName()); startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); } } Alarmservice.java package com.sg.alarm; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.util.Log; public class AlarmService extends IntentService { private NotificationManager alarmNotificationManager; public AlarmService() { super("AlarmService"); } @Override public void onHandleIntent(Intent intent) { sendNotification("Wake Up! Wake Up!"); } private void sendNotification(String msg) { Log.d("AlarmService", "Preparing to send notification...: " + msg); alarmNotificationManager = (NotificationManager) this .getSystemService(Context.NOTIFICATION_SERVICE);
  • 64. BuildersEngineeringCollege 62 PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, AlarmActivity.class), 0); NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder( this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launcher) .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) .setContentText(msg); alamNotificationBuilder.setContentIntent(contentIntent); alarmNotificationManager.notify(1, alamNotificationBuilder.build()); Log.d("AlarmService", "Notification sent."); } } Output: Result: Thus the application alarm clock is developed and tested using android studio.