100% found this document useful (1 vote)
1K views

BCA 6th Sem Mobile Programming

Mobile application development involves writing software for devices like smartphones. A mobile device is portable, personal, always with you, easy to use, and has network connectivity. The history of Android includes its founding in 2003 and acquisition by Google in 2005. There are four main approaches to mobile development: native apps, cross-platform native apps, hybrid apps, and web apps.
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
100% found this document useful (1 vote)
1K views

BCA 6th Sem Mobile Programming

Mobile application development involves writing software for devices like smartphones. A mobile device is portable, personal, always with you, easy to use, and has network connectivity. The history of Android includes its founding in 2003 and acquisition by Google in 2005. There are four main approaches to mobile development: native apps, cross-platform native apps, hybrid apps, and web apps.
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/ 6

What do you mean by mobile programming? Features Example: hybrid widget.

Example: hybrid widget. As the name suggests, hybrid apps combine the functionality of two or
Mobile application development is the set of processes and procedures involved in writing second.xml more different types of other widgets. This can be tricky to program, but they often offer
software for small, wireless computing devices, such as smartphones and other hand-held <?xml version="1.0" encoding="utf-8"?> seamless and fully-integrated options that users enjoy. An example of a hybrid widget is a
devices. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" widget for a music player that, in addition to offering control over music, also includes
A mobile device has the following features: android:layout_width="match_parent" information about the song, band, album, and so forth..
• It’s portable. android:layout_height="match_parent" Android Layout Types with examples:
• It’s personal. android:gravity="center" A layout defines the structure for a user interface in your app, such as in an activity. All
• It’s with you almost all the time. android:orientation="vertical"> elements in the layout are built using a hierarchy of View and View Group objects. A View
• It’s easy and fast to use. <TextView usually draws something the user can see and interact with.
• It has some kind of network connection. android:layout_width="wrap_content" Following are the different types of layout used for designing the User Interface.
========================================================== android:layout_height="wrap_content" 1. Linear Layout
Explain History of Android and it’s versions in brief android:text="@string/text_question" 2. Relative Layout
The code names of android ranges from A to J currently, such as Aestro, Blender, Cupcake, android:textStyle="bold" 3. Constraint layout
Donut, Eclair, Froyo, Gingerbread, Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat android:textSize="20sp"/>
and Lollipop. <LinearLayout Linear Layout
1.Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United android:layout_width="wrap_content" Linear Layout is a view group that aligns all children in a single direction, vertically or
States in October, 2003. android:layout_height="wrap_content" horizontally. You can specify the layout direction with the android: orientation attribute.
2.In 17th August 2005, Google acquired android Incorporation. Since then, it is in the android:orientation="horizontal"> All children of a LinearLayout are stacked one after the other, so a vertical list will only
subsidiary of Google Incorporation. <Button have one child per row, no matter how wide they are, and a horizontal list will only be one
android:layout_width="wrap_content" row high (the height of the tallest child, plus padding). A LinearLayout respects margins
android:layout_height="wrap_content" between children and the gravity (right, center, or left alignment) of each child.
android:text="@string/text_true"/>
<Button Example:
android:layout_width="wrap_content" <?xml version="1.0" encoding="utf-8"?>
android:layout_height="wrap_content" <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:text="@string/text_false"/> android:layout_width="match_parent"
</LinearLayout> android:layout_height="match_parent"
</LinearLayout> android:orientation="vertical">
<TextView
The root element of this layout’s view hierarchy is a LinearLayout. As the root element, android:layout_width="wrap_content"
the LinearLayout must specify the Android resource XML namespace at android:layout_height="wrap_content"
http://schemas.android.com/ apk/res/android. android:text="This is label 1"
LinearLayout inherits from a subclass of View named ViewGroup. A ViewGroup is a widget android:textSize="20sp"/>
that contains and arranges other widgets. You use a LinearLayout when you want <TextView
widgetsarranged in a single column or row. Other ViewGroup subclasses are android:layout_width="wrap_content"
FrameLayout,TableLayout, and RelativeLayout. android:layout_height="wrap_content"
When a widget is contained by a ViewGroup, that widget is said to be a child of android:text="This is label 2"
theViewGroup. The root LinearLayout has two children: a TextView and another android:textSize="20sp"/>
LinearLayout.The child LinearLayout has two Button children of its own. <TextView
There are four major development approaches when building mobile applications: android:layout_width="wrap_content"
1. Native Mobile Applications android:layout_height="wrap_content"
2. Cross-Platform Native Mobile Applications android:text="This is label 3"
3. Hybrid Mobile Applications Manifest file and example:
android:textSize="20sp"/>
4. Progressive Web Applications The manifest file describes essential information about your app to the Android build
</LinearLayout>
tools, the Android operating system, and Google Play.
Native Applications • The app's package name, which usually matches your code's namespace. The Android
============================================================
Native mobile applications are written in the programming language and frameworks build tools use this to determine the location of code entities when building your project.
Relative Layout
provided by the platform owner and running directly on the operating system of the When packaging the app, the build tools replace this value with the application ID from
Relative Layout is a view group that displays child views in relative
device such as iOS and Android. the Gradle build files, which is used as the unique app identifier on the system and on
positions. The position of each view can be specified as relative
Google Play.
to sibling elements (such as to the left-of or below another view)
Cross-Platform Applications • The components of the app, which include all activities, services, broadcast receivers,
or in positions relative to the parent Relative Layout area (such
Cross-platform native mobile applications can be written in variety of different and content providers. Each component must define basic properties such as the name of
as aligned to the bottom, left or center).
programming languages and frameworks, but they are compiled into a native application its Kotlin or Java class. It can also declare capabilities such as which device configurations
A RelativeLayout is a very powerful utility for designing a user
running directly on the operating system of the device. it can handle, and intent filters that describe how the component can be started.
interface because it can eliminate nested view groups and keep
• The permissions that the app needs in order to access protected parts of the system or
your layout hierarchy flat, which improves performance..
Hybrid-Web Applications other apps. It also declares any permissions that other apps must have if they want to
Hybrid mobile applications are built with standard web technologies - such as JavaScript, access content from this app.
Following code snippet will demonstrate RelativeLayout:
CSS, and HTML5 - and they are bundled as app installation packages. Contrary to the native • The hardware and software features the app requires, which affects which devices can
apps, hybrid apps work on a 'web container' which provides a browser runtime and a install the app from Google Play.
1. <?xml version="1.0" encoding="utf-8"?>
bridge for native device APIs via Apache Cordova. AndroidManifest.xml
2. <RelativeLayout
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:android="http://schemas.android.com/apk/res/android"
Progressive Web Applications package="com.example.raazu.myapplication">
4. android:layout_width="match_parent"
WAs offer an alternative approach to traditional mobile app development by skipping app <application
5. android:layout_height="match_parent">
store delivery and app installations. PWAs are web applications that utilize a set of android:allowBackup="true"
6. <TextView
browser capabilities - such as working offline, running a background process, and adding android:icon="@mipmap/ic_launcher"
7. android:layout_width="wrap_content"
a link to the device home screen - to provide an 'app like' user experience. android:label="@string/app_name"
8. android:layout_height="wrap_content"
android:roundIcon="@mipmap/ic_launcher_round"
9. android:text="Label 1"
android:supportsRtl="true"
10. android:textSize="20sp"
android:theme="@style/AppTheme">
Mobile Application Development Lifecycle 11. android:id="@+id/label1" />
<activity android:name=".Second">
There are two interlinked core components of a mobile application: 1) the mobile 12. <TextView
<intent-filter>
application “Front-End” that resides on the mobile device, and 2) the services “Back-End” 13. android:layout_width="wrap_content"
<action android:name="android.intent.action.MAIN" />
that supports the mobile front-end. 14. android:layout_height="wrap_content"
<category android:name="android.intent.category.LAUNCHER" />
15. android:text="Label 2"
</intent-filter>
16. android:textSize="20sp"
</activity>
17. android:id="@+id/label2"
</application>
18. android:layout_toRightOf="@+id/label1"/>
</manifest>
19. <TextView
20. android:layout_width="wrap_content"
Intent filters roles for any activity 21. android:layout_height="wrap_content"
App activities, services, and broadcast receivers are activated by intents. An intent is a 22. android:text="Label 3"
message defined by an Intent object that describes an action to perform, including the 23. android:textSize="20sp"
data to be acted upon, the category of component that should perform the action, and 24. android:id="@+id/label3"
other instructions. When an app issues an intent to the system, the system locates an app 25. android:layout_below="@+id/label1" />
• The mobile front-end is the visual and interactive part of the application the user component that can handle the intent based on intent filter declarations in each app's 26. </RelativeLayout>
experiences. It usually resides on the device, or there is at least an icon representing the manifest file. The system launches an instance of the matching component and passes the
app that is visible on the home screen or is pinned in the application CatLog of the device. Intent object to that component. If more than one app can handle the intent, then the
The application can be downloaded from the platform app store, side-loaded directly onto user can select which app to use.
the device, or can be reached through the device’s browser. An app component can have any number of intent filters (defined with the <intent-filter>
Constraint Layout
element), each one describing a different capability of that component. If activity is
Constraint layout is an advanced version of a Relative layout. It is used to reduce the child
• Regardless of what front-end platform or development methodology is being used, defined with <intent-filter> element in manifest file than that activity will be launched as
view hierarchies and improve the performance. It is used to define a layout by assigning
delivering high-quality mobile applications that delight and retain users requires reliable the first activity of application.
constraints for every child view/widget relative to other views present. A ConstraintLayout
back-end services. is similar to a RelativeLayout, but with more power. The aim of ConstraintLayout is to
Explain any four widgets with their attributes in detail android? improve the performance of the applications by removing the nested views with a flat and
• Given the critical importance of back-end services for the success of the mobile A widget is a small gadget or control of your android application placed on the home flexible design.
application, the developers have several important architectural decisions that they must screen. Widgets can be very handy as they allow you to put your favourite applications on
consider. These decisions include which services should they build themselves and which your home screen in order to quickly access them. You have probably seen some common Following code snippet will demonstrate constraint layout.
third party services should they leverage, and then should they run and maintain their own widgets, such as music widget, weather widget, clock widget e.t.c <?xml version="1.0" encoding="utf-8"?>
services or should they take advantage of 3rd party services. Information widgets are by far the most common type of widget. They display vital <android.support.constraint.ConstraintLayout
information from an app that is easily visible without actually accessing the app’s main UI. xmlns:android="http://schemas.android.com/apk/res/android"
Environment Setup For android application Development Things like clocks, weather apps, sports score trackers, and other sorts of things are all xmlns:app="http://schemas.android.com/apk/res-auto"
In order to write an Android application, we are going to need a development good examples of informational widgets. It’s important to remember that only the most android:layout_width="match_parent"
environment. Google has made a very useful tool for all Android Developers, the Android vital information should be supplied in order to not clutter the home screen with too much
Studio. Android Studio is the official IDE for Android development, and with a single information. Users typically have control over just how much information is displayed by
download includes everything you need to begin developing Android apps. an informational widget and, usually, touching the widget will open more detailed
Step 1 - First we have to have installed the Java Development Kit (JDK) from Oracle. information about what it’s displaying.
RelativeLayout
Step 2 – After installing JDK, now it’s the time for you to setup environment variables. For LinearLayout
this procedure, right click This PC (My Computer) -> Properties -> Advanced System Collection widgets are similar to information widgets in that they display information,
however, the difference is that collection widgets display an aggregate of a bunch of We can adjust views and widgets We can adjust views and widgets according
Settings -> Environment Variables -> New.
different sources; such as news article titles, galleries of images, or other lists comprised linearly i.e. Horizontally and to one’s satisfaction.
Step 3 – Now download the latest android studio and install in your system.
of multiple sources. Generally, this lets the user do two things: browse a selection of vertically.
Step 4: Download the android emulator from android studio to run the program
items, and select one to look at more closely. layout_weight attribute in the linear Various attributes like: layout_toRightOf,
layout is used to specify the equal layout_toLeftOf, layout_below,
The View Hierarchy with example: Control widgets give simple access to basic and essential features of an existing app. or specific size to the particular layout_alignParentTop, layout_top,
Your widgets exist in a hierarchy of View objects called the view hierarchy. To demonstrate They’re sort of like remote controls – they offer control over a part of the app’s function widget and view by using the layout_alignParentLeft,
view hierarchy now I am going to create another layout file named as “second.xml” which that you can access without opening the app. For example, a control widget could turn on following attribute. layout_alignParentRight are used to specify
contains the following widgets: or off phone settings such as Bluetooth, WI-Fi and screen brightness, without having to android:layout_weight = ‘0’ the position of each view and widget.
1. a vertical LinearLayout go into the settings. Control widgets can also feature a detailed view of something, such Here Weight is specified as 0 in
2. a TextView as a search result or a data set. order to give equal size or space to
3. a horizontal LinearLayout each view or widget.
4. two Buttons It is useful when we arrange views It is useful when we arrange views in a
in a linear fashion relative fashion.
Syntax: Syntax:
<LinearLayout> <RelativeLayout>
<!–Views, widgets–> <!–Views, Widgets–>
</LinearLayout> </RelativeLayout>
LinearLayout is less used as RelativeLayout is used more in
compared to RelativeLayout. applications.
We can use LinearLayout inside We can also use RelativeLayout as a Child
RelativeLayout. of LinearLayout.`
android:layout_height="match_parent">
<TextView SecondActivity.java
android:layout_width="wrap_content" public class SecondActivity extends Activity {
android:layout_height="wrap_content" @Override
android:text="Label 1" protected void onCreate(Bundle b){
android:id="@+id/label1" super.onCreate(b);
android:textSize="20sp"/> setContentView(R.layout.second_activity);
<TextView //receiving data
android:layout_width="wrap_content" Intent i=getIntent();
android:layout_height="wrap_content" int id=i.getIntExtra("id",0);
android:text="Label 2" //second argument is default value
android:textSize="20sp" String name=i.getStringExtra("name");
android:id="@+id/label2" String
app:layout_constraintLeft_toRightOf="@+id/label1" address=i.getStringExtra("address");
app:layout_constraintTop_toBottomOf="@+id/label1" /> //Displaying received data in TextView Creating a UI Fragment with example
<TextView TextView txt=findViewById(R.id.text2);
android:layout_width="wrap_content" Fragment can be created in UI resource file as follows:
android:layout_height="wrap_content" txt.setText("Id="+id+"\n"+"Name="+name+"\n"+"Address="+ <fragment android:name="com.example.raazu.myapplication.Fragment1"
android:text="Label 3" address); android:id="@+id/headlines_fragment"
android:textSize="20sp" } android:layout_weight="1"
android:id="@+id/label3" } android:layout_width="0dp"
app:layout_constraintBottom_toTopOf="@+id/label2" android:layout_height="match_parent" />
app:layout_constraintLeft_toRightOf="@+id/label2" />
</android.support.constraint.ConstraintLayout> Creating a Fragment Class
following dependency in your build.gradle file. To create a fragment, extend the Fragment class, then override key lifecycle methods to
What do you mean by fragment? Explain lifecycle of fragment in detail.
implementation 'com.android.support.constraint:constraint-layout:1.1.3' insert your app logic, similar to the way you would with an Activity class. One difference
A Fragment represents a behaviour or a portion of user interface in FragmentActivity. You
when creating a Fragment is that you must use the onCreateView() callback to define the
can combine multiple fragments in a single activity to build a multi-pane UI and reuse a
layout. In fact, this is the only callback you need in order to get a fragment running. For
fragment in multiple activities. You can think of a fragment as a modular section of an
example, here's a simple fragment that specifies its own layout:
activity, which has its own lifecycle, receives its own input events, and which you can add
Event Handling in detail: or remove while the activity is running (sort of like a "sub activity" that you can reuse in
public class Fragment1 extends Fragment {
Events are a useful way to collect data about a user's interaction with interactive different activities).
@Override
components of Applications. Like button presses or screen touch etc. The Android
public View onCreateView(LayoutInflater inflater, ViewGroup
framework maintains an event queue as first-in, first-out (FIFO) basis.
container,Bundle savedInstanceState) {
There are following three concepts related to Android Event Management −
// Inflate the layout for this fragment
• Event Listeners − An event listener is an interface in the View class that contains a single
return inflater.inflate(R.layout.article_view, container,
callback method. These methods will be called by the Android framework when the View
false);
to which the listener has been registered is triggered by user interaction with the item in
}
the UI.
}
• Event Listeners Registration − Event Registration is the process by which an Event
Example of Fragment
Handler gets registered with an Event Listener so that the handler is called when the Event
Following example creates two fragments named as Fragment1 and Fragment2. After
Listener fires the event.
creating fragments, we will add these two fragments in activity named as FirstActivity and
display them.
• Event Handlers − When an event happens and we have registered an event listener for
the event, the event listener calls the Event Handlers, which is the method that actually
fragment1.xml
handles the event.
<?xml version="1.0" encoding="utf-8"?>
Examples:
<LinearLayout
onClick(),onLongClick(),onTouch() etc
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
What do you mean by android activity? Explain android activity life cycle in detail.
android:background="#AEB6BF"
Every instance of Activity has a lifecycle. During this lifecycle, an activity transitions
android:layout_width="match_parent"
between three possible states: running, paused, and stopped. For each transition, there is
android:layout_height="match_parent">
an activity method that notifies the activity of the change in its state. As a user navigates
<TextView
through, out of, and back to your app, the Activity instances in your app transition through
android:layout_width="wrap_content"
different states in their lifecycle. The Activity class provides a number of callbacks that
android:layout_height="wrap_content"
allow the activity to know that a state has changed: that the system is creating, stopping,
android:text="I am inside Fragment 1"
or resuming an activity, or destroying the process in which the activity resides.
android:layout_gravity="center"
Let's see the 7 lifecycle methods of android activity.
android:textSize="20sp"
onCreate called when activity is first created.
android:layout_marginTop="20sp"
onStart called when activity is becoming visible to the user.
android:textStyle="bold"
onResume called when activity will start interacting with the user.
</linearlayout>
onPause called when activity is not visible to the user.
Method Description
onStop called when activity is no longer visible to the user.
fragment2.xml
onRestart called after your activity is stopped, prior to start.
onAttach(Activity) it is called only once when it is attached <?xml version="1.0" encoding="utf-8"?>
onDestroy called before the activity is destroyed.
with activity. <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
onCreate(Bundle) It is used to initialize the fragment.
android:orientation="vertical"
onCreateView(LayoutInfl creates and returns view hierarchy. android:background="#D0ECE7"
ater, ViewGroup, Bundle) android:layout_width="match_parent"
android:layout_height="match_parent">
onActivityCreated(Bundle It is invoked after the completion of
<TextView
) onCreate() method.
android:layout_width="wrap_content"
onViewStateRestored(Bu It provides information to the fragment android:layout_height="wrap_content"
ndle) that all the saved state of fragment view android:text="I am inside Fragment 2"
hierarchy has been restored. android:layout_gravity="center"
onStart() makes the fragment visible. android:textSize="20sp"
android:layout_marginTop="20sp"
onResume() makes the fragment interactive. android:textStyle="bold" />
</LinearLayout>
onPause() is called when fragment is no longer
interactive. Fragment1.java
onStop() is called when fragment is no longer visible. public class Fragment1 extends Fragment {
@Override
onDestroyView() allows the fragment to clean up resources. public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
onDestroy() allows the fragment to do final clean up of // Inflate the layout for this fragment
fragment state. View view= inflater.inflate(R.layout.fragment1, container,
onDetach() It is called immediately prior to the false);
fragment no longer being associated with return view;
Passing Data Between Activities its activity. }
Between activities data can be passed and received by using Intent extras. Extras are }
arbitrary data that the calling activity can include with an intent. The OS forwards the
intent to the recipient activity, which can then access the extra and retrieve the data. An Fragment2.java
extra is structured as a key-value pair. To add an extra to an intent, you use The Need for UI Flexibility public class Fragment2 extends Fragment {
Intent.putExtra(...). In particular, you will be calling public Intent putExtra(String name, Android introduced fragments in Android 3.0 (API level 11), primarily to support more @Override
boolean value) dynamic and flexible UI designs on large screens, such as tablets. Because a tablet's screen public View onCreateView(LayoutInflater inflater,
Intent.putExtra(...) comes in many flavors, but it always has two arguments. The first is much larger than that of a handset, there's more room to combine and interchange UI ViewGroup
argument is always a String key, and the second argument is the value, whose type will components. Fragments allow such designs without the need for you to manage complex container, Bundle savedInstanceState) {
vary. Suppose if we want to pass data like id, name and address of student from changes to the view hierarchy. By dividing the layout of an activity into fragments, you // Inflate the layout for this fragment
FirstActivity to SecondActivity then we can use Intent extras as follows: become able to modify the activity's appearance at runtime and preserve those changes View view= inflater.inflate(R.layout.fragment2,
in a back stack that's managed by the activity. container,
FirstActivity.java You should design each fragment as a modular and reusable activity component. That is, false);
public class FirstActivity extends Activity { because each fragment defines its own layout and its own behavior with its own lifecycle return view;
@Override callbacks, you can include one fragment in multiple activities, so you should design for }
protected void onCreate(Bundle savedInstanceState) { reuse and avoid directly manipulating one fragment from another fragment. This is }
super.onCreate(savedInstanceState); especially important because a modular fragment allows you to change your fragment
setContentView(R.layout.first_activity); combinations for different screen sizes. When designing your application to support both
Button btn=findViewById(R.id.button1); tablets and handsets, you can reuse your fragments in different layout configurations to What do you mean by menu? Explain its types.
btn.setOnClickListener(new View.OnClickListener() { optimize the user experience based on the available screen space. For example, on a
@Override handset, it might be necessary to separate fragments to provide a single-pane UI when
public void onClick(View view) { more than one cannot fit within the same activity.
Intent i=new Intent(FirstActivity.this,
SecondActivity.class);
//passing data using putExtra
i.putExtra("id",001);
i.putExtra("name","Ram");
i.putExtra("address","KTM");
startActivity(i);
} }); }
}
Menus are a common user interface component in
many types of applications. To provide a familiar and listview_example.xml
consistent user experience, you can use the Menu to <?xml version="1.0" encoding="utf-8"?>
present user actions and other options in your <RelativeLayout
activities. xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
Types of Menu android:layout_height="match_parent">
They are options menu, contextual <ListView
menu and popup menu. android:layout_width="match_parent"
android:id="@+id/mylist"
Options Menu android:layout_height="match_parent" />
The options menu is the primary collection of menu </RelativeLayout>
items for an activity. It's where you listview_items.xml
should place actions that have a global impact on the <?xml version="1.0" encoding="utf-8"?>
app, such as "Search," "Compose email," and <RelativeLayout
"Settings." Menu shown in above diagram is an xmlns:android="http://schemas.android.com/apk/res/android"
example of options menu. android:layout_width="match_parent"
android:layout_height="match_parent">
Context Menu <TextView
Android context menu appears when user press long clicks on the element. It is also known android:layout_width="match_parent"
as floating menu. It affects the selected content while doing action on it. It doesn't support android:layout_height="wrap_content"
item shortcuts and icons. android:textSize="20sp"
android:id="@+id/text"
Popup Menu android:textStyle="bold" =============================================================
A popup menu displays a list of items in a vertical list that's anchored to the view that android:layout_margin="10dp" /> Hello World in ios
invoked the menu. It's good for providing an overflow of actions that relate to specific </RelativeLayout> import UIKit
content or to provide options for a second part of a command. Actions in a popup menu class ViewController: UIViewController {
should not directly affect the corresponding content—that's what contextual actions are Now we are creating a java file to for displaying String array in a ListView. @IBOutlet var displayLabel: UILabel!
for. Rather, the popup menu is for extended actions that relate to regions of content in ListViewExample.java @IBAction func saySomethingTapped(_ sender: UIButton) {
your activity. public class ListViewExample extends AppCompatActivity { displayLabel.text = "Hello World!"
ListView listView; }
@Override }
Dialogs and its types:
protected void onCreate(Bundle b){
A dialog is a small window that prompts the user to make a decision or enter additional
super.onCreate(b); RecyclerView
information. A dialog does not fill the screen and is normally used for modal events that
setContentView(R.layout.listview_example); The RecyclerView widget is a more advanced and flexible version of ListView. If your app
require users to take an action before they can proceed.
listView=findViewById(R.id.mylist); needs to display a scrolling list of elements based on large data sets (or data that
//creating string array frequently changes), you should use RecyclerView. RecyclerView is mostly used to design
String names[]= the user interface with the fine-grain control over the lists and grids of android
{"Ram","Shyam","Hari","Sita","Gita","Rita"}; application. It was introduced in Marshmallow.
//displaying list using ArrayAdapter
ArrayAdapter<String> adapter=new ArrayAdapter<String> Features of RecyclerView
(this,R.layout.listview_items,R.id.text,names); 1.RecyclerView widget is a more advanced and flexible version of ListView. So, we
listView.setAdapter(adapter); 2.can use RecyclerView to display large dataset.
} 3.RecyclerView contains integrated animations for adding, updating and removing
} items.
Following are the different types of dialogs: GridView 4.RecyclerView enforces the recycling of views by using the ViewHolder pattern.
AlertDialog Android GridView shows items in two-dimensional 5.RecyclerView supports both grids and lists.
• A dialog that can show a title, up to three buttons, a list of selectable items, or a custom scrolling grid (rows & columns). The items in the grid 6.RecyclerView supports vertical and horizontal scrolling.
layout. come from the ListAdapter associated with this view.

DatePickerDialog or TimePickerDialog Features of GridView


• A dialog with a pre-defined UI that allows the user to select a date or time. 1.GridView displays items in two-dimensional
scrolling grid.
Custom Dialog 2.GridView uses Adapter classes which add the
• A custom dialog built by programmer as per the requirement. content from data source (such as string array, array,
database etc.)
3.GridView is a default scrollable which does not use
other scroll view.
4.GridView is implemented by importing
Activity Fragment android.widget.GridView class.

gridview_example.xml
<?xml version="1.0" encoding="utf-8"?>
Activity is an application component <RelativeLayout
that gives a user interface where the The fragment is only part of an activity, it xmlns:android="http://schemas.android.com/apk/res/android" SQLIte and it’s features
user can interact. basically contributes its UI to that activity. android:layout_width="match_parent" SQLite is an open-source relational database i.e. used to perform database operations on
android:layout_height="match_parent"> android devices such as storing, manipulating or retrieving persistent data from the
<GridView database. It is very lightweight database that comes with Android OS. It supports all the
android:layout_width="match_parent" relational database features. In order to access this database, you don't need to establish
android:id="@+id/mygrid" any kind of connections for it like JDBC, ODBC etc.
android:numColumns="3" Features of SQLite:
Fragment is dependent on activity. It can’t android:layout_height="match_parent" /> Following is a list of features which makes SQLite popular among other lightweight
Activity is not dependent on fragment exist independently. </RelativeLayout> databases:
gridview_items.xml 1.SQLite is totally free: SQLite is open-source. So, no license is required to work with it.
<?xml version="1.0" encoding="utf-8"?> 2.SQLite is server less: SQLite doesn't require a different server process or system to
<RelativeLayout operate.
xmlns:android="http://schemas.android.com/apk/res/android" 3.SQLite is very flexible: It facilitates you to work on multiple databases on the same
we need to mention all activity it in Fragment is not required to mention android:layout_width="match_parent" session on the same time.
the manifest.xml file in the manifest file android:layout_height="match_parent"> 4.Configuration Not Required: SQLite doesn't require configuration. No setup or
<TextView administration required.
android:layout_width="match_parent" 5.SQLite is a cross-platform DBMS: You don't need a large range of different platforms
android:layout_height="wrap_content" like Windows, Mac OS, Linux, and Unix. It can also be used on a lot of embedded
android:textSize="20sp" operating systems like Symbian, and Windows CE.
6.Storing data is easy: SQLite provides an efficient way to store data.
We can’t create multi-screen UI After using multiple fragments in a single android:id="@+id/text"
without using fragment in an activity, activity, we can create a multi-screen UI. android:textStyle="bold"
Introduction to iOS and iOS Programming
android:layout_margin="10dp" />
iOS (formerly iPhone OS) is a mobile operating system created and developed by Apple
</RelativeLayout>
Inc. exclusively for its hardware. It is the operating system that presently powers many of
Now we are creating a java file to for displaying String array in a GridView.
the company's mobile devices, including the iPhone, and iPod Touch; it also powered the
GridViewExample.java
iPad prior to the introduction of iPadOS in 2019. It is the second most popular mobile
Fragment cannot be used without an 1. public class GridViewExample extends AppCompatActivity { operating system globally after Android.
Activity can exist without a Fragment Activity. 2. GridView gridView;
3. @Override
iOS Platform
4. protected void onCreate(Bundle b){
The iOS SDK (Software Development Kit) allows for the development of mobile apps on
5. super.onCreate(b);
iOS. While originally developing iPhone prior to its unveiling in 2007, Apple's then-CEO
6. setContentView(R.layout.gridview_example);
While Using fragments in the project, the Steve Jobs did not intend to let third-party developers build native apps for iOS, instead
7. gridView =findViewById(R.id.mygrid);
Creating a project using only Activity project structure will be good and we can directing them to make web applications for the Safari web browser.
8. //creating string array
then it’s difficult to manage handle it easily. its apple integrated development environment (IDE). The Xcode editor is the primary
9. String names[]= development tool for any type of apple platforms like OSX Software’s, iPhones App, Mac,
10. {"Ram","Shyam","Hari","Sita","Gita"};
etc.
11. //displaying list using ArrayAdapter
12. ArrayAdapter<String> adapter=new ArrayAdapter<String>
13. (this,R.layout.gridview_items,R.id.text,names);
Lifecycle methods are hosted by OS. Lifecycle methods in fragments are hosted
14. gridView.setAdapter(adapter);
The activity has its own life cycle. by hosting the activity.
15. }
16. }
Above code produces following output:

ListView
Android ListView is a view which groups several items and display them in vertical
scrollable list. The list items are automatically inserted to the list using an Adapter that
pulls content from a source such as an array or database.

Features of ListView:
1. It displays a vertically-scrollable collection of views, where each view is
positioned
1. immediately below the previous view in the list.
2. ListView uses Adapter classes which add the content from data source
(such as string array, array, database etc.)
3. ListView is a default scrollable which does not use other scroll view.
4. ListView is implemented by importing android.widget.ListView class.
============================================================== 90. int e=a+d; 106. edtName=findViewById(R.id.edtName);
91. txt1.setText("Total Interest Is 107. radMale=findViewById(R.id.radMale);
:"+String.valueOf(d)); 108. radFemale=findViewById(R.id.radFemale);
92. txt2.setText("Total Amount is : 109. spProgram=findViewById(R.id.spProgram);
"+String.valueOf(e)); 110. btnSubmit=findViewById(R.id.btnSubmit);
111. txtResult=findViewById(R.id.txtResult);
} 112. btnSubmit.setOnClickListener(new View.OnClickListener() {
}); 113. @Override
} 114. public void onClick(View view) {
} 115. //getting data from edit text
116. String id=edtId.getText().toString();
Getting and Setting Data to/from Layout File 117. String name=edtName.getText().toString();
first_activity.xml 118. //getting data from radio button
1. <?xml version="1.0" 119. String gender="";
encoding="utf-8"?> 120. if(radMale.isChecked())
2. <RelativeLayout 121. gender="Male";
3. xmlns:android="http://schemas.android.com/apk/res/android" 122. else
4. android:layout_width="match_parent" 123. gender="Female";
5. android:layout_height="match_parent"> 124. //getting data from spinner
6. 125. String program=spProgram.getSelectedItem().toString();
7. <TextView 126. //displaying data in text view
8. android:layout_width="wrap_content" 127. txtResult.setText("Student Id="+id+"\n"+"Student Name="
9. android:layout_height="wrap_content" 128. +name+"\n"+"Gender="+gender+"\n"+"Program="+program);
10. android:text="Student Form" 129. }
11. android:textSize="20sp" 130. });
12. android:layout_centerHorizontal="true" 131. }
13. android:layout_marginTop="10dp" 132. }
14. android:id="@+id/txtForm" />
Calculate Simple Interest in Android App 15.
Activity_main.xml File 16. <EditText
1. <?xml version="1.0" encoding="utf-8"?> 17. android:layout_width="match_parent"
2. <LinearLayout 18. android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android" 19. android:layout_below="@+id/txtForm"
3. xmlns:app="http://schemas.android.com/apk/res-auto" 20. android:layout_margin="5dp"
4. xmlns:tools="http://schemas.android.com/tools" 21. android:hint="Enter Student Id"
5. android:layout_width="match_parent" 22. android:id="@+id/edtId" />
6. android:layout_height="match_parent" 23.
7. android:orientation="vertical" 24. <EditText
8. tools:context=".MainActivity"> 25. android:layout_width="match_parent"
9. <TextView 26. android:layout_height="wrap_content"
10. android:layout_width="fill_parent" 27. android:layout_below="@+id/edtId"
11. android:layout_height="wrap_content" 28. android:layout_margin="5dp"
12. android:text="SImple Calculator" 29. android:hint="Enter Student Name"
13. android:textAlignment="center" 30. android:id="@+id/edtName" />
14. android:textSize="30dp" /> 31.
Displaying Retrieved data in RecyclerView from remote server
15. <TextView 32. <TextView
1. json_example.xml
16. android:layout_width="fill_parent" 33. android:layout_width="wrap_content"
2. <?xml version="1.0" encoding="utf-8"?>
17. android:layout_height="wrap_content" 34. android:layout_height="wrap_content"
3. <RelativeLayout
18. android:text="------------------------------------------" 35. android:text="Gender:"
4. xmlns:android="http://schemas.android.com/apk/res/android"
19. android:textAlignment="center" 36. android:textSize="18sp"
5. android:layout_width="match_parent"
20. android:textSize="30dp" /> 37. android:id="@+id/txtGender"
6. android:layout_margin="5dp"
21. <EditText 38. android:layout_below="@+id/edtName"
7. android:layout_height="match_parent">
22. android:layout_width="fill_parent" 39. android:layout_marginLeft="10dp"
8. <android.support.v7.widget.RecyclerView
23. android:layout_height="wrap_content" 40. android:layout_margin="5dp" />
9. android:layout_width="match_parent"
24. android:hint="Enter Amount" 41. <RadioGroup
10. android:layout_height="wrap_content"
25. android:id="@+id/amt" 42. android:layout_width="match_parent"
11. android:id="@+id/recyclerview" />
26. android:textAlignment="center" 43. android:layout_height="wrap_content"
12. </RelativeLayout>
27. android:inputType="number"/> 44. android:layout_below="@+id/edtName"
28. <EditText 45. android:id="@+id/radGroup"
13. list_items.xml
29. android:layout_width="fill_parent"
14. <?xml version="1.0" encoding="utf-8"?>
30. android:layout_height="wrap_content" 46. android:orientation="horizontal"
15. <RelativeLayout
31. android:hint="Enter Interest Rate (In %)" 47. android:layout_toRightOf="@+id/txtGender">
16. xmlns:android="http://schemas.android.com/apk/res/android"
32. android:id="@+id/interest" 48. <RadioButton
17. android:layout_width="match_parent"
33. android:textAlignment="center" 49. android:layout_width="wrap_content"
18. android:id="@+id/relat"
34. android:inputType="number"/> 50. android:layout_height="wrap_content"
19. android:layout_height="wrap_content">
35. <EditText 51. android:text="Male"
20. <TextView
36. android:layout_width="fill_parent" 52. android:id="@+id/radMale" />
21. android:layout_width="wrap_content"
37. android:layout_height="wrap_content" 53.
22. android:layout_height="wrap_content"
38. android:hint="Enter Time (in Year)" 54. <RadioButton
23. android:textSize="20sp"
39. android:id="@+id/tim" 55. android:layout_width="wrap_content"
24. android:layout_margin="10dp"
40. android:textAlignment="center" 56. android:layout_height="wrap_content"
25. android:text="Id"
41. android:inputType="number" /> 57. android:text="Female"
26. android:textStyle="bold"
42. <Button 58. android:id="@+id/radFemale" />
27. android:id="@+id/txtId" />
43. android:layout_width="wrap_content" 59. </RadioGroup>
28. <TextView
44. android:layout_height="wrap_content" 60. <TextView
29. android:layout_width="wrap_content"
45. android:text="Calculate" 61. android:layout_width="wrap_content"
30. android:layout_height="wrap_content"
46. android:id="@+id/btn" /> 62. android:layout_height="wrap_content"
31. android:textSize="20sp"
47. <TextView 63. android:text="Program:"
32. android:id="@+id/txtName"
48. android:layout_width="fill_parent" 64. android:textSize="18sp"
33. android:textStyle="bold"
49. android:layout_height="wrap_content" 65. android:layout_below="@+id/radGroup"
34. android:layout_toRightOf="@+id/txtId"
50. android:id="@+id/txt1" 66. android:layout_margin="5dp"
35. android:layout_marginTop="10dp"
51. android:textSize="30dp" /> 67. android:id="@+id/txtProgram" />
36. android:text="Name" />
52. <TextView 68. <Spinner
37. <TextView
53. android:layout_width="fill_parent" 69. android:layout_width="wrap_content"
38. android:layout_width="wrap_content"
54. android:layout_height="wrap_content" 70. android:layout_height="wrap_content"
39. android:layout_height="wrap_content"
55. android:id="@+id/txt2" 71. android:entries="@array/programs"
40. android:textSize="20sp"
56. android:textSize="20dp" /> 72. android:layout_below="@+id/radGroup"
41. android:id="@+id/txtAddress"
57. </LinearLayout> 73. android:layout_toRightOf="@+id/txtProgram"
42. android:text="Address"
74. android:layout_marginTop="5dp"
43. android:layout_marginLeft="10dp"
58. MainActivity.Java File 75. android:id="@+id/spProgram" />
44. android:layout_below="@+id/txtName" />
59. package com.irawen.simpleinterest; 76. <Button
45. </RelativeLayout>
60. import android.support.v7.app.AppCompatActivity; 77. android:layout_width="wrap_content"
61. import android.os.Bundle; 78. android:layout_height="wrap_content"
46. DataModel.java
62. import android.view.View; 79. android:layout_below="@+id/txtProgram"
47. public class DataModel {
63. import android.widget.Button; 80. android:layout_marginTop="10dp"
48. private int id;
64. import android.widget.EditText; 81. android:text="Submit"
49. private String name;
65. import android.widget.TextView; 82. android:id="@+id/btnSubmit"
50. private String address;
66. public class MainActivity extends AppCompatActivity { 83. android:layout_centerHorizontal="true" />
51. public DataModel(int id, String name, String address){
67. @Override protected void onCreate(Bundle savedInstanceState) { 84. <TextView
52. this.id=id;
68. super.onCreate(savedInstanceState); 85. android:layout_width="wrap_content"
53. this.name=name;
69. setContentView(R.layout.activity_main); 86. android:layout_height="wrap_content"
54. this.address=address;
70. OnCLick(); 87. android:text="Result"
55. }
71. } 88. android:textSize="18sp"
56. public int getId(){
72. EditText amt,interest,time; 89. android:id="@+id/txtResult"
57. return id;
73. Button btn; 90. android:layout_below="@+id/btnSubmit"
58. }
74. TextView txt1,txt2; 91. android:layout_margin="5dp"
59. public String getName(){
75. public void OnCLick() 92. android:layout_centerHorizontal="true" />
60. return name;
76. { 93. </RelativeLayout>
61. }
77. amt=(EditText)findViewById(R.id.amt);
62. public String getAddress(){
78. interest=(EditText)findViewById(R.id.interest); 94. FirstActivity.java
63. return address;
79. time=(EditText)findViewById(R.id.tim); 95. public class FirstActivity extends Activity {
64. }
80. btn=(Button)findViewById(R.id.btn); 96. EditText edtId,edtName;
65. }
81. txt1=(TextView)findViewById(R.id.txt1); 97. RadioButton radMale,radFemale;
82. txt2=(TextView)findViewById(R.id.txt2); 98. Spinner spProgram;
66. RecyclerViewAdapter.java
83. btn.setOnClickListener(new View.OnClickListener() { 99. Button btnSubmit;
67. public class RecyclerViewAdapter extends
84. @Override public void onClick(View v) { 100. TextView txtResult;
68. RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
85. int a=Integer.parseInt(amt.getText().toString()); 101. @Override
69. Activity context;
86. int b=Integer.parseInt(interest.getText().toString()); 102. protected void onCreate(Bundle savedInstanceState) {
70. ArrayList<DataModel> data;
87. int c=Integer.parseInt(time.getText().toString()); 103. super.onCreate(savedInstanceState);
71. public RecyclerViewAdapter(Activity context, ArrayList<DataModel>
88. int d; 104. setContentView(R.layout.first_activity);
72. data){
89. d=(a*b*c)/100; 105. edtId=findViewById(R.id.edtId);
73. this.context=context;
74. this.data=data; 77. queue.add(stringRequest);
75. } 78. }}
76. @Override
77. public ViewHolder onCreateViewHolder(ViewGroup parent, int 79. setdata.php
viewType) 80. <?php //getting post data
78. { 81. $sid=$_POST["sid"];
79. LayoutInflater layoutInflater = LayoutInflater.from(context); 82. $name=$_POST["name"];
80. View listItem= layoutInflater.inflate(R.layout.list_items, 83. $address=$_POST["address"];
81. parent, false); //server credentials
82. ViewHolder viewHolder = new ViewHolder(listItem); 84. $server="localhost";
83. return viewHolder; 85. $username="root";
84. } 86. $password="";
85. @Override 87. $database="bcatest"; // Create
86. public void onBindViewHolder(ViewHolder holder, int position) { connection
87. final DataModel current=data.get(position); 88. $conn = new mysqli($server,
88. holder.txtId.setText(current.getId()+""); $username, $password,$database);
89. holder.txtName.setText(current.getName()); // Check connection
90. holder.txtAddress.setText(current.getAddress()); 89. if ($conn->connect_error) {
91. } 90. die("Connection failed: " . $conn-
92. @Override >connect_error);}
93. public int getItemCount() { 91. //inserting data
94. return data.size(); 92. $sql = "INSERT INTO student(sid,name,address)
95. } 93. VALUES('".$sid."','".$name."','".$address."')";
96. public static class ViewHolder extends RecyclerView.ViewHolder { 94. $result = $conn->query($sql);
97. TextView txtId,txtName,txtAddress; 95. if($result)
98. ImageView imageView; 96. echo"Data Inserted Successfully !";
99. public ViewHolder(View itemView) { 97. else
100. super(itemView); 98. echo"Failed to Insert Data !";
101. txtId = itemView.findViewById(R.id.txtId); 99. $conn->close();
102. txtName = itemView.findViewById(R.id.txtName); 100. ?
Sending Contents to Remote Server
103. txtAddress = itemView.findViewById(R.id.txtAddress); Crude operation using sql lite
1. send_data.xml
104. } <?xml version="1.0" encoding="utf-8"?>
2. <?xml version="1.0" encoding="utf-8"?>
105. } <RelativeLayout
3. <RelativeLayout
106. } xmlns:android="http://schemas.android.com/apk/res/android"
4. xmlns:android="http://schemas.android.com/apk/res/android"
107. android:layout_width="match_parent"
5. android:layout_width="match_parent"
108. JsonExample.java android:orientation="vertical"
6. android:orientation="vertical"
109. public class JsonExample extends AppCompatActivity{ android:layout_margin="5dp"
7. android:layout_margin="5dp"
110. RecyclerView recyclerView; android:layout_height="match_parent">
8. android:layout_height="match_parent">
111. RecyclerView.Adapter recyclerAdapter;
9. <EditText
112. RecyclerView.LayoutManager layoutManager; <EditText
10. android:layout_width="match_parent"
113. @Override android:layout_width="match_parent"
11. android:layout_height="wrap_content"
114. protected void onCreate(Bundle b){ android:layout_height="wrap_content"
12. android:hint="Enter Id"
115. super.onCreate(b); android:hint="Enter Id"
13. android:inputType="number"
116. setContentView(R.layout.json_example); android:inputType="number"
14. android:id="@+id/edtId" />
117. recyclerView=findViewById(R.id.recyclerview); android:id="@+id/edtId" />
15. <EditText
118. volleyRequest(); <EditText
16. android:layout_width="match_parent"
119. } android:layout_width="match_parent"
17. android:layout_height="wrap_content"
120. public void volleyRequest(){ android:layout_height="wrap_content"
18. android:hint="Enter Address"
121. // Instantiate the RequestQueue. android:hint="Enter Name"
19. android:layout_below="@+id/edtName"
122. RequestQueue queue = Volley.newRequestQueue(this); android:layout_below="@+id/edtId"
20. android:id="@+id/edtAddress" />
123. //url for localhost android:id="@+id/edtName" />
21. <Button
124. String url ="http://10.0.2.2/myproject/getdata.php"; <EditText
22. android:layout_width="wrap_content"
125. // Request a string response from the provided URL. android:layout_width="match_parent"
23. android:layout_height="wrap_content"
126. StringRequest stringRequest = new StringRequest android:layout_height="wrap_content"
24. android:layout_below="@+id/edtAddress"
127. (Request.Method.GET, url, android:hint="Enter Address"
25. android:id="@+id/btnSubmit"
128. new Response.Listener<String>() { android:layout_below="@+id/edtName"
26. android:layout_centerHorizontal="true"
129. @Override android:id="@+id/edtAddress" />
27. android:text="Submit" />
130. public void onResponse(String response) { <Button
28. </RelativeLayout>
131. //passing data for decoding android:layout_width="wrap_content"
132. decodeJson(response); android:layout_height="wrap_content"
29. SendData.java
133. } android:layout_below="@+id/edtAddress"
30. public class SendData extends AppCompatActivity {
134. }, new Response.ErrorListener() { android:id="@+id/btnInsert"
31. EditText edtId,edtName,edtAddress;
135. @Override android:text="Insert" />
32. Button btnSubmit;
136. public void onErrorResponse(VolleyError error) { <Button
33. @Override
137. //displaying error response message android:layout_width="wrap_content"
34. protected void onCreate(Bundle b){
138. Log.d("exception",error.toString()); android:layout_height="wrap_content"
35. super.onCreate(b);
139. } android:layout_below="@+id/edtAddress"
36. setContentView(R.layout.send_data);
140. }); android:layout_toRightOf="@+id/btnInsert"
37. edtId=findViewById(R.id.edtId);
141. // Add the request to the RequestQueue. android:id="@+id/btnSelect"
38. edtName=findViewById(R.id.edtName);
142. queue.add(stringRequest); android:layout_marginLeft="10dp"
39. edtAddress=findViewById(R.id.edtAddress);
143. } android:text="Select" />
40. btnSubmit=findViewById(R.id.btnSubmit);
144. public void decodeJson(String response){ <Button
41. btnSubmit.setOnClickListener(new View.OnClickListener() {
145. try{ android:layout_width="wrap_content"
42. @Override
146. ArrayList<DataModel> data=new ArrayList<>(); android:layout_height="wrap_content"
43. public void onClick(View view) {
147. JSONObject result=new JSONObject(response); android:layout_below="@+id/edtAddress"
44. volleyRequest();
148. JSONArray array=result.getJSONArray("data"); android:layout_toRightOf="@+id/btnSelect"
45. }});}
149. for(int i=0;i<array.length();i++){ android:id="@+id/btnUpdate"
46. public void volleyRequest(){
150. //fetching each row android:layout_marginLeft="10dp"
47. // Instantiate the RequestQueue.
151. JSONObject student=array.getJSONObject(i); android:text="Update" />
48. RequestQueue queue = Volley.newRequestQueue(this);
152. int sid=student.getInt("sid"); <Button
49. //url for localhost
153. String name=student.getString("name"); android:layout_width="wrap_content"
50. String url ="http://10.0.2.2/myproject/setdata.php";
154. String address=student.getString("address"); android:layout_height="wrap_content"
51. // Request a string response from the provided URL.
155. DataModel dataModel=new DataModel(sid,name,address); android:layout_below="@+id/edtAddress"
52. StringRequest stringRequest = new StringRequest
156. data.add(dataModel); android:layout_toRightOf="@+id/btnUpdate"
53. (Request.Method.POST, url,
157. } android:id="@+id/btnDelete"
54. new Response.Listener<String>() {
158. //plotting data in recyclerview android:layout_marginLeft="10dp"
55. @Override
159. layoutManager=new LinearLayoutManager(this); android:text="Delete" />
56. public void onResponse(String response) {
160. recyclerView.setLayoutManager(layoutManager); <TextView
57. //displaying response message
161. recyclerAdapter=new RecyclerViewAdapter android:layout_width="match_parent"
58. Toast.makeText(getApplicationContext(),response,
162. (JsonExample.this,data); android:layout_height="wrap_content"
59. Toast.LENGTH_LONG).show();
163. recyclerView.setAdapter(recyclerAdapter); android:text="Selected Data:"
60. }
164. }catch (Exception ex){ android:layout_below="@+id/btnSelect"
61. }, new Response.ErrorListener() {
165. Log.d("exception",ex.toString());
62. @Override
166. }
63. public void onErrorResponse(VolleyError error) {
167. } android:layout_marginTop="10dp"
64. //displaying error response message
168. } android:id="@+id/txtData"
65. Log.d("exception",error.toString());
android:textSize="18sp" />
66. }}){
</RelativeLayout>
67. //sending data to server
68. @Override
Now we are creating Helper class for SQLite operations by extending
69. protected HashMap<String,String> getParams(){
SQLiteOpenHelpter
70. HashMap<String,String> params = new HashMap<>();
as follows:
71. params.put("sid",edtId.getText().toString());
public class MyDbHelper extends SQLiteOpenHelper{
72. params.put("name",edtName.getText().toString());
// Database Version
73. params.put("address",edtAddress.getText().toString());
private static final int DATABASE_VERSION = 1;
74. return params;
// Database Name
75. }};;
private static final String DATABASE_NAME = "mydb";
76. // Add the request to the RequestQueue.
public MyDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
// create notes table
String createQuery="CREATE TABLE mytable(id INTEGER PRIMARY

KEY,name TEXT, address TEXT)";

db.execSQL(createQuery);
}
// Upgrading database
@Override An API key is needed to access the Google Maps servers. This key is free
public void onUpgrade(SQLiteDatabase db, int oldVersion, int and you can useit with any of your applications. If you haven’t created
newVersion) { project, you can follow the belowsteps to get started:
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME); Step 1: Open Google developer console and sign in with your Gmail
// Create tables again account: https://console.developers.google.com/project
onCreate(db);
} Step 2: Now create new project. You can create new project by clicking
//code to insert data on the Create Project button and give name to your project.
public void insertData(int id,String name, String address){
SQLiteDatabase db = this.getWritableDatabase(); Step 3: Now click on APIs & Services and open Dashboard from it.
ContentValues contentValues=new ContentValues();
contentValues.put("id",id); Step 4: Now click Enable APIS AND SERICES.
contentValues.put("name",name);
contentValues.put("address",address); Step 5: Now search for Google Map Android API and enable it.
//inserting row
db.insert("mytable",null,contentValues); Step 6: Now refresh page and go to Credentials.
db.close();
} Step 7: Now click on Create credentials and choose API key. It will create
//code to select data API key to integrate maps in your application.
public Cursor selectData(){
SQLiteDatabase db=this.getReadableDatabase(); Step 8: Now API your API key will be generated. Copy it and save it
String query="SELECT * FROM mytable"; somewhere as we will
Cursor cursor=db.rawQuery(query,null); need it when implementing Google Map in our Android project.
return cursor;
} Developing Google Maps Application in Android
//code to update data Following are the steps for integrating google maps in your application:
public void updateData(String id,String name, String address){
SQLiteDatabase db = this.getWritableDatabase(); Step 1: Add following permission in your manifest file.
ContentValues contentValues=new ContentValues(); <uses-permission
contentValues.put("name",name); android:name="android.permission.ACCESS_FINE_LOCATION"/>
contentValues.put("address",address);
//updating row Step 2: Add your generated API Key in your manifest file inside
db.update("mytable",contentValues,"id=?",new String[]{id}); application tag as follows.
db.close();} <meta-data
//code to delete data android:name="com.google.android.geo.API_KEY"
public void deleteData(String id) { android:value="AIzaSyCWIdlyqlFhC7lOthG164H42heV1F7N3v0" />
SQLiteDatabase db = this.getWritableDatabase();
//deleting row Step 3: Add following dependency in build.gradle file .
db.delete("mytable","id=?",new String[]{id}); dependencies {
}} implementation 'com.google.android.gms:play-services-maps:15.0.1'
Now finally we are creating Activity named as “SqliteExample.java” to }
perform various
data manipulation operations: Step 4: Now create layout resource file to display google map.
public class SqliteExample extends AppCompatActivity { map_activity.xml
EditText edtId,edtName,edtAddress; <?xml version="1.0" encoding="utf-8"?>
Button btnInsert,btnSelect,btnUpdate,btnDelete; <RelativeLayout
TextView txtData; xmlns:android="http://schemas.android.com/apk/res/android"
MyDbHelper myDbHelper; android:layout_width="match_parent"
@Override android:layout_height="match_parent"
protected void onCreate(Bundle b){ xmlns:tools="http://schemas.android.com/tools">
super.onCreate(b); <fragment
setContentView(R.layout.sqlite_example); xmlns:android="http://schemas.android.com/apk/res/android"
//creating object of MyDbHelper class android:id="@+id/map"
myDbHelper=new MyDbHelper(this); android:name="com.google.android.gms.maps.SupportMapFragment"
edtId=findViewById(R.id.edtId); tools:context=".MapsActivity"
edtName=findViewById(R.id.edtName); android:layout_width="match_parent"
edtAddress=findViewById(R.id.edtAddress); android:layout_height="match_parent" />
btnInsert=findViewById(R.id.btnInsert); </RelativeLayout>
btnUpdate=findViewById(R.id.btnUpdate);
btnSelect=findViewById(R.id.btnSelect); Step 5: Now finally create an Activity by implementing
btnDelete=findViewById(R.id.btnDelete); OnMapReadyCallback interface.
txtData=findViewById(R.id.txtData); MapsActivity.java
btnInsert.setOnClickListener(new View.OnClickListener() { public class MapsActivity extends AppCompatActivity implement
@Override OnMapReadyCallback {
public void onClick(View view) { GoogleMap mMap;
int id=Integer.parseInt(edtId.getText().toString()); @Override
String name=edtName.getText().toString(); protected void onCreate(Bundle b){
String address=edtAddress.getText().toString(); super.onCreate(b);
//calling insert function setContentView(R.layout.map_activity);
myDbHelper.insertData(id,name,address); // Obtain the SupportMapFragment and get notified when the map is
Toast.makeText(getApplicationContext(),"Data Inserted ready to be used.
Successfully !", Toast.LENGTH_SHORT).show(); SupportMapFragment mapFragment =
}}); (SupportMapFragment).getSupportFragmentManager().findFragmentB
btnSelect.setOnClickListener(new View.OnClickListener() { yId(R.id.map);
@Override mapFragment.getMapAsync(this);
public void onClick(View view) { }
//retrieving data @Override
int id=0; public void onMapReady(GoogleMap googleMap) {
String name="",address=""; mMap = googleMap;
//calling select function // Adding latitude and longitude
Cursor cursor=myDbHelper.selectData(); LatLng location = new LatLng(26.644096, 87.989391);
while (cursor.moveToNext()){ //Adding red marker to point location
id=cursor.getInt(0); mMap.addMarker(new MarkerOptions().position(location).
name=cursor.getString(1); title("Marker in Birtamode"));
address=cursor.getString(2); //Moving camera to desired location
} mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
//displaying data in TextView //Adding zoom effect
txtData.setText("Id="+id+"\t Name="+name+"\tAddress=" mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f) );
+address); }
}}); }
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
String name=edtName.getText().toString();
String address=edtAddress.getText().toString();
//calling insert function
myDbHelper.updateData(id,name,address);
Toast.makeText(getApplicationContext(),"Data Updated
Successfully !",Toast.LENGTH_SHORT).show();
}});
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String id=edtId.getText().toString();
//calling delete function
myDbHelper.deleteData(id);
Toast.makeText(getApplicationContext(),"Data Deleted
Successfully !",Toast.LENGTH_SHORT).show();
}});}}

Steps for Getting Google Maps API Key and map program.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy