You are on page 1of 25

Question Bank MAD (22617) - PT2

Class/Course: CO6I (A+B)


Academic Year 2021-2022

1. What is Intent? Enlist its types?

Android Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc. It is generally used with startActivity() method to invoke
activity, broadcast receivers etc.

There are two types of intents in android: implicit and explicit.

1) Implicit Intent

It doesn't specify the component. In such case, intent provides information of available components
provided by the system that is to be invoked.

2) Explicit Intent

It specifies the component. In such case, intent provides the external class to be invoked.

2. What is Activity in android?

An Android activity is one screen of the Android app's user interface. In that way an Android activity
is very similar to windows in a desktop application. An Android app may contain one or more
activities, meaning one or more screens. The Android app starts by showing the main activity, and
from there the app may make it possible to open additional activities.

3. What is Service in android? Enlist its types?

Android service is a component that is used to perform operations on the background such as
playing music, handle network transactions, interacting content providers etc. It doesn't has any UI
(user interface).The service runs in the background indefinitely even if application is

PT-2 QB CO6I prepared by Poonam V Page 1


destroyed.Moreover, service can be bounded by a component to perform interactivity and inter
process communication (IPC).

There can be two forms of a service.The lifecycle of service can follow two different paths: started or
bound.

1. Started

2. Bound

1) Started Service

A service is started when application component (like activity) starts or calls startService() method,
now it runs in the background indefinitely. It is stopped by stopService() method. The service can
stop itself by calling the stopSelf() method.

2) Bound Service

A service is bound when another component (e.g. client) calls bindService() method. 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).The
client can unbind the service by calling the unbindService() method.The service cannot be stopped
until all clients unbind the service.

PT-2 QB CO6I prepared by Poonam V Page 2


4. Draw the neat diagram of activity life cycle

5. What Is Sensor in android? Enlist its Types

Android-powered devices have built-in sensors that measure motion, orientation, and various
environmental conditions. These sensors are capable of providing raw data with high precision and
accuracy, and are useful if you want to monitor three-dimensional device movement or positioning,
or you want to monitor changes in the ambient environment near a device.

The Android platform supports three broad categories of sensors:

PT-2 QB CO6I prepared by Poonam V Page 3


 Motion sensors

These sensors measure acceleration forces and rotational forces along three axes. This category
includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.

 Environmental sensors

These sensors measure various environmental parameters, such as ambient air temperature and
pressure, illumination, and humidity. This category includes barometers, photometers, and
thermometers.

 Position sensors

These sensors measure the physical position of a device. This category includes orientation sensors
and magnetometers.

6. What is Animation? Enlist its Types.

Animation is the process of creating motion and shape change. Animation in android is possible in 3
ways:

1. Property Animations — They are used to alter property of objects (Views or non view objects).
We specify certain properties(like translateX, TextScaleX) of the objects to change. Various
characteristics of animation which can be manipulated are animation duration, whether to reverse
it and for how many times we want to repeat the animation etc. They were introduced in Android
3.0 (API level 11).

2. View Animations — They are used to do simple animations like changing size, position, rotation,
control transparency. They are easy to build and are very fast but have their own constraints. For
eg — Their state changes but their property does not change. View animations will be covered in
part 2.

3. Drawable Animations — This is used to do animation using drawables. An XML file specifying
various list of drawables is made which are run one by one just like a roll of a film. This is not
much used so I won’t cover it.

7. What is TTS feature of Android?

Text to speech, abbreviated as TTS, is a form of speech synthesis that converts text into spoken
voice output. Text to speech systems were first developed to aid the visually impaired by offering a
computer-generated spoken voice that would "read" text to the user. Android TTS API offers
PT-2 QB CO6I prepared by Poonam V Page 4
multiple-language support, control of voice characteristics and features, file output, and so on.
With just a small number of lines of code, you can make your apps reach out to a wider audience.

8. List different User interface elements. Explain toggle button.

In android UI or input controls are the interactive or View components that are used to design the
user interface of an application. In android we have a wide variety of UI or input controls available,
those are TextView, EditText, Buttons, Checkbox, Progressbar, Spinners, etc.

Following is the pictorial representation of user interface (UI) or input controls in android
application.

Toggle button
A two state button that can be used as an alternative to a checkbox. It is particularly appropriate
where pressing the button will initiate an action as well as change a state. A toggle button allow the
user to change a setting between two states.
 On state
 Off state
Syntax
<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="@string/toggle_turn_on"
android:textOff="@string/toggle_turn_off"
android:checked="true"
android:text="" />

PT-2 QB CO6I prepared by Poonam V Page 5


9. Enlist (Explain) different ways to handle databases in android? (if explain
comes in question write with explanation or else mention only steps. Also see
the weightage of marks if for 4 marks should write with explanation and
example.)

There are basically four different ways to handle databases in an Android :

1. Shared Preferences

You should use this to save primitive data in key-value pairs. You have a key, which must be a
String, and the corresponding value for that key, which can be one of: boolean, float, int, long or
string. Internally, the Android platform stores an app’s Shared Preferences in an xml file in a private
directory.

2. Internal Storage

The Internal Storage data storage method is specifically for those situations where you need to store
data to the device filesystem, but you do not want any other app (even the user) to read this data.
Data stored using the Internal Storage method is completely private to your application, and are
deleted from the device when your app is uninstalled.

3. External Storage

To save (and/or read) files to the device’s external storage, your app must request for the
WRITE_EXTERNAL_STORAGE permission. If you only want to read from the External Storage
without writing, request for the READ_EXTERNAL_STORAGE permission. The
WRITE_EXTERNAL_STORAGE permission grants both read/write access.

4. SQLite database

Finally, Android provides support for apps to use SQLite databases for data storage. Databases
created are app specific, and are available to any class within the app, but not to outside applications.

PT-2 QB CO6I prepared by Poonam V Page 6


SQLite database

Android provides complete support for SQLite databases. The recommended way of creating SQLite
databases is to subclass the SQLiteOpenHelper class, and override the onCreate() method. For this
sample, we simply create a single table.

public class SampleSQLiteDBHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 2;

public static final String DATABASE_NAME = "sample_database";

public static final String PERSON_TABLE_NAME = "person";

public static final String PERSON_COLUMN_ID = "_id";

public static final String PERSON_COLUMN_NAME = "name";

public static final String PERSON_COLUMN_AGE = "age";

public static final String PERSON_COLUMN_GENDER = "gender";

public SampleSQLiteDBHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

@Override

public void onCreate(SQLiteDatabase sqLiteDatabase) {

sqLiteDatabase.execSQL("CREATE TABLE " + PERSON_TABLE_NAME + " ("


+

PERSON_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "


+

PERSON_COLUMN_NAME + " TEXT, " +

PERSON_COLUMN_AGE + " INT UNSIGNED, " +

PERSON_COLUMN_GENDER + " TEXT" + ")");

@Override

public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

PT-2 QB CO6I prepared by Poonam V Page 7


sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " +
PERSON_TABLE_NAME);

onCreate(sqLiteDatabase);

SQLite storage offers the power and speed of a full featured relational database to your app. If you
intend to store data that needs to be queried, you should consider using the SQLite storage option.
Watch out for our upcoming in-depth article on using sqlite storage in an android app.

10. List different types of views? Explain scroll view?


Most Commonly Used Android View classes:

These views can be used to create a useful input and output fields.

 Text View
 EditText
 ImageView
 CheckBox
 RadioGroup
 ListView
 Spinner
 Scrollview
 AutoCompleteTextView

The android.widget.ScrollView class provides the functionality of scroll view. ScrollView is used
to scroll the child elements of palette inside ScrollView. Android supports vertical scroll view as
default scroll view. Vertical ScrollView scrolls elements vertically. Android
uses HorizontalScrollView for horizontal ScrollView.

11. Name any 4 methods to get location data in android.

PT-2 QB CO6I prepared by Poonam V Page 8


The Location object represents a geographic location which can consist of a latitude, longitude, time
stamp, and other information such as bearing, altitude and velocity. There are following important
methods which you can use with Location object to get location specific information −

Sr.No. Method & Description

1
float distanceTo(Location dest)
Returns the approximate distance in meters between this location and the given location.

2
float getAccuracy()
Get the estimated accuracy of this location, in meters.

3
double getAltitude()
Get the altitude if available, in meters above sea level.

4
float getBearing()
Get the bearing, in degrees.

5
double getLatitude()
Get the latitude, in degrees.

6
double getLongitude()
Get the longitude, in degrees.

7
float getSpeed()
Get the speed if it is available, in meters/second over ground.

8
boolean hasAccuracy()
True if this location has an accuracy.

9
boolean hasAltitude()
True if this location has an altitude.

10
boolean hasBearing()
True if this location has a bearing.

PT-2 QB CO6I prepared by Poonam V Page 9


11
boolean hasSpeed()
True if this location has a speed.

12
void reset()
Clears the contents of the location.

13
void setAccuracy(float accuracy)
Set the estimated accuracy of this location, meters.

14
void setAltitude(double altitude)
Set the altitude, in meters above sea level.

15
void setBearing(float bearing)
Set the bearing, in degrees.

16
void setLatitude(double latitude)
Set the latitude, in degrees.

17
void setLongitude(double longitude)
Set the longitude, in degrees.

18
void setSpeed(float speed)
Set the speed, in meters/second over ground.

19
String toString()
Returns a string containing a concise, human-readable description of this object.

PT-2 QB CO6I prepared by Poonam V Page 10


12. Enlist (Explain) steps to develop android application. (if explain comes in
question write with explanation or else mention only steps. Also see the
weightage of marks if for 4 marks should write with explanation.)

Creation of Android App Step by Step:

Step 1: Start with Android Studio

The most common IDE for Android development is Android Studio, which comes directly from
Google itself.

Step 2: Installation of Java Development Kit (JDK)

After the installation of Android Studio, You also need to install Java on your machine to use
Android Studio. The JDK is able to interpret and compile your code for the application development.

Step 3: Start Your Project

Choose ‘Start a new Android Studio Project’ option. Enter the name you want for your application
and your ‘company domain’. All these elements will be used to create your package name in a format
like: com.companyname.appname

Step 4: Select Activity

Moreover, you’ll be given the option to pick the way you want the app to look at the beginning. This
will be the look of your main ‘Activity Module’ which is basically the main page of your app. There
are various fields available which you have to choose according to your app needs, such as templates,
title, access to Google maps, full-screen activity, blank activity etc. As per my view, it’s better to go
for ‘Basic Activity’ to keep things as simple as possible and for all intents and purposes.

Step 5: Selecting the Layout

Now, you have to choose a layout name for the selected activity. This will define that where
elements like images and menus go and what fonts you’ll use. Choose a name for the menu and title
as well. Pick something attractive for the title, as your users will be able to see this at some points.

Step 6: Edit the Welcome Message

Go to the activity_main.xml tab if it is not open. Click and drag the “Hello, world!” from the upper
left corner of the phone display to the center of the screen. Then go to the values folder, and double-
click the strings.xml file. In this file, find the line “Hello world!” and add “Welcome to my App!”

PT-2 QB CO6I prepared by Poonam V Page 11


Step 7: Adding Button to your Activity

In the Palette menu to the left of display, find Button. Click and drag Button to be positioned beneath
welcome message. Afterward, go to properties and find the field for text. Change the text from “New
Button” to “Next Page”.

Now go back to your content_main.xml and click on the button. In the right corner, where you have
your parameters for the button, you will catch an option called ‘onClick’. Click on this and then
select the ‘onClick’. By doing this, you have told Android Studio that you want to associate the
section of code with the button created.

Step 8: Test your App

Finally, all that’s missing to do is run the app you just made. Simple go to ‘run’ along the top and
then select ‘run app’ from the drop-down menu. Follow the steps to launch the emulator running
your app.

13. Write the syntax for Intent-filter tag


<intent-filter>

syntax:

<intent-filter android:icon="drawable resource"


android:label="string resource"
android:priority="integer" >
. . .
</intent-filter>

14. Enlist (explain) the steps to publish the Android application. (if explain comes
in question write with explanation or else mention only steps. Also see the
weightage of marks if for 4 marks should write with explanation.)

1. Create an account

Firstly, To publish your app on google play store, you need to have account on google. You may
have already personal email account with them but for your app it's better to separate one for manage
your app(s) easily. You would have to pay a registration fees of 25 USD, using Google payments,
While registering your publisher account. After that, a verification mail would be sent to you and
then you sign in to your developer console, where all action would take place.

PT-2 QB CO6I prepared by Poonam V Page 12


2. Familiarise yourself with Developer Console

Developer console is starting point and main dashboard for publishing tools and operations. Before
you go ahead, familiarise yourself with list of merchant countries and developer countries. You need
to review list of merchant countries if you want to sell apps or in app purchases or have subscriptions
and list of developer countries will tell you about locations where distribution to Google play users is
supported. Apart from this, also looks the Google Play’s Terms and conditions.

3. Fill in the necessary account details

After this, you have to provide your complete account details like you have to provide your
developer name, the name which would be displayed in Google Play Store. You will have to wait for
anything between just a little and 48 hours, after filling the details for Google play developer
registration to be processed.

4. Link your merchant account

If you have a paid app or subscription or in app purchases, then you have to inter link your google
payments merchant account and developer profile. It can be used for tax and financial identification
as well as monthly payout from sale.

5. Upload your app

When you are sign in your Google Play developer console, click on “Add new application” from
“All Applications tab”. After this select correct “Default Language” from drop down menu and then
type “title” of your app which would be appear on Google Play store. Then, select “Upload APK”
button to view on new page which would be your homepage for app. Time taken to upload file
depend on your app size. App will be in drafts until or unless you publish it.

6. Alpha and beta testing of app

It is essential to test it with sample of end users to get feedback of app before launch your app even
Google play take care of this as well. In section of your app “APK” of developer console, you will
find option related to “Alpha Testing” and “Beta Testing”. After you uploaded your app’s “APK” file
you can use these options for receive URL that can be shared with testers. By using this link, Testers
can download app beta or alpha version. Your testers can not provide reviews and feedback on app
page. Now you use this feedback to make relevant changes and optimise your app before publishing
in app store.

PT-2 QB CO6I prepared by Poonam V Page 13


7. Provide details for store listing

After uploading “APK” file go to “Store listing” tab. Over there you need to add details of app like
“Full description” and “Short description”. Along with this add categorisation, contact details, link of
promo video if you have, add screenshots and other necessary details to app. After complete
mandatory fields click on “Save” button. You can update your store listing anytime.

8. Add pricing and distribution details

Now move on next tab, which is “Pricing and Distribution” and select it is “Paid” or “Free” app. You
also select distribution countries and check boxes stating your app complies with content guidelines.
If your app is an game one, then you can put in limelight using “Google Play for Game” option. Now
save changes and move on next step.

9. Publishing the application

When all three tabs “Pricing and Distribution”, “Store Listing” and “APK” have been filled then
appear a green check mark next to them you are all ready to publish app in Google Play. After then
click on “Publish this app” button under “Ready to Publish” drop down menu at top right corner of
Developer console. A confirmation bar would show up stating your app would appear shortly in
Google Play Store.

10. Device Filtering option

There are series of extra option that might not seem to be important to publish the app but they can
prevent app from negative feedback. There is also option to manually filter non compatible devices
or problematic so make the most use of it to filter out any negativities and stay on the top.

15. Explain Google Map with types.

Google Maps provides four types of maps. They are −

 ROADMAP (normal, default 2D map)− This is the default type. If you haven't chosen any of
the types, this will be displayed. It shows the street view of the selected region.
 SATELLITE (photographic map)− This is the map type that shows the satellite images of
the selected region.

PT-2 QB CO6I prepared by Poonam V Page 14


 HYBRID (photographic map + roads and city names)− This map type shows the major
streets on satellite images.

 TERRAIN (map with mountains, rivers, etc.) − This is the map type that shows the terrain
and vegetation

16. Describe the types of permissions used while developing android applications.

Permissions are divided into several protection levels. The protection level affects whether runtime
permission requests are required. There are three protection levels that affect third-party
apps: normal, signature, and dangerous permissions.

Normal permissions

Normal permissions cover areas where your app needs to access data or resources outside the app's
sandbox, but where there's very little risk to the user's privacy or the operation of other apps. For
example, permission to set the time zone is a normal permission.

Signature permissions

The system grants these app permissions at install time, but only when the app that attempts to use a
permission is signed by the same certificate as the app that defines the permission.

Dangerous permissions

Dangerous permissions cover areas where the app wants data or resources that involve the user's
private information, or could potentially affect the user's stored data or the operation of other apps.
For example, the ability to read the user's contacts is a dangerous permission. If an app declares that
it needs a dangerous permission, the user has to explicitly grant the permission to the app. Until the
user approves the permission, your app cannot provide functionality that depends on that permission.

Special permissions

There are a couple of permissions that don't behave like normal and dangerous
permissions. SYSTEM_ALERT_WINDOW and WRITE_SETTINGS are particularly sensitive, so
most apps should not use them. If an app needs one of these permissions, it must declare the
permission in the manifest, and send an intent requesting the user's authorization. The system
responds to the intent by showing a detailed management screen to the user.

PT-2 QB CO6I prepared by Poonam V Page 15


Starting from Android 6.0 (API 23), users are not asked for permissions at the time of installation
rather developers need to request for the permissions at the run time. Only the permissions that
are defined in the manifest file can be requested at run time.

Permissions Required at:


1. Install-Time Permissions: If the Android 5.1.1 (API 22) or lower, the permission is
requested at the installation time at the Google Play Store.

If the user Accepts the permissions, the app is installed. Else the app installation is cancelled.

2. Run-Time Permissions: If the Android 6 (API 23) or higher, the permission is requested at
the run time during the runnnig of the app.

If the user Accepts the permissions, then that feature of the app can be used. Else to use the feature,
the app requests the permission again. So, now the permissions are requested at runtime.

17. Define content provider and explain fragments.


 A content provider manages access to a central repository of data. Content providers are
primarily intended to be used by other applications, which access the provider using a
provider client object.
 Providers and provider clients offer a consistent, standard interface to data that also handles
inter-process communication and secure data access.
 A content provider presents data to external applications as one or more tables that are similar
to the tables found in a relational database.
 A content provider component supplies data from one application to others on request. Such
requests are handled by the methods of the ContentResolver class.

PT-2 QB CO6I prepared by Poonam V Page 16


 A content provider can use different ways to store its data and the data can be stored in a
database, in files, or even over a network.

 Content providers let you centralize content in one place and have many different
applications access it as needed.
 A content provider behaves very much like a database where you can query it, edit its
content, as well as add or delete content using insert(), update(), delete(), and query()
methods.
 A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.
 public class My Application extends ContentProvider
{
}

Fragments:

A Fragment is a piece of an activity which enable more modular activity design.


A fragment is a kind of sub-activity.

• A fragment is an independent Android component which can be used by an activity. A


fragment encapsulates functionality so that it is easier to reuse within activities and layouts.

• A fragment runs in the context of an activity, but has its own life cycle and typically its own
user interface.

• Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse
of components in different layouts and their logic.

PT-2 QB CO6I prepared by Poonam V Page 17


• You can also use fragments also to support different layout for landscape and portrait
orientation on a smartphone.

• As it is possible to dynamically add and remove fragments from an activity. The usage of
fragments allows designing very flexible user interfaces.

18. Discuss developer console with its purpose.

The Android Things Console provides easy and secure deployment of updates to your connected
devices. Google provides the infrastructure to host and deliver system and app updates with the
developer in final control.

Using the console, developers and device makers can:

 Download and install the latest Android Things system image

 Build factory images that contain OEM applications along with the system image

 Push over-the-air (OTA) seamless updates, including OEM (original equipment manufacturer)
applications and the system image, to devices

 Manage and share OEM applications across products and owners

 Monitor informative analytics to understand how well products are performing

How to use the Play Console

Register for a Google Play Developer account

To publish Android apps on Google Play, you'll need to create a Google Play Developer account.

Step 1: Sign up for a Google Play Developer account

Step 2: Accept the Developer Distribution Agreement

Step 3: Pay registration fee

Step 4: Complete your account details

Use the Play Console

Once you've selected an app, here are the pages you'll find in each category:

PT-2 QB CO6I prepared by Poonam V Page 18


 Android vitals: Overview, ANRs & crashes, Deobfuscation files
 Development tools: Services & APIs
 Release management: Release dashboard, App releases, Android Instant Apps, Artifact
library, App bundle explorer, Device catalog, App signing, Pre-launch report
 Store presence: Store listing, Store listing experiments, Pricing & distribution, Content rating,
In-app products, Paid app sales, Translation service
 User acquisition: Acquisition reports, Google Ads campaigns, Promotions, Optimization tips
 Financial reports: Overview, Revenue, Buyers, Conversions, Subscriptions
 User feedback: Ratings, Reviews analysis, Reviews, Beta feedback

19. Write a program to create a text field and button “Navigate”. When you enter
www.google.com and press on navigate button it should open the google page.

activity_main.xml

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


<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="60dp"
android:ems="10"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.575"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginLeft="156dp"
android:layout_marginTop="172dp"
android:text="Navigate"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText" />

</androidx.constraintlayout.widget.ConstraintLayout>

PT-2 QB CO6I prepared by Poonam V Page 19


MainActivity.java

package com.example.implicit_intent_navigate;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.content.Intent;
import android.net.Uri;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

Button button;
EditText editText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = findViewById(R.id.button);
editText = findViewById(R.id.editText);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url=editText.getText().toString();
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);

}
});
}
}

20. Write a program to display an image using imageview and a button named as change image.
Once you click on button another image should get displayed

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"
tools:context=".MainActivity" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="249dp"
android:layout_weight="1"
android:src="@drawable/sun_spring_green_forest"/>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"

PT-2 QB CO6I prepared by Poonam V Page 20


android:layout_height="wrap_content"
android:layout_weight="1"
android:text="change image" />
</LinearLayout>

MainActivity.java
package com.example.changeimage;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View;

public class MainActivity extends Activity {

Button button;
ImageView img;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

addListenerOnButton();

public void addListenerOnButton()


{
img=(ImageView)findViewById(R.id.imageView1);
button=(Button)findViewById(R.id.button1);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
img.setImageResource(R.drawable.palombaggia_beach_sunny);
}
});

}
}

21. Explain the significance of SQLite database in android.


 SQLite is an open-source relational database i.e. used to perform database operations on
android devices such as storing, manipulating or retrieving persistent data from the database.
 It is embedded in android bydefault. So, there is no need to perform any database setup or
administration task.
 SQLiteOpenHelper class provides the functionality to use the SQLite database. This class will
act as a database controller which will have the methods to perform the CRUD operations.
 First the database instance should be created using the method like getReadableDatabase() or
getWritableDatabase() based on the type of access required.

PT-2 QB CO6I prepared by Poonam V Page 21


 SQLiteOpenHelper provides callback methods and we should override it to get our job done.
Those callback methods that we can override are onCreate(), onUpgrade(), onOpen() and
onDowngrade(). And onCreate() and onUpgrade() are abstract methods and must be overridden.

SQLiteOpenHelper class

The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version


management. For performing any database operation, you have to provide the implementation
of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.

onCreate(SQLiteDatabase database) – is the method which is called first time when the database is
created and we need to use this method to create the tables and populate it as per the need.

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) – is the method called when
upgrade is done. We can drop the datbase and reset if required.

SQLiteDatabase class

It contains methods to be performed on sqlite database such as create, update, delete, select etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String inserts a record on the database. The table
nullColumnHack, ContentValues values) specifies the table name, nullColumnHack
doesn't allow completely null values. If
second argument is null, android will store
null values if values are empty. The third
argument specifies the values to be stored.
int update(String table, ContentValues updates a row.
values, String whereClause, String[]
whereArgs)
Cursor query(String table, String[] returns a cursor over the resultset.
columns, String selection, String[]
selectionArgs, String groupBy, String
having, String orderBy)

PT-2 QB CO6I prepared by Poonam V Page 22


22. Explain the activity life cycle. (if explain comes in question write with
explanation or else mention only methods. Also see the weightage of marks if
for 4 marks should write with explanation.)

Refer the diagram given above.

Activity is one of the building blocks of Android OS. In simple words Activity is a screen that user
interact with. Every Activity in android has lifecycle like created, started, resumed, paused, stopped
or destroyed. These different states are known as Activity Lifecycle.

Short description of Activity Lifecycle example: (If 2 marks question with explanation)

onCreate() – Called when the activity is first created

onStart() – Called just after it’s creation or by restart method after onStop(). Here Activity start
becoming visible to user

onResume() – Called when Activity is visible to user and user can interact with it

onPause() – Called when Activity content is not visible because user resume previous activity

onStop() – Called when activity is not visible to user because some other activity takes place of it

onRestart() – Called when user comes on screen or resume the activity which was stopped

onDestroy – Called when Activity is not in background

LIST OF ACTIVITY LIFECYCLE METHODS OR STATES: ( 4 marks and above)

onCreate(Bundle savedInstanceState):

onCreate() method is called when activity gets memory in the OS. To use create state we need to
override onCreate(Bundle savedInstanceState) method. Bundle is a data repository object that
can store any kind of primitive data and this object will be null until some data isn’t saved in that.

 When an Activity first call or launched then onCreate(Bundle savedInstanceState) method is


responsible to create the activity.

PT-2 QB CO6I prepared by Poonam V Page 23


 When ever orientation(i.e. from horizontal to vertical or vertical to horizontal) of activity gets
changed or when an Activity gets forcefully terminated by any Operating System then
savedInstanceState i.e. object of Bundle Class will save the state of an Activity.
 It is best place to put initialization code.

onStart():

onStart() method is called just after it’s creation. In other case Activity can also be started by calling
restart method i.e after activity stop. So this means onStart() gets called by Android OS when
user switch between applications. For example, if a user was using Application A and then a
notification comes and user clicked on notification and moved to Application B, in this case
Application A will be paused. And again if a user again click on app icon of Application A then
Application A which was stopped will again gets started.

onResume():

Activity resumed is that situation when it is actually visible to user means the data displayed in the
activity is visible to user. In lifecycle it always gets called after activity start and in most use case
after activity paused (onPause).

onPause():

Activity is called paused when it’s content is not visible to user, in most case onPause() method
called by Android OS when user press Home button (Center Button on Device) to make hide.

Activity also gets paused before stop called in case user press the back navigation button. The
activity will go in paused state for these reasons also if a notification or some other dialog is
overlaying any part (top or bottom) of the activity (screen). Similarly, if the other screen or dialog is
transparent then user can see the screen but cannot interact with it. For example, if a call or
notification comes in, the user will get the opportunity to take the call or ignore it.

onStop():

Activity is called stopped when it’s not visible to user. Any activity gets stopped in case some other
activity takes place of it. For example, if a user was on screen 1 and click on some button and moves
to screen 2. In this case Activity displaying content for screen 1 will be stopped.
PT-2 QB CO6I prepared by Poonam V Page 24
Every activity gets stopped before destroy in case of when user press back navigation button. So
Activity will be in stopped state when hidden or replaced by other activities that have been launched
or switched by user. In this case application will not present anything useful to the user directly as
it’s going to stop.

onRestart():

Activity is called in restart state after stop state. So activity’s onRestart() function gets called when
user comes on screen or resume the activity which was stopped. In other words, when Operating
System starts the activity for the first time onRestart() never gets called. It gets called only in case
when activity is resumes after stopped state.

onDestroy():

Any activity is known as in destroyed state when it’s not in background. There can different cases at
what time activity get destroyed.

First is if user pressed the back navigation button then activity will be destroyed after completing the
lifecycle of pause and stop.

In case if user press the home button and app moves to background. User is not using it no more and
it’s being shown in recent apps list. So in this case if system required resources need to use
somewhere else then OS can destroy the Activity.

After the Activity is destroyed if user again click the app icon, in this case activity will be recreated
and follow the same lifecycle again.

PT-2 QB CO6I prepared by Poonam V Page 25

You might also like