MAD Unit 5
MAD Unit 5
2 Marks Questions
1. Draw diagram of activity life cycle.
Ans.
10. Write down syntax to create an intent and start another activity.
Ans.
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(intent);
4 marks Questions
1. Describe with example, how to create a simple database in SQLite (Assume suitable data).
2. Write significance of SQLite database in android.
Ans.
This procedure is by openOrCreateDatabase()
1. The package imported into the application is android.database.sqlite.SQLiteDatabase.
2. Here the class used is SQLiteDatabase.
3. The method used to create the database or connect to the database is openOrCreateDatabse()
method.
Program:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:text="Create SQLite Database"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button" />
</RelativeLayout>
MainActivity.java
package com.example.p1;
import ...
public class MainActivity extends AppCompatActivity
{
SQLiteDatabase sq;
Button b1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
sq = openOrCreateDatabase("AndroidJSonDataBase", Context.MODE_PRIVATE,
null);
}
});
}
}
Service Lifecycle
1. Started
a. A service is started when an application component, such as an activity, starts it by calling
startService().
b. Now the service can run in the background indefinitely, even if the component that started it is
destroyed.
2. Bound
a. A service is bound when an application component binds to it by calling bindService().
b. A bound service offers a client-server interface that allows components to interact with the service,
send requests, get results, and even do so across processes with InterProcess Communication (IPC).
c. Like any other components service also has callback methods. These will be invoked while the service
is running to inform the application of its state. Implementing these in our custom service would help
you in performing the right operation in the right state.
d. There is always only a single instance of service running in the app. If you are calling startService() for
a single service multiple times in our application it just invokes the onStartCommand() on that service.
Neither is the service restarted multiple times nor are its multiple instances created
1. onCreate(): This is the first callback which will be invoked when any component starts the service. If
the same service is called again while it is still running this method wont be invoked. Ideally one time
setup and intializing should be done in this callback.
2. onStartCommand() /startSetvice(): This callback is invoked when service is started by any component
by calling startService(). It basically indicates that the service has started and can now run indefinetly.
3. onBind(): To provide binding for a service, you must implement the onBind() callback method. This
method returns an IBinder object that defines the programming interface that clients can use to interact
with the service.
4. onUnbind(): This is invoked when all the clients are disconnected from the service.
5. onRebind(): This is invoked when new clients are connected to the service. It is called after onRebind
6. onDestroy(): This is a final clean up call from the system. This is invoked just before the service is
being destroyed.
7. Explain property animation method to animate the properties of view object with example.
Ans.
A property animation changes a property's (a field in an object) value over a specified length of time. To
animate something, you specify the object property that you want to animate, such as an object's
position on the screen, how long you want to animate it for, and what values you want to animate
between.
The property animation system lets you define the following characteristics of an animation:
Duration: You can specify the duration of an animation. The default length is 300 ms.
Time interpolation: You can specify how the values for the property are calculated as a function of the
animation's current elapsed time.
Repeat count and behavior: You can specify whether or not to have an animation repeat when it reaches
the end of a duration and how many times to repeat the animation. You can also specify whether you
want the animation to play back in reverse. Setting it to reverse plays the animation forwards then
backwards repeatedly, until the number of repeats is reached.
Animator sets: You can group animations into logical sets that play together or sequentially or after
specified delays.
Frame refresh delay: You can specify how often to refresh frames of your animation. The default is set to
refresh every 10 ms, but the speed in which your application can refresh frames is ultimately dependent
on how busy the system is overall and how fast the system can service the underlying timer.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/buttonAnimate"
android:text="Animate Me"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
MainActivity.java
package com.example.animationdemo;
import ...
public class MainActivity extends AppCompatActivity
{
Button b1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.buttonAnimate);
b1.setOnClickListener(new View.onClickListener()
{
public void onClick(View v)
{
ObjectAnimator moveX = ObjectAnimator.ofFloat(view, "translationX", 0f, 00f);
ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 2f);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 2f);
ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", 0f, 360f);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(moveX, scaleX, scaleY, rotate);
animatorSet.setDuration(2000);
animatorSet.start();
}
});
}
Uses of Fragments
1 Reusability → The same fragment can be used in multiple activities to avoid redundant code.
2 Flexible UI Design → Supports multi-pane layouts for better user experience, especially on tablets.
4 Efficient Memory Usage → Uses less memory than creating multiple activities.
5 Easier Lifecycle Management → Lifecycle is managed by the parent activity, reducing complexity.
6 Better UI Organization → Helps in breaking large UI components into smaller, manageable pieces.
Example-
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
<fragment
android:name="com.example.ExampleFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/sensorList"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<manifest>
<Button
android:id="@+id/b1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Turn ON Bluetooth"
android:click="on"/>
<Button
android:id="@+id/b2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Turn OFF Bluetooth"
android:click="off"/>
<Button
android:id="@+id/b3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Paired Devices"
android:click="visible"/>
<Button
android:id="@+id/b4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="list"
android:click="list"/>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
6 Marks Questions
1. Write a program to capture an image using camera and display it.
Ans.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TAKE PHOTO" />
</LinearLayout>
MainActivity.java
package com.example.ifcdiv;
import ...
public class MainActivity extends AppCompatActivity
{
Button b1;
ImageView imageView;
int CAMERA_REQUEST=1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.photo);
imageView=findViewById(R.id.image);
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i,CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==CAMERA_REQUEST)
{
Bitmap image= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(image);
}
}
}
2. Write a program to implement Android Activity Life Cycle. Use toast messages to display message
through life cycle.
Ans.
package com.example.lifecycleexample;
import ...
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "onCreate() called", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "onStart() called", Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "onResume() called", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "onPause() called", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "onStop() called", Toast.LENGTH_SHORT).show();
}
@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(this, "onRestart() called", Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "onDestroy() called", Toast.LENGTH_SHORT).show();
}
}
3. Develop an application to store customer's details like, customer-id, customer-name, mobile number,
address, pin-code and retrieve customer information using customer-id in SQLite databases. (Any other
relevant logic can be considered).
Ans.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="ID"
android:id="@+id/editid" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Mobile No."
android:id="@+id/editmobile"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Address"
android:id="@+id/editaddress" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Pin Code"
android:id="@+id/editpincode" />
<Button
android:text="Insert Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editpincode"
android:id="@+id/button" />
<TextView
android:text="Search Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView1" >
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter ID"
android:id="@+id/editsearchid" />
<Button
android:text="Search Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button1" />
</LinearLayout>
MainActivity.java
package in.msbte.database;
import ...
public class MainActivity extends AppCompatActivity {
SQLiteDatabase sqLiteDatabaseObj;
EditText editTextID, editTextName, editMobileNo, editAddress, editPincode,
editSearchid;
String cid, cname, cmobile, caddress, cpincode, sql_query, sid;
Button EnterData, SearchData;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EnterData = (Button)findViewById(R.id.button);
SearchData = (Button)findViewById(R.id.button1);
editTextID = (EditText)findViewById(R.id.editid);
editTextName = (EditText)findViewById(R.id.editname);
editMobileNo = (EditText)findViewById(R.id.editmobile);
editAddress = (EditText)findViewById(R.id.editaddress);
editPincode = (EditText)findViewById(R.id.editpincode);
editSearchid = (EditText)findViewById(R.id.editsearchid);
EnterData.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase", Context.MODE_PRIVATE,
null);
sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS AndroidJSonTable(id INTEGER
PRIMARY KEY AUTOINCREMENT NOT NULL, cid VARCHAR, name VARCHAR, mobile VARCHAR, address
VARCHAR, pincode VARCHAR);");
cid = editTextID.getText().toString();
cname = editTextName.getText().toString() ;
cmobile = editMobileNo.getText().toString();
caddress = editAddress.getText().toString();
cpincode = editPincode.getText().toString();
sql_query = "INSERT INTO AndroidJSonTable (cid, name, mobile, address, pincode)
VALUES('"+cid+"', '"+cname+"', '"+cmobile+"', '"+caddress+"', '"+cpincode+"');";
sqLiteDatabaseObj.execSQL(sql_query);
Toast.makeText(getApplicationContext(), "Data Inserted Successfully",
Toast.LENGTH_LONG).show();
}
});
SearchData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sid = editSearchid.getText().toString();
Cursor cursor = sqLiteDatabaseObj.rawQuery( "select * from AndroidJSonTable where
cid="+sid+"", null );
StringBuffer buffer= new StringBuffer();
while (cursor.moveToNext())
{
String cid =cursor.getString(1);
String name =cursor.getString(2);
String mob =cursor.getString(3);
String addr =cursor.getString(4);
String pcode =cursor.getString(5);
buffer.append(cid+ " " + name + " " + mob +" " + addr +" " + pcode +" \n");
Toast.makeText(getApplicationContext(), buffer, Toast.LENGTH_LONG).show();
} }); } }
6. Develop an android application for taking student feedback with database connectivity.
Ans.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Student Feedback Form" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Roll No."
android:id="@+id/editrollno"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Class"
android:id="@+id/editclass"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your Feedback"
android:lines="3"
android:id="@+id/editfeedback"/>
<Button
android:text="Submit Feedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/button" />
</LinearLayout>
MapsActivity.java
package com.example.feedback;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
submitBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sqLiteDatabaseObj = openOrCreateDatabase("FeedbaseDataBase",
Context.MODE_PRIVATE, null);
sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS
Student(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name
VARCHAR, rollno VARCHAR, class VARCHAR, feedback VARCHAR);");
sname = std_name.getText().toString();
srollno = std_rollno.getText().toString() ;
sclass = std_class.getText().toString();
sfeedback = std_class.getText().toString();
sql_query = "INSERT INTO Student (name, rollno, class, feedback)
VALUES('"+sname+"', '"+srollno+"', '"+sclass+"', '"+sfeedback+"')";
sqLiteDatabaseObj.execSQL(sql_query);
Toast.makeText(getApplicationContext(), "Feedback Submitted
Successfully", Toast.LENGTH_LONG).show();
}
});
}
}
7. Develop an application to convert “thanks” text to speech as given in the following GUI.
Ans.
Code of activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android Text to Speech(TTS) Demo"
android:id="@+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CLICK TO CONVERT TEXT TO SPEECH"
android:id="@+id/button" />
</LinearLayout>
Code of MainActivity.java.
package com.example.texttospeech.myapplication;
import ...
public class MainActivity extends Activity
{
TextToSpeech t1;
EditText ed1;
Button b1;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_title_layout);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
b1=(Button)findViewById(R.id.button);
t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()
{
public void onInit(int status)
{
if(status != TextToSpeech.ERROR)
{
t1.setLanguage(Locale.UK);
}
}
});
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
}
public void onPause(){
if(t1 !=null){
t1.stop();
t1.shutdown();
}
super.onPause();
}
}
8. Develop an application to update a record of an employee whose emp.id is ‘E101’ in SQlite database.
Change employee name from “PQR” to “XYZ”. Also display the updated record. (Write .java and .xml
files)
Ans.
9. Develop an application to store details like roll no, name, marks and retrive student information using
roll no. in SQLite database. (Write java and xml file)
Ans. Same as Q6