CP 313 All Lectures
CP 313 All Lectures
Among many other things, the manifest file is required to declare the following:
• The app's package name.
usually matches your code's namespace. The Android build tools use this to
determine the location of code entities when building your project. When
packaging the app, the build tools replace this value with the application ID
from the Gradle build files, which is used as the unique app identifier on the
system and on Google Play.
Android Project Structure (Manifest file)
An intent-filter
This is a tag used in the manifest file of your app, generally for two
basic reasons:-
To specify which activity of your app is going to be
the launcher activity(the home screen).
It is used to register broadcast receivers or services.
Android Project Structure (Manifest file)
App components
For each app component that you create in your app, you must declare a
corresponding XML element in the manifest file:
<activity> for each subclass of Activity.
<service> for each subclass of Service.
<receiver> for each subclass of BroadcastReceiver.
<provider> for each subclass of ContentProvider.
If you subclass any of these components without declaring it in the manifest
file, the system cannot start it.
Android Project Structure (Manifest file)
Permissions
Android apps must request permission to access sensitive user data (such as
contacts and SMS) or certain system features (such as the camera and internet
access).
Each permission is identified by a unique label.
For example, an app that needs to send SMS messages must have the following
line in the manifest:
<manifest ... >
<uses-permission android:name="android.permission.SEND_SMS"/>
...
</manifest>
Android Project Structure (Manifest file)
Device compatibility
The manifest file is also where you can declare what types of hardware or
software features your app requires, and thus, which types of devices your app is
compatible with.
Google Play Store does not allow your app to be installed on devices that don't
provide the features or system version that your app requires.
There are several manifest tags that define which devices your app is compatible
with.
The following are just a couple of the most common tags.
Android Project Structure (Manifest file)
<uses-feature>
The <uses-feature> element allows you to declare hardware and software features
your app needs. For example, if your app cannot achieve basic functionality on a
device without a compass sensor, you can declare the compass sensor as required
with the following manifest tag:
<uses-sdk>
Each successive platform version often adds new APIs not available in the
previous version.
To indicate the minimum version with which your app is compatible, your
manifest must include the <uses-sdk> tag and its minSdkVersion attribute.
Android Project Structure (Java folder)
Java folder contains all the java and Kotlin source code (.java) files which we
create during the app development, including other Test files.
If we create any new project using java, by default the class file
MainActivity.java file will create automatically under the package name
“com.example.myapplication1” like as shown below.
Android Project Structure (Java folder)
Android Project Structure (Resource (res) folder)
res/drawable folder
It contains the different type of images used for the development of
the application.
We need to add all the images in drawable folder for the application
development.
Android Project Structure (Resource (res) folder)
res/layout folder
Layout folder contains all XML layout files which we used to define
the user Interface of our application.
It contains the activity_main.xml file.
Android Project Structure (Resource (res) folder)
res/mipmap folder
This folder contains launcher.xml files to define icons which are used
to show on the home screen.
It contains different density type of icons depends upon the size of the
device such as hdpi, mdpi, xhdpi.
Android Project Structure (Resource (res) folder)
res/values folder
Values folder contains a number of XML files like strings, dimens,
colors and styles definitions.
One of the most important file is strings.xml file which contains the
resources.
Android Project Structure (Resource (res) folder)
A menu
This resource defines an application menu (Options Menu, Context
Menu, or submenu) that can be inflated with MenuInflater.
Android Project Structure (Gradle Scripts folder)
android:layout_marginTop
This is the extra space on the top
side of the layout.
Layouts in android(common properties)
android:layout_marginBottom
This is the extra space on the bottom side of the layout.
android:layout_marginLeft
This is the extra space on the left side of the layout.
android:layout_marginRight
This is the extra space on the right side of the layout.
android:layout_gravity
This specifies how child Views are positioned.
Layouts in android(common properties)
android:layout_weight
This specifies how much of the extra space in the layout
should be allocated to the View.
Layouts in android(Relative Layout)
RelativeLayout is a view group that displays child views in relative positions.
RelativeLayout enables you to specify how child views are positioned relative to
each other.
The position of each view
can be specified as relative to
sibling elements or relative to the parent.
Layouts in android(Table Layout)
TableLayout - displays elements in the form of a table, with rows and
columns.
Android UI Controls
There are number of UI controls provided by Android that
allow you to build the graphical user interface for your app.
A TextView displays text to the user and optionally allows
them to edit it.
A TextView is a complete text editor, however the basic class
is configured to not allow editing.
Android UI Controls(attributes of text view)
android:id
This is the ID which uniquely identifies the control.
android:capitalize
If set, specifies that this TextView has a textual input method and should automatically capitalize
what the user types.
android:hint
Hint text to display when the text is empty.
android:password
Whether the characters of the field are displayed as password dots instead of themselves. Possible
value either "true" or "false".
Android UI Controls(Edit Text)
A EditText is an overlay over TextView that configures itself to be
editable.
It is the predefined subclass of TextView that includes rich editing
capabilities.
Android UI Controls(Button)
A Button is a Push-button which can be pressed, or clicked, by the
user to perform an action.
Android UI Controls(Check Box)
A CheckBox is an on/off switch that can be toggled by the
user.
You should use check-boxes when presenting users with a
group of selectable options that are not mutually exclusive.
Android UI Controls(Radio Button)
A RadioButton has two states: either checked or unchecked.
This allows the user to select one option from a set.
Android UI Controls(Spinner)
Spinner allows you to select an item from a drop down
menu
END
CP 313: MOBILE APPLICATIONS DEVELOPMENT
Contents
oActivities
● Defining an activity
● Starting a new activity with an intent
● Passing data between activities with extras
● Navigating between activities
What is an Activity?
oAn Activity is an application component
● Represents one window, one hierarchy of views
● Typically fills the screen, but can be embedded in other
activity or a appear as floating window
● Java class, typically one activity in one file
What is an Activity?
oAn activity represents a single screen with a user interface
just like window or frame of Java.
oAndroid activity is the subclass of ContextThemeWrapper
class.
Activity Life Cycle
If you have worked with C, C++ or Java programming language then
you must have seen that your program starts from main() function.
Very similar way, Android system initiates its program with in an
Activity starting with a call on onCreate() callback method.
There is a sequence of callback methods that start up an activity and
a sequence of callback methods that tear down an activity as shown in
the next slide.
Activity Life Cycle
Activity Life Cycle
onCreate(): This is the first callback and called when the activity is first created.
onStart(): This callback is called when the activity becomes visible to the user.
onResume(): This is called when the user starts interacting with the application.
onPause(): The paused activity does not receive user input and cannot execute any
code and called when the current activity is being paused and the previous activity is
being resumed.
onStop(): This callback is called when the activity is no longer visible.
onDestroy(): This callback is called before the activity is destroyed by the system.
onRestart(): This callback is called when the activity restarts after stopping it.
What does an Activity do?
Represents an activity, such as ordering groceries, sending
email, or getting directions
● Handles user interactions, such as button clicks, text entry,
or login verification
● Can start other activities in the same or other apps
● Has a life cycle—is created, started, runs, is paused,
resumed, stopped, and destroyed
Examples of Activities
Apps and activities
Activities are loosely tied together to make up an app
● First activity user sees is typically called "main activity"
● Activities can be organized in parent-child relationships in
the Android manifest to aid navigation
Layouts and Activities
An activity typically has a UI layout
● Layout is usually defined in one or more XML files
● Activity "inflates" layout as part of being created
Implement new activities
1.Define layout in XML
2. Define Activity Java class
○ extends AppCompatActivity
3. Connect Activity with Layout
○ Set content view in onCreate()
4. Declare Activity in the Android manifest
1. Define layout in XML
2. Define Activity Java class
3. Connect activity with layout
3. Connect activity with layout
package com.example.myapplication10;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
3. Connect activity with layout
public class MainActivity extends AppCompatActivity {
private EditText FirstName,LastName, Results;
private Button Submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirstName = (EditText) findViewById(R.id.editTextFName);
LastName =(EditText) findViewById(R.id.editTextLName);
Results =(EditText) findViewById(R.id.tvResults);
Submit =(Button) findViewById(R.id.btnSubmit);
3. Connect activity with layout
Submit.setOnClickListener(new View.OnClickListener() {
@Override
int num1=Integer.parseInt(FirstName.getText().toString());
int num2=Integer.parseInt(LastName.getText().toString());
int sum=num1+num2;
});
}
4. Declare activity in Android manifest
4. Declare main activity in manifest
Intents
What is an intent?
An intent is a description of an operation to be performed.
An Intent is an object used to request an action from another
app component via the Android system.
What can intents do?
oStart activities
◦ A button click starts a new activity for text entry
◦ Clicking Share opens an app that allows you to post a photo
● Start services
◦ Initiate downloading a file in the background
● Deliver broadcasts
◦ The system informs everybody that the phone is now charging
Types of Intents
Explicit Intent
Implicit Intent
Types of Intents (Explicit Intent)
We can also pass the information from one activity to another using explicit intent.
Types of Intents (Implicit Intent)
We can also pass the information from one activity to another using explicit intent.
Starting Activities
Start an Activity with an explicit intent
To start a specific activity, use an explicit intent
1. Create an intent
○ Intent intent = new Intent(this, ActivityName.class);
2. Use the intent to start the activity
○ startActivity(intent);
public void onClick(View v) {
}
});
}
public void Activity2(){
Intent myIntent = new Intent(this,HomeActivity.class);
startActivity(myIntent);
}
}
Sending and Receiving Data
We can send data while calling one activity from another activity
using intent.
All we have to do is add the data to Intent object using putExtra()
method.
The data is passed in key value pair.
The value can be of types like int, float, long, string, etc.
Sending Data
Submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Activity2();
}
});
}
public void Activity2(){
int num1=Integer.parseInt(FirstName.getText().toString());
int num2=Integer.parseInt(LastName.getText().toString());
//int sum=num1+num2;
// Results.setText("The Answer is "+sum);
Intent myIntent = new Intent(this,HomeActivity.class);
myIntent.putExtra("numberOne:",num1);
myIntent.putExtra("numberTwo:",num2);
startActivity(myIntent);
}
}
Receiving Data
public class HomeActivity extends AppCompatActivity {
private TextView n1,n2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
n1=(TextView)findViewById(R.id.tvNumber1);
n2=(TextView)findViewById(R.id.tvNumber2);
}
}
Intents can be used for broadcasting a
message
Suppose that the battery of your mobile phone is low and
the message is sent to different android applications to your
phone alerting that the battery is low
Your Turn
Services
Broadcast Message
Implicit Intents
END
CP 313: Mobile Application Development
Android Fragments
Lecture # 4
A Useful Trick!
• Press Ctrl and click on keyword of java in Android Studio.
You will get complete definitions of that keyword.
REDMOL Saturday, October 07, 2023 14
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY
STEP ONE
Create the fragment
STEP TWO
Define the activity to host the fragment
<TextView
android:id="@+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment Title"
android:textSize="40dp"
android:gravity="center">
</TextView>
REDMOL Saturday, October 07, 2023 19
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY
<Button
android:id="@+id/btnFirstFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment One"
android:textSize="40dp"
android:layout_below="@id/tvTitle"
android:gravity="center"></Button>
<Button
android:id="@+id/btnSecondFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fragment Two"
android:textSize="40dp"
android:layout_below="@id/btnFirstFragment"
android:gravity="center"></Button>
REDMOL Saturday, October 07, 2023 20
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY
<LinearLayout
android:id="@+id/fragMentCOntainer"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_below="@id/btnSecondFragment"
android:layout_margin="30dp"
android:layout_height="wrap_content">
android:la
</LinearLayout>
</RelativeLayout>
Step Three
Add the fragment in the activity you have
created
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
fragOne=(Button) findViewById(R.id.btnFirstFragment );
fragTwo=(Button) findViewById(R.id.
btnSecondFragment );
REDMOL Saturday, October 07, 2023 24
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY
fragOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment frag1=new FragmentOne();
FragmentTransaction ft=getSupportFragmentManager().
beginTransaction();
ft.replace(R.id.fragMentCOntainer ,frag1);
ft.addToBackStack(null);
ft.commit();
}
});
REDMOL Saturday, October 07, 2023 25
ADDING FRAGMENT DYNAMICALLY TO AN ACTIVITY
fragTwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment frag2=new FragmentTwo();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragMentCOntainer ,frag2);
ft.addToBackStack(null);
ft.commit();
}
});
• Services
• Broadcast Receivers
• Notifications
Services
Foreground Services
• When you use a foreground service, you must
display a notification so that users are actively
aware that the service is running.
• This notification cannot be dismissed unless the
service is either stopped or removed from the
foreground.
Types of Services
(There are three types of services:)
Background
A background service performs an operation
that isn't directly noticed by the user.
For example, if an app used a service to
compact its storage, that would usually be a
background service.
Types of Services
(There are three types of services:)
Bound
A service is bound when an application component binds to it by calling
bindService().
A bound service offers a client-server interface that allows
components to interact with the service, send requests, receive results,
and even do so across processes with interprocess communication
(IPC).
A bound service runs only as long as another application component is
bound to it.
Multiple components can bind to the service at once, but when all of
them unbind, the service is destroyed.
Services life cycle
• In android, services have Two (2) possible paths to complete its
life cycle namely Started and Bounded.
Started Service (Unbounded Service):
• By following this path, a service will initiate when an
application component calls the startService() method.
• Once initiated, the service can run continuously in the
background even if the component is destroyed which
was responsible for the start of the service.
Services life cycle
• To create a service, you must create a subclass of
Service or use one of its existing subclasses.
• In your implementation, you must override some
callback methods that handle key aspects of the
service lifecycle and provide a mechanism that allows
the components to bind to the service, if appropriate.
• These are the most important callback methods that
you should override:
Services life cycle
onStartCommand()
• The system invokes this method by calling startService()
when another component (such as an activity) requests
that the service be started.
• When this method executes, the service is started and
can run in the background indefinitely.
Services life cycle
• If you implement this, it is your responsibility to stop the
service when its work is complete by calling stopSelf()
or stopService().
• If you only want to provide binding, you don't need to
implement this method.
Services life cycle
Services life cycle
Bounded Service:
• It can be treated as a server in a client-server interface.
• By following this path, android application components can
send requests to the service and can fetch results.
• A service is termed as bounded when an application
component binds itself with a service by calling bindService()
method.
• To stop the execution of this service, all the components must
unbind themselves from the service by using unbindService()
method.
Services life cycle
onBind()
The system invokes this method by calling
bindService() when another component wants to bind
with the service (such as to perform RPC).
In your implementation of this method, you must
provide an interface that clients use to communicate
with the service by returning an IBinder.
You must always implement this method; however, if
you don't want to allow binding, you should return null.
Services life cycle
onCreate()
The system invokes this method to perform one-time
setup procedures when the service is initially created
(before it calls either onStartCommand() or onBind()).
If the service is already running, this method is not
called.
Services life cycle
onDestroy()
The system invokes this method when the
service is no longer used and is being destroyed.
Your service should implement this to clean up
any resources such as threads, registered
listeners, or receivers.
This is the last call that the service receives.
Declaring a service in the manifest
• You must declare all services in your application's manifest file, just as you
do for activities and other components.
• To declare your service, add a <service> element as a child of the
<application> element. Below is an example:
<manifest ... >
...
<application ... >
<service android:name=".ExampleService" />
...
</application>
</manifest>
Creating a started service
• A started service is one that another component starts by
calling startService(), which results in a call to the service's
onStartCommand() method.
• When a service is started, it has a lifecycle that's independent of
the component that started it.
• The service can run in the background indefinitely, even if the
component that started it is destroyed.
• As such, the service should stop itself when its job is complete
by calling stopSelf(), or another component can stop it by
calling stopService().
Creating a started service
• An application component such as an activity can start the
service by calling startService() and passing an Intent that
specifies the service and includes any data for the service to use.
• The service receives this Intent in the onStartCommand() method.
• The Service class is the base class for all services.
• When you extend this class, it's important to create a new thread
in which the service can complete all of its work; the service uses
your application's main thread by default, which can slow the
performance of any activity that your application is running.
Creating a started service (Interface)
<? xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Service App"
android:textStyle="bold"
android:textSize="40dp"
android:textColor="@color/teal_200"
android:gravity="center">
</TextView>
<Button
android:id="@+id/btnStartService"
Creating a android:layout_width="match_parent"
android:layout_height="wrap_content"
started service android:layout_below="@+id/tvTitle"
android:layout_marginTop="30sp"
(Interface) android:text="Start Service"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="@color/Red"
android:gravity="center">
</Button>
<Button
android:id="@+id/btnStopService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btnStartService"
android:layout_marginTop="30sp"
android:text="Stop Service"
android:textSize="40sp"
android:textStyle="bold"
android:textColor="@color/Red"
android:gravity="center">
</Button>
Creating a package com.example.
Service by myapplication;
extending a
import android.app.Service;
service class. import android.content.Intent;
import android.os.IBinder;
@Override
public void onDestroy() {
super.onDestroy();
}
public class MainActivity extends AppCompatActivity {
Button startService, stopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Interface with
stopService=(Button) findViewById(R.id.btnStopService);
startService.setOnClickListener(new View.OnClickListener() {
@Override
@Override
public void onDestroy() {
super.onDestroy();
myPlayer.stop();
}
}
Services Behaviors
Services Behaviors
START_STICKY
Services that are explicit managed and long running ie. Your
starting your services and you are stopping your services using
startService() and stopService() methods.
The advantage of START_STICKY is if the service get killed, it will
automatically get started.
But when it get restarted, it will not get the intent values, so the
intent value will be NULL ie. It will not remember what was the
previous calculated value in the intent.
Music service is a good example here. You don’t your music to get
started automatic on your ears in unexpected time.
Services Behaviors
START_NOT_STICKY
You are not starting the service but the intent is triggered you will
start it.
Here the services are running periodically and get self stop.
If the service get stopped, it will not automatically restarted. If the
service get killed, and intent is triggered, then the service will start.
Tasks that runs periodically in the background are examples of
START_NOT_STICKY
Alarm service is an example of such a service.
Services Behaviors
START_REDELIVER_INTENT
Here The services will always get restated and it will
get the previous intent values.
Good example is a file download.
If the file stopped due to internet connection, when the
internet connection is available, then the file has to
restated automatically and it has to continue where it
ended when the internet connection get lost.
Bound Services
• A bound service is the server in a client-server interface.
• A bound service allows components (such as activities)
to bind to the service, send requests, receive responses,
and even perform interprocess communication (IPC).
• A bound service typically lives only while it serves
another application component and does not run in the
background indefinitely.
Bound Services
• A bound service is an implementation of the Service
class that allows other applications to bind to it and
interact with it.
• 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.
Bound Services
• A client can bind to the service by calling bindService().
• When it does, it must provide an implementation of
ServiceConnection, which monitors the connection with the
service.
• The bindService() method returns immediately without a
value, but when the Android system creates the connection
between the client and service, it calls
onServiceConnected() on the ServiceConnection, to deliver
the IBinder that the client can use to communicate with the
service.
Bound Services
• Multiple clients can connect to the service at once.
• However, the system calls your service's onBind()
method to retrieve the IBinder only when the first client
binds.
• The system then delivers the same IBinder to any
additional clients that bind, without calling onBind() again.
• When the last client unbinds from the service, the system
destroys the service (unless the service was also started
by startService()).
Creating a Bound Service
• When you implement your bound service, the most important
part is defining the interface that your onBind() callback method
returns.
• When creating a service that provides binding, you must provide
an IBinder that provides the programming interface that clients
can use to interact with the service.
• There are three ways you can define the interface:
Creating a Bound Service
Creating a Bound Service
Extending the Binder class
If your service is private to your own application and runs in the
same process as the client (which is common), you should
create your interface by extending the Binder class and returning
an instance of it from onBind().
The client receives the Binder and can use it to directly access
public methods available in either the Binder implementation or
even the Service.
Creating a Bound Service
Using a Messenger
If you need your interface to work across different processes, you
can create an interface for the service with a Messenger.
Using AIDL
AIDL (Android Interface Definition Language) performs all the
work to decompose objects into primitives that the operating
system can understand and marshall them across processes to
perform IPC.
The previous technique, using a Messenger, is actually based on
AIDL as its underlying structure
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
Creating a bound Service
BROADCAST RECEIVERS
Examples Events occurring in android
Register events in manifest file (static) or
in code(dynamically)
Step One: Creating a Java class that
extends Broadcast Receiver
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
Demo
Shared preference
Shared preference
public class MainActivity extends AppCompatActivity {
Button save;
EditText name,email;
public static final StringSHARED_PREF ="shared preference";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
save=(Button) findViewById(R.id.btnSave );
name=(EditText) findViewById(R.id.etName );
email=(EditText) findViewById(R.id.etEMail );
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveData();
}
});
}
Shared preference
Demo
Step One
• Create an HELPER class and override its methods
• A helper class to manage database creation and
version management.
• SQLiteOpenHelper class provides the functionality to use the
SQLite database.
• For performing any database operation, you have to provide the
implementation of onCreate() and onUpgrade() methods of
SQLiteOpenHelper class.
Step One
public class DatabaseHelper extends SQLiteOpenHelper {
public static final StringDATABASE ="users.db";
public static final StringTABLE_NAME ="students";
public DatabaseHelper(Context context) {
super(context,DATABASE , null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Step Two
• Affect the onCreate() and onUpgrade() methods
Step Two
public class DatabaseHelper extends SQLiteOpenHelper {
public static final StringDATABASE ="users.db";
public static final StringTABLE_NAME ="students";
public DatabaseHelper(Context context) {
super(context,DATABASE , null, 1);
SQLiteDatabase db=this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+TABLE_NAME +"(Id INTEGER PRIMARY KEY AUTOINCREMENT,Name TEXT,EMAIL
TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
onCreate(db);
}
}
Step Three
• In the Main Activity, create an instance of the
Helper class to access the Helper class we have
created so far.
• Use the instance of the helper class to call the
constructor
• Once the constructor is called it is going to
create the database and the table.
Step Three
//Constants
public static final String DATABASE="users.db";
public static final String TABLE_NAME="students";
public static final String COL1="Id";
public static final String COL2="Name";
public static final String COL3="EMAIL";
Step Four
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME );
onCreate(db);
}
public boolean insertData(String name,String email){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues myContentValues=new ContentValues();
myContentValues.put(COL2 ,name);
myContentValues.put(COL3 ,email);
Long results=db.insert(TABLE_NAME ,null,myContentValues);
if(results==-1){
return false
}else{
return true;
}
}
}
Step Five
• Within the Main Class create a method to add data from the
layout and then use the instance of the Helper class to call the
method that insert data.
Step Five
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
dbhelper = new DatabaseHelper(this);
saveData=(Button) findViewById(R.id.btnSave );
name=(EditText) findViewById(R.id.etName );
email=(EditText) findViewById(R.id.etEMail );
addData();
}
Step Five
public void addData(){
saveData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted= dbhelper.insertData(name.getText().toString(),email.getText().
toString());
if(isInserted=true){
Toast.makeText (MainActivity.this, "Data addedd Successfully", Toast.LENGTH_SHORT ).
show();
}else{
Toast.makeText (MainActivity.this, "Data not Addedd", Toast.LENGTH_SHORT ).show();
}
}
});
}
END