0% found this document useful (0 votes)
7 views22 pages

Mad Imp Questions1

The document outlines key features of the Android operating system, components of Android UI design, and the role of the Android emulator. It provides detailed steps for installing Android Studio, deploying applications on the Google Play Store, and explains the Android architecture and service lifecycle. Additionally, it includes a sample program for sending SMS in Android and compares JVM and DVM.

Uploaded by

Ganesh Ghadshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views22 pages

Mad Imp Questions1

The document outlines key features of the Android operating system, components of Android UI design, and the role of the Android emulator. It provides detailed steps for installing Android Studio, deploying applications on the Google Play Store, and explains the Android architecture and service lifecycle. Additionally, it includes a sample program for sending SMS in Android and compares JVM and DVM.

Uploaded by

Ganesh Ghadshi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

MAD IMP QUESTION

1.List any four features of android operating system. (2m)


Features of Android Operating System:
1)Storage
2)Multitasking
3)Web Browser
4)Open Source
5)Accessibility
6)Media Support
7)Streaming Media Support
8)Voice Based Features
9)Multitouch
10)External Storage
11)Video Calling
12)Handset Layout
13)Google cloud Messaging
14)WiFi Direct

2.List various components of android UI design. (2m)


Components of android UI design:
1)views
2)viewgroups
3)fragments
4)activity

3.Describe role of Emulator. (2m)


Android emulator is a tool that creates virtual Android devices on your computer. The
emulator lets you prototype, develop and test Android applications without using a physical
device

4 MARKS Q2
1 .Compare JVM and DVM. (any four points)
2 .Describe various installation steps of android studio and its environment.

Steps to install Android studio and SDK


Pre-Installation Check List
1. Before installing Android SDK, there is need to install Java Development Kit (JDK).
Ensure that JDK is at or above 1.8.
2. Uninstall older version(s) of "Android Studio" and "Android SDK", if any
We need to install two packages:
1. Android Studio (IDE), which is an Integrated Development Environment (IDE)
2. Android SDK (Software Development Kit) for developing and running Android apps.
Steps to install Android studio:
Download Android Studio
1. Click Download Android Studio. The Terms and Conditions page with the Android Studio
License Agreement opens.
2. Read the License Agreement.
3. At the bottom of the page, if you agree with the terms and conditions, select the I have
read and agree with the above terms and conditions checkbox.
4. Click Download Android Studio to start the download.
5. When prompted, save the file to a location where you can easily locate it, such as the
Downloads folder.
6. Wait for the download to complete.
Install Android Studio
a) Open the folder where you downloaded and saved the Android Studio installation file.
b) Double-click the downloaded file.
c) If you see a User Account Control dialog about allowing the installation to make changes
to your computer, click Yes to confirm the installation.
d) Click Next to start the installation.
e) Accept the default installation settings for all steps.
f) Click finish when installation is done.
Installing Android SDK
Within Android Studio, you can install the Android SDK as follows:
1. Click Tools > SDK Manager.
2. In the SDK Platforms tab, select Android Tiramisu Preview.
3. In the SDK Tools tab, select Android SDK Build.
4. Click OK to install the SDK.

3 .Explain importance or use of developer console.


Google Play Developer Console is the platform that Google provides for Google Play and
Android developers to publish their apps.
● The Google Play Developer console allows app developers and marketers to better
understand how their apps are performing in terms of growth, technical performance such as
crashes or display issues, and financials.
● The console offers acquisition reports and detailed analysis which can help app devs find
out how well an app is really performing.
● The platform is important as it provides developers with access to first party data
(trustworthy information collected about an app’s audience that comes straight from Google
Play) that highlights the real performance of an app.
● It shows the number of impressions an app listing receives and the number of Installs an
app receives from different sources over time.

4 MARKS Q3
1.List and elaborate steps to deploy an Android application on Google play
store.

Steps to deploy and Android Application on Google Play Store:


Step 1: Make a Developer Account
Step 2: Plan to Sell? Link Your Merchant Account
Step 3: Create an App
Step 4: Prepare Store Listing
Step 5: Upload APK to an App Release
Step 6: Provide an Appropriate Content Rating
Step 7: Set Up Pricing & Distribution
Step 8: Rollout Release to Publish Your App
Step 1: Create a Developer Account
Before you can publish any app on Google Play, you need to create a Developer Account.
You can easily sign up for one using your existing Google Account. You’ll need to pay a
one-time registration fee of $25 using your international credit or debit card. It can take
up to 48 hours for your registration to be fully processed.
Step 2: Plan to Sell? Link Your Merchant Account
If you want to publish a paid app or plan to sell in-app purchases, you need to create a
payments center profile, i.e. a merchant account. A merchant account will let you manage
your app sales and monthly payouts, as well as analyze your sales reports right in your
Play Console.
Step 3: Create an App
Now you have create an application by clicking on 'Create Application'. Here you have
to select your app’s default language from the drop-down menu and then type in a title
for your app. The title of your app will show on Google Play after you’ve published.
Step 4: Prepare Store Listing
Before you can publish your app, you need to prepare its store listing. These are all the
details that will show up to customers on your app’s listing on Google Play. You not
necessarily complete it at once , you can always save a draft and revisit it later when
you’re ready to publish.
The information required for your store listing is divided into several categories such as
Product Details containing title, short and full description of the app, Your app’s title
and description should be written with a great user experience in mind. Use the right
keywords, but don’t overdo it. Make sure your app doesn’t come across as spam-y or
promotional, or it will risk getting suspended on the Play Store.
Graphic Assets where you can add screenshots, images, videos, promotional graphics,
and icons that showcase your app’s features and functionality.
Languages & Translations, Categorization where in category can be selected to which
your app belong to. Contact Details , Privacy Policy for apps that request access to
sensitive user data or permissions, you need to enter a comprehensive privacy policy that
effectively discloses how your app collects, uses, and shares that data.
Step 5: Upload APK to an App Release
Finally upload your app, by uploading APK file. Before you upload APK, you need to
create an app release. You need to select the type of release you want to upload your first
app version to. You can choose between an internal test, a closed test, an open test, and a
production release. The first three releases allow you to test out your app among a select
group of users before you make it go live for everyone to access.
This is a safer option because you can analyze the test results and optimize or fix your
app accordingly if you need to before rolling it out to all users.
Once you create a production release, your uploaded app version will become accessible
to everyone in the countries you choose to distribute it in and click on ‘Create release.’
Step 6: Provide an Appropriate Content Rating
If you don’t assign a rating to your app, it will be listed as ‘Unrated’. Apps that are
‘Unrated’ may get removed from Google Play.
To rate your app, you need to fill out a content rating questionnaire An appropriate
content rating will also help you get to the right audience, which will eventually improve
your engagement rates.
Step 7: Set Up Pricing & Distribution
Before you can fill out the details required in this step, you need to determine your app’s
monetization strategy. Once you know how your app is going to make money, you can go
ahead and set up your app as free or paid.
You can always change your app from paid to free later, but you cannot change a free app
to paid. For that, you’ll need to create a new app and set its price.
Step 8: Rollout Release to Publish Your App
The final step involves reviewing and rolling out your release after making sure you’ve
taken care of everything else.
Before you review and rollout your release, make sure the store listing, content rating,
and pricing and distribution sections of your app each have a green check mark next to
them.
Once you’re sure about the correctness of the details, select your app and navigate to
‘Release management’ – ‘App releases.’ You can always opt for reviews by clicking on
‘Review’ to be taken to the ‘Review and rollout release’ screen. Here, you can see if there
are any issues or warnings you might have missed out on.
Finally, select ‘Confirm rollout.’ This will also publish your app to all users in your target
countries on Google Play.

4 MARKAS Q4
1.Develop a program to send an SMS

AndroidManifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>
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">
<TextView
android:id="@+id/textView"
android:layout_width="81dp"
android:layout_height="41dp"
android:layout_marginEnd="268dp"
android:layout_marginBottom="576dp"
android:text="To :"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<TextView
android:id="@+id/textView2"
android:layout_width="70dp
android:layout_height="43dp"
android:layout_marginEnd="276dp"
android:layout_marginBottom="512dp"
android:text="Sms Text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="@+id/etPhno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="40dp"
android:layout_marginBottom="572dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<EditText
android:id="@+id/etmsg"
android:layout_width="193dp"
android:layout_height="51dp"
android:layout_marginEnd="56dp"
android:layout_marginBottom="504dp"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/btnSms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="156dp"
android:layout_marginBottom="400dp"
android:text="SEND SMS"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity
{
EditText et1,et2;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=findViewById(R.id.etPhno);
et2=findViewById(R.id.etmsg);
b1=findViewById(R.id.btnSms);
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.SEN
D_SMS)!
=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,new
String[]{Manifest.permission.SEND_SMS},100);
}
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String phno= et1.getText().toString();
String msg=et2.getText().toString();
SmsManager smsManager= SmsManager.getDefault();
smsManager.sendTextMessage(phno,null,msg,null,null);
Toast.makeText(MainActivity.this,"Sms sent successfully",
Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,"Sms failed to send... try again",
Toast.LENGTH_LONG).show();
}
}
});
}
}
2.Describe Android Architecture with diag

1. Applications:
• The top layer of android architecture is Applications. The native and third
party applications like Contacts, Email, Music, Gallery, Clock, Games, etc.
whatever we will build those will be installed on this layer only.
• The application layer runs within the Android run time using the classes and
services made available from the application framework.

2. Application Framework:
• The Application Framework provides the classes used to create an Android
application. It also provides a generic abstraction for hardware access and
manages the user interface and application resources.
• It basically provides the services through which we can create the particular
class and make that class helpful for the Applications creation.
• The application framework includes services like telephony service, location
services, and notification. manager, NFC service, view system, etc. which we
can use for application development as per our requirements.
3. Android Runtime:
• Android Runtime environment is an important part of Android rather than an
internal part and it contains a components like core libraries and the Dalvik
virtual machine.
• The Android run time is the engine that powers our applications along with the
libraries and it forms the basis for the application framework.
• Dalvik Virtual Machine (DVM) is a register-based virtual machine like Java
Virtual Machine (JVM).
• It is specially designed and optimized for android to ensure that a device can
run multiple instances efficiently. It relies on the Linux kernel for threading
and low-level memory
• management.
• The core libraries in android runtime will enable us to implement an android
applications using standard JAVA programming language.
4. Platform Libraries:
• The Platform Libraries includes various C/C++ core libraries and Java based
libraries such as SSL,libc, Graphics, SQLite, Webkit, Media, Surface Manger,
OpenGL etc. to provide a support for android development.
5. Linux Kernel:
• Linux Kernel is a bottom layer and heart of the android architecture. It is heart
of Android architecture that exists at the root of android architecture and
contains all the low-level device drivers for the various hardware components
of an Android device.
• Linux Kernel is responsible fro device drivers, power management, memory
management, device management and resource access. It manage all the
drivers such as display drivers, camera drivers, Bluetooth drivers, audio
drivers, memory drivers, etc. which are mainly required for the android device
during the runtime.
• The Linux Kernel will provide an abstraction layer between the device
hardware and the remainder of the stack. It is responsible for memory
management, power management, device management, resource access, etc.

6 MARKS Q5
1.Explain Service Life Cycle
A service is an application component which runs without direst interaction with the
user in the background.
● Services are used for repetitive and potentially long running operations, i.e., Internet
downloads, checking for new data, data processing, updating content providers and the
like.
● Service can either be started or bound we just need to call either startService() or
bindService() from any of our android components. Based on how our service was
started it will either be “started” or “bound”
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 Won’t
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.

2.Draw and explain activity life cycle.


onCreate (): Called then the activity is created. Used to initialize the activity, for example
create the user interface.
onStart ():called when activity is becoming visible to the user.
onResume (): Called if the activity get visible again and the user starts interacting with the
activity again. Used to initialize fields, register listeners, bind to services, etc.
onPause (): Called once another activity gets into the foreground. Always called before the
activity is not visible anymore. Used to release resources or save application data. For example you
unregister listeners, intent receivers, unbind from services or remove system
service listeners.
onStop (): Called once the activity is no longer visible. Time or CPU intensive shutdown
operations, such as writing information to a database should be down in the onStop() method.
This method is guaranteed to be called as of API 11.
onDestroy (): called before the activity is destroyed.
1. Activity States:
The Android OS uses a priority queue to assist in managing activities running on the device.
Based on the state a particular Android activity is in, it will be assigned a certain priority
within the OS. This priority system helps Android identify activities that are no longer in
use, allowing the OS to reclaim memory and resources. Fig. illustrates the states an activity
can go through, during its lifetime:
These states are often broken into three main teams as follows:
1. Active or Running:
Activities are thought of active or running if they're within the foreground, additionally
referred to as the top of the activity stack. this can be thought of the highets priority activity
within the Android Activity stack, and as such only be killed by the OS in extreme things,
like if the activity tries to use more memory than is available on the device as this might
cause the UI to become unresponsive.
2. Paused:
When the device goes to sleep, or an activity continues to be visible but partially hidden by
a new, non-full-sized or clear activity, the activity is taken into account paused. Paused
activities are still alive, that is, they maintain all state and member information, and stay
attached to the window manager. This can be thought of to be the second highest priority
activity within the android Activity stack and, as such, can solely be killed by the OS if
killing this activity can satisfy the resource requirement needed to keep the Active/Running
Activity stable and responsive.
3. Stopped:
Activities that are utterly obscured by another activity are thought of stopped or within the
background. Stopped activities still try and retain their state and member info for as long as
possible but stopped activities are thought of to be loweat priority of the three states and, as
such, the OS can kill activities during this state initial to satisfy the resource needs of higher
priority activities.

2.Explain Geocoding and reverse geocoding in android with example.


Geocoding: Converts an address (like "123 Main St, Mumbai") into geographical
coordinates (latitude and longitude).
Reverse Geocoding: Converts geographical coordinates into a readable address (like
"123 Main St, Mumbai").
Example: Geocoding and Reverse Geocoding
1. Add Permissions
Include location permissions in the AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
2. Layout File (res/layout/activity_main.xml)
A layout with a button and two TextView elements to show results.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<Button
android:id="@+id/btnGeocode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Coordinates from Address" />
<TextView
android:id="@+id/tvGeocodeResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp" />
<Button
android:id="@+id/btnReverseGeocode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Address from Coordinates"
android:layout_marginTop="20dp" />
<TextView
android:id="@+id/tvReverseGeocodeResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp" />
</LinearLayout>
3. Java Code (MainActivity.java)
Using Geocoder to perform geocoding and reverse geocoding.
package com.example.geocodingdemo;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnGeocode = findViewById(R.id.btnGeocode);
TextView tvGeocodeResult = findViewById(R.id.tvGeocodeResult);
Button btnReverseGeocode = findViewById(R.id.btnReverseGeocode);
TextView tvReverseGeocodeResult =
findViewById(R.id.tvReverseGeocodeResult);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
// Geocoding: Address to Coordinates
btnGeocode.setOnClickListener(v -> {
String address = "123 Main St, Mumbai";
try {
List<Address> addresses = geocoder.getFromLocationName(address, 1);
if (addresses != null && !addresses.isEmpty()) {
Address location = addresses.get(0);
tvGeocodeResult.setText("Coordinates: " + location.getLatitude() + ", " +
location.getLongitude());
} else {
tvGeocodeResult.setText("Address not found");
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
// Reverse Geocoding: Coordinates to Address
btnReverseGeocode.setOnClickListener(v -> {
double latitude = 19.0760; // Example: Mumbai's latitude
double longitude = 72.8777; // Example: Mumbai's longitude
try {
List<Address> addresses = geocoder.getFromLocation(latitude, longitude,
1);
if (addresses != null && !addresses.isEmpty()) {
Address address = addresses.get(0);
tvReverseGeocodeResult.setText("Address: " +
address.getAddressLine(0));
} else {
tvReverseGeocodeResult.setText("Address not found");
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
}
}
6.MARKS Q6
1. Develop an application to store student details like roll no, name, marks
and retrieve student information using roll no. in SQLite database. (Write
java and
xml file).

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editRollNo"
android:layout_width="match_parent”
android:layout_height="wrap_content"
android:hint="Roll No"
android:inputType="number" />
<EditText
android:id="@+id/editName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:inputType="text" />
<EditText
android:id="@+id/editMarks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Marks"
android:inputType="number" />
<Button
android:id="@+id/saveButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save Student Info" />
<EditText
android:id="@+id/searchRollNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Roll No to Search"
android:inputType="number" />
<Button
android:id="@+id/searchButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search Student" />
<TextView
android:id="@+id/studentInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Student Info will appear here"
android:textSize="18sp"
android:gravity="center"
android:layout_marginTop="20dp" />
</LinearLayout>
Java Code
package com.example.studentinfo;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// UI components
EditText editRollNo, editName, editMarks, searchRollNo;
Button saveButton, searchButton;
TextView studentInfo;
// SQLite helper class
DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize UI components
editRollNo = findViewById(R.id.editRollNo);
editName = findViewById(R.id.editName);
editMarks = findViewById(R.id.editMarks);
searchRollNo = findViewById(R.id.searchRollNo);
saveButton = findViewById(R.id.saveButton);
searchButton = findViewById(R.id.searchButton);
studentInfo = findViewById(R.id.studentInfo);
// Initialize DB helper
dbHelper = new DBHelper(this);
// Save button click listener
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveStudentInfo();
}
});
// Search button click listener
searchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchStudentInfo();
}
});
}
// Save student info to the database
private void saveStudentInfo() {
String rollNo = editRollNo.getText().toString();
String name = editName.getText().toString();
String marks = editMarks.getText().toString();
if (rollNo.isEmpty() || name.isEmpty() || marks.isEmpty()) {
Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show();
} else {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_ROLL_NO, rollNo);
values.put(DBHelper.COLUMN_NAME, name);
values.put(DBHelper.COLUMN_MARKS, marks);
long result = db.insert(DBHelper.TABLE_NAME, null, values);
if (result == -1) {
Toast.makeText(this, "Failed to save student info",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Student info saved",
Toast.LENGTH_SHORT).show();
clearFields();
}
}
}
// Search student info from the database
private void searchStudentInfo() {
String rollNo = searchRollNo.getText().toString();
if (rollNo.isEmpty()) {
Toast.makeText(this, "Please enter roll number",
Toast.LENGTH_SHORT).show();
} else {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] projection = {
DBHelper.COLUMN_ROLL_NO,
DBHelper.COLUMN_NAME,
DBHelper.COLUMN_MARKS
};
String selection = DBHelper.COLUMN_ROLL_NO + " = ?";
String[] selectionArgs = {rollNo};
Cursor cursor = db.query(DBHelper.TABLE_NAME, projection, selection,
selectionArgs, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String name =
cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.COLUMN
String marks =
cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.COLUMN_MARKS));
studentInfo.setText("Roll No: " + rollNo + "\nName: " + name + "\nMarks: "
+ marks);
cursor.close();
} else {
studentInfo.setText("No student found with this roll number");
}
}
}
// Clear input fields
private void clearFields() {
editRollNo.setText("");
editName.setText("");
editMarks.setText("")
searchRollNo.setText("");
}
}

2.Explain date picker with suitable example


DatePicker is used to display date selection widget in android application. It can be
used in either spinner mode or calendar mode ( date picker).
DatePicker Properties:
DatePickerMode :
Value can be spinner or calendar. If set to calendar, it will display a calendar which let
you choose date. If set to spinner, it will display a spinner to let you choose date.
XML file:
<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">
<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#150"
android:datePickerMode="spinner" />
<Button
android:id="@+id/submitButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@+id/simpleDatePicker"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:background="#150"
android:text="SUBMIT"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
Java File:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
DatePicker simpleDatePicker;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleDatePicker = (DatePicker) findViewById(R.id.simpleDatePicker);
submit = (Button) findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String day = "Day = " + simpleDatePicker.getDayOfMonth();
String month = "Month = " + (simpleDatePicker.getMonth() + 1);
String year = "Year = " + simpleDatePicker.getYear();
Toast.makeText(getApplicationContext(), day + "\n" + month + "\n" + year,
Toast.LENGTH_LONG).show();
}
});
}
}

3. Write a program to demonstrate Date and Time picker.


(Note: Consider the appropriate XML file. All attributes are not required.
In java file all imports are not expected. Different relevant logic/code can be
considered.)
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">
<TextView
android:id="@+id/tvDate"
android:layout_width="149dp"
android:layout_height="46dp"
android:layout_marginEnd="224dp"
android:layout_marginBottom="312dp"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/btnDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="96dp"
android:layout_marginBottom="312dp"
android:text="Set Date"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:ignore="DuplicateClickableBoundsCheck" />
<DatePicker
android:id="@+id/dtpcker"
android:layout_width="314dp"
android:layout_height="293dp"
android:layout_marginBottom="368dp"
android:datePickerMode="spinner"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.36"
app:layout_constraintStart_toStartOf="parent" />
<TimePicker
android:id="@+id/timepcker"
android:layout_width="184dp"
android:layout_height="195dp"
android:layout_marginEnd="132dp"
android:layout_marginBottom="108dp"
android:timePickerMode="spinner"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="@+id/tvTime"
android:layout_width="130dp"
android:layout_height="56dp"
android:layout_marginEnd="232dp"
android:layout_marginBottom="40dp"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/btnTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="104dp"
android:layout_marginBottom="48dp"
android:text="Set Time"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.datepickereg;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TextView tvDate,tvTime;
DatePicker dtpcker;
TimePicker timepcker;
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDate=findViewById(R.id.tvDate);
tvTime=findViewById(R.id.tvTime);
b1=findViewById(R.id.btnDate);
b2=findViewById(R.id.btnTime);
dtpcker=findViewById(R.id.dtpcker);
timepcker=findViewById(R.id.timepcker);
b1.setOnClickListener(new View.OnClickListener() {
@Override
_____________________________________________________________________________
Page No: 20 | 39
public void onClick(View view) {
tvDate.setText("Date : "+dtpcker.getDayOfMonth()+"-
"+dtpcker.getMonth()+"-"+dtpcker.getYear());
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tvTime.setText(timepcker.getCurrentHour()
+":"+timepcker.getCurrentMinute());
}
});
}
}

You might also like