Beruflich Dokumente
Kultur Dokumente
Name : __________________________________________
Reg No: __________________________________________
Year : __________________________________________
Branch: __________________________________________
Exp Page
Date Name of the Experiment Mark Signature
No No.
2a
2b
10
11
Jerusalem College of Engineering Department of Information Technology
AIM:
To develop an application using gui components, Fonts and Colors.
ALGORITHM:
1. Create three activities for registration and welcome page.
2. Add the necessary gui components like textbox, label, radio button, checkbox to the
layout page.
3. Set the properties of the gui components by right->click edit text, edit id or modify the
layout.xml file
4. Write the implementation code in java file. Include the necessary packages. Write the
code inside create() function.
5. Get the values entered in the textbox, radio buttons and checkboxes using
findViewById().
6. Invoke putExtra(keyvalue,classname) method to send data from one page to other.
7. Invoke getStringExtra(keyvalue) method to receive data from one page.
8. Write button onclick listener to perform operation when button is clicked
PROGRAM:
MainActivity.java
package com.example.ex1_gui_color_font;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show();
}
}
display_rec.java
package com.example.ex1_gui_color_font;
import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
}
}
Output:
MainAvtivity
display_rec
Result:
AIM:
To develop an application that displays child views in relative positions.
ALGORITHM:
1. Layout changes the style of the design page.
2. The position of each view can be specified as relative to sibling elements (such as to the
left-of or below another view) or in positions relative to the parent RelativeLayout area
(such as aligned to the bottom, left or center).
3. RelativeLayout lets child views specify their position relative to the parent view or to
each other.
4. The value for each layout property is either a Boolean to enable a layout position relative
to the parent RelativeLayout or an ID that references another view in the layout against
which the view should be positioned.
PROGRAM:
<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" >
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</EditText>
<Spinner
android:id="@+id/dates"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/times" />
<Spinner
android:id="@id/times"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_alignParentRight="true" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/dates"
android:layout_below="@id/times"
android:layout_marginRight="44dp"
android:layout_marginTop="34dp"
android:text="Submit" />
</RelativeLayout>
Output:
Result:
AIM:
To develop an application that displays child views in relative positions.
ALGORITHM:
1. Events are a useful way to collect data about a user's interaction with interactive
components of Applications.
2. Design a xml with a textview and two buttons, ok and cancel.
3. Declare instance variables for our objects outside onCreate method.
4. The objects are initialized using findViewById method.
5. Create oclBtnOk object which implements View.OnClickListener interface. This object
has onClick method
6. The onClick method will be invoked when the button is pressed.
7. The TextView content change when a button is clicked.
PROGRAM:
package com.example.ex3_eventlistener;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
t1.setText("Cancel Button Clicked");
}
});
}
}
Output:
Result:
AIM:
To develop a native calculator application to perform operations such as addition, subtraction,
multiplication and division.
ALGORITHM:
1. In the layout create a textbox and buttons for numbers and operators.
2. For each buttons get their id using findviewbyid() and setonclicklistener.
3. Create onclick() method to get the value of each button.
4. Using switch statement compares the ids of the button.
5. Once matched invoke compute function to perform various operations.
PROGRAM:
package com.example.calculator_two;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener
{
Button nine,eig,sev,six,fiv,four,thr,two,one,zero,dot,plus,mins,div,mul,eq,cl;
EditText et;
String s = "0";
int result = 0;
char lO = ' ';
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nine=(Button)findViewById(R.id.b9);
eig=(Button)findViewById(R.id.b8);
sev=(Button)findViewById(R.id.b7);
six=(Button)findViewById(R.id.b6);
fiv=(Button)findViewById(R.id.b5);
four=(Button)findViewById(R.id.b4);
thr=(Button)findViewById(R.id.b3);
two=(Button)findViewById(R.id.b2);
one=(Button)findViewById(R.id.b1);
zero=(Button)findViewById(R.id.b0);
dot=(Button)findViewById(R.id.bd);
plus=(Button)findViewById(R.id.bpl);
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 11
Jerusalem College of Engineering Department of Information Technology
mins=(Button)findViewById(R.id.bmin);
div=(Button)findViewById(R.id.bdiv);
mul=(Button)findViewById(R.id.bmul);
eq=(Button)findViewById(R.id.beq);
cl=(Button)findViewById(R.id.bcl);
et=(EditText)findViewById(R.id.tv);
nine.setOnClickListener(this);
eig.setOnClickListener(this);
sev.setOnClickListener(this);
six.setOnClickListener(this);
fiv.setOnClickListener(this);
four.setOnClickListener(this);
thr.setOnClickListener(this);
two.setOnClickListener(this);
one.setOnClickListener(this);
dot.setOnClickListener(this);
plus.setOnClickListener(this);
mins.setOnClickListener(this);
div.setOnClickListener(this);
mul.setOnClickListener(this);
eq.setOnClickListener(this);
cl.setOnClickListener(this);
et.setOnClickListener(this);
zero.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.b0:
case R.id.b1:
case R.id.b2:
case R.id.b3:
case R.id.b4:
case R.id.b5:
case R.id.b6:
case R.id.b7:
case R.id.b8:
case R.id.b9:
String inDigit = ((Button) v).getText().toString();
if (s.equals("0"))
{
s= inDigit;
}
else {
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 12
Jerusalem College of Engineering Department of Information Technology
s+=inDigit;
}
et.setText(s);
if(lO == '=')
{
result=0;
lO =' ';
}
break;
case R.id.bpl:
compute();
lO = '+';
break;
case R.id.bmin:
compute();
lO = '-';
break;
case R.id.bdiv:
compute();
lO = '/';
break;
case R.id.bmul:
compute();
lO = '*';
break;
case R.id.beq:
compute();
lO = '=';
break;
case R.id.bcl:
result = 0;
s = "0";
lO = ' ';
et.setText("0");
break;
}
}
private void compute()
{
// TODO Auto-generated method stub
int inNum = Integer.parseInt(s);
s = "0";
if (lO == ' ')
{
result = inNum;
}
else if (lO == '+'){
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 13
Jerusalem College of Engineering Department of Information Technology
result += inNum;
}
else if (lO == '-')
{
result -= inNum;
}
else if (lO == '*')
{
result *= inNum;
}
else if (lO == '/')
{
result /= inNum;
}
else if (lO == '=')
{
}
et.setText(String.valueOf(result));
}
}
OUTPUT :
RESULT:
AIM:
To develop an application that draws basic graphical primitives like circle, rectangle, line and
oval on the screen.
ALGORITHM:
1. Import graphics package to use the classes.
2. Create onDraw() method .
3. Create object for paint class, set style for the window and color.
4. Set the color for the circle. Then to draw circle invoke drawcircle() method.
5. Using canvas object invoke drawLine(),drawRectF(),drawOval() method to draw line,
Rectangle and oval shape.
6. Use rotate function to rotate the text.
PROGRAM:
package com.example.user.graphicsdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
public class MainActivity extends Activity {
DemoView demoview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demoview = new DemoView(this);
setContentView(demoview);
}
private class DemoView extends View{
public DemoView(Context context){
super(context);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// custom drawing code here
Paint ob = new Paint();
ob.setStyle(Paint.Style.FILL);
// make the entire canvas white
ob.setColor(Color.WHITE);
canvas.drawPaint(ob);
// draw blue circle with anti aliasing turned off
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 16
Jerusalem College of Engineering Department of Information Technology
ob.setAntiAlias(false);
ob.setColor(Color.GREEN);
canvas.drawCircle(20, 20, 20, ob);
// draw green circle with anti aliasing turned on
ob.setAntiAlias(true);
ob.setColor(Color.CYAN);
canvas.drawCircle(60, 20, 30, ob);
ob.setColor(Color.BLUE);
RectF oval3 = new RectF(250, 50, 350, 400);
canvas.drawOval(oval3, ob);
// draw red rectangle with anti aliasing turned off
ob.setAntiAlias(false);
ob.setColor(Color.MAGENTA);
canvas.drawRect(100, 5, 200, 40, ob);
ob.setAntiAlias(false);
ob.setColor(Color.RED);
canvas.drawLine(250, 50, 350, 400,ob);
// draw the rotated text
canvas.rotate(-45);
ob.setStyle(Paint.Style.FILL);
canvas.drawText("FDP Training MAD", 50, 180, ob);
//undo the rotate
canvas.restore();
}}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}}
OUTPUT:
RESULT:
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "+
newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(long id,String name, String email)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ROWID, id);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
} //---retrieves all the contacts---
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 20
Jerusalem College of Engineering Department of Information Technology
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
db.insertContact(Integer.parseInt(et1.getText().toString()),et2.getText().toString(),
et3.getText().toString());
db.close();
Toast.makeText(getBaseContext(), "Inserted",Toast.LENGTH_SHORT).show();
}
});
//---Select All contacts---
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{
do {
DisplayContact(c);
} while (c.moveToNext());
}
db.close();
}
private void DisplayContact(Cursor c)
{
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"id: " + c.getString(0) +"Name: " + c.getString(1) +
"\n" + "Email: " + c.getString(2),Toast.LENGTH_LONG).show();
}
});
//---Select a contact---
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
Cursor c = db.getContact(Integer.parseInt (et1.getText().toString()));
if (c.moveToFirst())
DisplayContact(c);
else
Toast.makeText(getBaseContext(), "No contact
found",Toast.LENGTH_LONG).show();
db.close();
} private void DisplayContact(Cursor c) {
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 22
Jerusalem College of Engineering Department of Information Technology
OUTPUT:
Insert
Display
Update
Delete
RESULT:
return title;
}
public String getLink()
{
return link;
}
public String getDescription()
{
return description;
}
public void parseXMLAndStoreIt(XmlPullParser myParser)
{
int event;
String text=null;
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT)
{
String name=myParser.getName();
switch (event)
{
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("title"))
{
title = text;
}
else if(name.equals("link"))
{
link = text;
}
else if(name.equals("description"))
{
description = text;
}
else
{
}
break;
}
event = myParser.next();
}
parsingComplete = false; }
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 29
Jerusalem College of Engineering Department of Information Technology
catch (Exception e)
{
e.printStackTrace();
}
}
public void fetchXML()
{
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
}
catch (Exception e)
{
} }
});
thread.start();
}
}
MainActivity.java
package com.example.rssfeed;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 30
Jerusalem College of Engineering Department of Information Technology
import android.widget.EditText;
import android.widget.TextView;
import java.util.Set;
public class MainActivity extends Activity
{
EditText title,link,description;
Button b1,b2;
private String finalUrl="http://tutorialspoint.com/android/sampleXML.xml";
private HandleXML obj;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = (EditText) findViewById(R.id.editText);
link = (EditText) findViewById(R.id.editText2);
description = (EditText) findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
obj = new HandleXML(finalUrl);
obj.fetchXML();
while(obj.parsingComplete);
title.setText(obj.getTitle());
link.setText(obj.getLink());
description.setText(obj.getDescription());
}
});
b2.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v)
{
Intent in=new Intent(MainActivity.this,Second.class);
startActivity(in);
}
});
}
@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;
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 31
Jerusalem College of Engineering Department of Information Technology
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// 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);
}
}
Second.java
package com.example.rssfeed;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class Second extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
WebView w1=(WebView)findViewById(R.id.webView);
w1.loadUrl("http://tutorialspoint.com/android/sampleXML.xml");
}
}
Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
OUTPUT:
RESULT:
Ex No: 7 Multithreading
Date
AIM:
To implement an application that implements Multithreading.
ALGORITHM:
1. In the design layout add two textviews and a button.
2. In mainactivity java file, create object for handler class.
3. using handler object invoke postDelayedfuntion.
4. Create object for runnable class.
5. Inside run method call a userdefined function. This function has an explicit intent to
invoke a webpage.
6. Oncreate thread starts followed by runnable thread.
PROGRAM:
package com.example.multithread;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Handler hand = new Handler();
Button clickme;
TextView timer;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = (TextView) findViewById(R.id.timer);
clickme = (Button) findViewById(R.id.clickme);
hand.postDelayed(run, 1000);
}
Runnable run = new Runnable()
{
@Override
public void run()
{
updateTime();
}
};
public void updateTime()
{
timer.setText("" + (Integer.parseInt(timer.getText().toString()) - 1));
if (Integer.parseInt(timer.getText().toString()) == 0)
{
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com/"));
startActivity(browserIntent);
}
else {
hand.postDelayed(run, 1000);
} } }
OUTPUT:
RESULT:
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e)
{
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS()
{
if(locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
} }
/**
* Function to get latitude
* */
public double getLatitude()
{
if(location != null)
{
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 38
Jerusalem College of Engineering Department of Information Technology
latitude = location.getLatitude();
} return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude()
{
if(location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 39
Jerusalem College of Engineering Department of Information Technology
} @Override
public void onLocationChanged(Location location) {
} @Override
public void onProviderDisabled(String provider) {
} @Override
public void onProviderEnabled(String provider) {
} @Override
public void onStatusChanged(String provider, int status, Bundle extras) {
} @Override
public IBinder onBind(Intent arg0) {
return null;
}}
MainActivity.java
package com.example.gpsdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.location.*;
import android.content.Context;
import android.widget.*;
public class MainActivity extends Activity
{
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.button1);
btnShowLocation.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View arg0)
{
// create class object
gps = new GPSTracker(MainActivity.this);
// check if GPS enabled
if(gps.canGetLocation())
{
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude +
"\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else
{
// can't get location
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 40
Jerusalem College of Engineering Department of Information Technology
OUTPUT
RESULT:
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 41
Jerusalem College of Engineering Department of Information Technology
AIM:
To implement an application that writes data to the SD card.
ALGORITHM:
1. In the design layout add two text fields and two buttons.
2. In manifest file include permission to access sdcard
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3. To write data ,create a new file using createNewFile();
4. Pass new file object to FileOutputStream.
5. Then using OutputStreamWriter object append data into the file .
6. To read data from the file
7. Pass file object to FileInputStream
8. Then using BufferedReader object and readline() method, read the content from the file.
PROGRAM:
Manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Activity java
package com.example.user.sdcardapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.*;
import android.view.*;
import android.widget.*;
public class MainActivityextends AppCompatActivity {
Button save,read;
EditTextt1,t2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(EditText)findViewById(R.id.editText);
t2=(EditText)findViewById(R.id.editText2);
save=(Button)findViewById(R.id.button);
read=(Button)findViewById(R.id.button2);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String fname=t1.getText().toString();
String data=t2.getText().toString();
FileOutputStream fos;
try
{
File myfile=new File("/sdcard/"+fname);
myfile.createNewFile();
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 42
Jerusalem College of Engineering Department of Information Technology
Toast.makeText(getApplicationContext(),fname+"saved",Toast.LENGTH_LONG).show();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String filename = t1.getText().toString();
StringBuffersbuffer = new StringBuffer();
String adatarow = "";
String aBuffer = "";
try {
File myfile = new File("/sdcard/" + filename);
FileInputStream in = new FileInputStream(myfile);
BufferedReadermyreader = new BufferedReader(new InputStreamReader(in));
while ((adatarow = myreader.readLine()) != null) {
aBuffer += adatarow + "\n";
}
myreader.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), aBuffer, Toast.LENGTH_LONG).show();
}
});
}
}
OUTPUT:
RESULT:
AIM:
To implement an application that creates an alert upon receiving a message.
ALGORITHM:
1. Create a textview to display a message in design layout.
2. In manifest file include the following permissions
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-
permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
3. Create IncomingSms.java file
4. Make the class to extend BroadcastReciever.
5. Get the object of SmsManager.
6. Retrieve the phone number of the sender and content of the message
7. Broadcast it to the receiver and display it as toast message.
PROGRAM:
Manifest file
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidexample.broadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.androidexample.broadcastreceiver.BroadcastNewSms"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.androidexample.broadcastreceiver.IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 45
Jerusalem College of Engineering Department of Information Technology
OUTPUT:
RESULT:
AIM:
To write a mobile application that creates alarm clock
ALGORITHM:
1. In Activity_alarmreciver.XML create a button to stop the alarm
2. In Activity_main.xml create a textview to display hello message
3. In AlarmReceiverActivity.java Create an object for MediaPlayer class. Inside onCreate
method, write onTouchListener for stop button, which invokes stop() method to stop the
alarm
4. Create another function playSound(),in which alarm tone is set and media player is
started.
5. In MainActivity.java Create an offset from the current time in which the alarm will go
off.
6. Create a new PendingIntent and add it to the AlarmManager.
PROGRAM:
AlarmReceiverActivity.java
package com.example.alarm_final;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
//import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class AlarmReceiverActivity extends Activity
{
private MediaPlayer mMediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarm);
Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
stopAlarm.setOnTouchListener(new OnTouchListener()
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 48
Jerusalem College of Engineering Department of Information Technology
{
public boolean onTouch(View arg0, MotionEvent arg1)
{
mMediaPlayer.stop();
finish();
return false;
}
});
playSound(this, getAlarmUri());
}
private void playSound(Context context, Uri alert)
{
mMediaPlayer = new MediaPlayer();
try
{
mMediaPlayer.setDataSource(context, alert);
final AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0)
{
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.prepare();
mMediaPlayer.start();
} }
catch (IOException e)
{
System.out.println("OOPS");
} }
//Get an alarm sound. Try for an alarm. If none set, try notification,
//Otherwise, ringtone.
private Uri getAlarmUri()
{
Uri alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alert == null)
{
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (alert == null)
{
alert = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
}
}
return alert;
}}
MainActivity.java
package com.example.alarm_final;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
//import android.view.Menu;
import android.view.Window;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//Create an offset from the current time in which the alarm will go off.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
//Create a new PendingIntent and add it to the AlarmManager
Intent intent = new Intent(this, AlarmReceiverActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
pendingIntent);
}
}
Layout
Activity_alarmreciver
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center" >
<Button
android:id="@+id/stopAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop_alarm" />
</RelativeLayout>
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
IT6611 MOBILE APPLICATION DEVELOPMENT LAB 50
Jerusalem College of Engineering Department of Information Technology
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<TextView
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="alarm_hello" />
</RelativeLayout>
RESULT: