UNIT 2 Mobile Application Development-1
UNIT 2 Mobile Application Development-1
android:id
1
This is the ID which uniquely identifies the view.
android:layout_width
2
This is the width of the layout.
android:layout_height
3
This is the height of the layout
android:layout_marginTop
4
This is the extra space on the top side of the layout.
android:layout_marginBottom
5
This is the extra space on the bottom side of the layout.
android:layout_marginLeft
6
This is the extra space on the left side of the layout.
android:layout_marginRight
7
This is the extra space on the right side of the layout.
android:layout_gravity
8 This specifies how child Views are positioned from top bottom left and write
from the window
android:layout_weight
9 This specifies how much of the extra space in the layout should be allocated
to the View.It distributes the available space among the child views
android:layout_x
10
This specifies the x-coordinate of the layout.
android:layout_y
11
This specifies the y-coordinate of the layout.
android:layout_width
12
This is the width of the layout.
android:paddingLeft
13
This is the left padding filled for the layout.
android:paddingRight
14
This is the right padding filled for the layout.
android:paddingTop
15
This is the top padding filled for the layout.
android:paddingBottom
16
This is the bottom padding filled for the layout.
o ConstraintLayout
o FrameLayout
o LinearLayout (Horizontal) and LinearLayout (Vertical)
o TableLayout
o RelativeLayout
o ScrollView
o Grid view
ConstraintLayout
ConstraintLayout is a ViewGroup subclass,Whenever you open the android
studio framework the application will be present in the constraint layout.
In this we have to set the constraint in all four sides.
This is the default layout.
Framelayout
FrameLayout is a ViewGroup subclass, The FrameLayout is the most basic of the
Android layouts. FrameLayouts are built to hold one view.
You can add multiple views to a FrameLayout, but each is stacked on top of the
previous one. This is when you want to animate a series of images, with only one
visible at a time.
Linearlayout (horizontal) and linearlayout (Vertical)
LinearLayout is a ViewGroup subclass,The LinearLayout arranges views in a
single column or a single row. Child views can be arranged either horizontally or
vertically, which explains the need for two different layouts—one for horizontal
rows of views and one for vertical columns of views.
LinearLayout(Horizontal) and LinearLayout(Vertical)
the android:orientation property of the LinearLayout controls if the application has
a horizontal or vertical flow.
Tablelayout
TableLayout is a ViewGroup subclass,The TableLayout Layout groups views into
rows and columns. You use the <TableRow> element to designate a row in the
table. Each row can contain one or more views.
Each view you place within a row forms a cell. The width of each column is
determined by the largest width of each cell in that column.
Relativelayout
RelativeLayout is a ViewGroup subclass,The RelativeLayout layout enables you
to specify how child views are positioned relative to each other.
each view embedded within the RelativeLayout has attributes that enable it to
align with another view.
These attributes are as follows:
layout_alignParentTop
layout_alignParentStart
layout_alignStart
layout_alignEnd
layout_below
layout_centerHorizontal
ScrollView
A ScrollView is a special type of FrameLayout in that it enables users to scroll
through a list of views that occupy more space than the physical display.
The ScrollView can contain only one child view or ViewGroup, which normally is a
LinearLayout.
GridView
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.
ListView
ListView is a view group that displays a list of scrollable items.
These attributes are important for controlling the layout and appearance of views within
your Android app's user interface.
attribute description
layout_width Specifies the width of the view or ViewGroup
layout_height Specifies the height of the view or ViewGroup
Specifies extra space on the top side of the view or
layout_marginTop
ViewGroup
Specifies extra space on the bottom side of the view or
layout_marginBottom
ViewGroup
Specifies extra space on the left side of the view or
layout_marginLeft
ViewGroup
Specifies extra space on the right side of the view or
layout_marginRight
ViewGroup
layout_gravity Specifies how child views are positioned
Specifies how much of the extra space in the layout
layout_weight
should be allocated to the view
layout_x Specifies the x-coordinate of the view or ViewGroup
layout_y Specifies the y-coordinate of the view or ViewGroup
Adapting to Display Orientation
One of the key features of modern smartphones is their ability to switch screen
orientation, and Android is no exception.
Android supports two screen orientations: portrait and landscape.
By default, when you change the display orientation of your Android device, the
current activity automatically redraws its content in the new orientation.
This is because the onCreate() method of the activity is fired whenever there is a
change in display orientation.
Note: When you change the orientation of your Android device, your current
activity is actually destroyed and then re-created.
when the views are redrawn, they may be drawn in their original locations
(depending on the layout selected).
In general, you can employ two techniques to handle changes in screen orientation:
Anchoring—The easiest way is to “anchor” your views to the four edges of the
screen. When the screen orientation changes, the views can anchor neatly to the
edges.
Resizing and repositioning—Whereas anchoring and centralizing are simple
techniques to ensure that views can handle changes in screen orientation, the
ultimate technique is resizing each and every view according to the current screen
orientation
Managing Changes to screen orientation
Creating an application that displays message base on the screen orientation
Create a Project
App manifests
AndroidManifest.xml
Inside <activity>
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize" //INCLUDE THIS
LINE
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Inside MainActivity.java
\\Enter Ctrl+O select onConfigurationChanged
The following will be displayed
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
\\ Include the code which is in BOLD
If (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast
toast=Toast.makeText(this,"orientation_landscape",Toast.LENGTH_SHORT);
toast.show();
}
else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast toast=Toast.makeText(this,"orientation_Portrait",Toast.LENGTH_SHORT);
toast.show();
}
}
RUN THE PROGRAM
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name="com.codepath.example.simpleapp.FirstActivity"
android:label="@string/activity_name" >
</activity>
</application>
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
Entries in the action bar are typically called actions. Use this method to inflate a menu
resource that defines all the action items within a res/menu/menu_main.xml file, for
example:
You also should note that the xmlns:app namespace must be defined in order to
leverage the showAsAction option. The reason is that a compatibility library is used to
support the showAsAction="ifRoom" option. This option is needed to show the item
directly in the action bar as an icon. If there's not enough room for the item in the action
bar, it will appear in the action overflow. If withText is specified as well (as in the second
item), the text will be displayed with the icon.
5. *Set Content View*: If you created the layout container programmatically, set it
as the content view of your activity using the setContentView() method.
1. Using Android Studio, create a new Android project and name it UICode.
2. In the MainActivity.java file, add the bold statements in the following code:
//---create a layout---
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
//---create a text view---
//---create a button---
layout.addView(tv);
How It Works
In this example, you first commented out the setContentView() statement so that it does
not load the UI from the activity_main.xml file.
You then created a LayoutParams object to specify the layout parameter that can be
used by other views (which you will create next):
//---create a layout param for the layout---
LinearLayoutCompat.LayoutParams layoutParam = new
LinearLayoutCompat.LayoutParams(
LinearLayoutCompat.LayoutParams.WRAP_CONTENT,
LinearLayoutCompat.LayoutParams.WRAP_CONTENT );
You also created a LinearLayout object to contain all the views in your activity:
//---create a layout---
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
Next, you created a TextView and a Button view:
//---create a textview---
TextView tv = new TextView(this);
tv.setText("This is a TextView"); tv.setLayoutParams(params);
//---create a button---
INTRODUCTION
There are two levels of Android user interface with which users interact and they are as
follows:
1. Activity level
2. View level
ACTIVITY LEVEL
At activity level, there are certain methods in Activity class which we can override. Some
of the genuine methods are as follow:
It's often used to detect when a user releases a key on a hardware keyboard or a
software keyboard on the screen. This method is useful for handling input from keyboard
events, such as responding to specific keys being pressed or released.
• onKeyUp(): This is called when a key was released. This is not handled by any of
the views inside the activity.
• onKeyDown(): This is called when a key was pressed. This is not handled by any
of the views inside the activity.
• onMenuItemSelected(): This is called when any item of the menu panel is
pressed by user.
• onMenuOpened(): This method is called when user opens the panel’s menu.
VIEW LEVEL
When any user interacts with a view, the corresponding view fires event.
When a user touches a button or an image button or any such view we have to
service the related service so that appropriate action can be performed.
For this, events need to be registered. For a button we will have code like this:
➤➤Basic views—Commonly used views, such as the TextView, EditText, and Button
views.
➤➤ Picker views—Views that enable users to select from a list, such as the TimePicker
and DatePicker views.
➤➤ List views—Views that display a long list of items, such as the ListView and the
SpinnerView views.
➤➤ Specialized fragments—Special fragments that perform specific functions.
Using Basic Views
These basic views enable you to display text information, as well as perform some
basic selection.
View class extends Object class and implements Drawable.Callback,
KeyEvent.Callback and AccessibilityEventSource.
match_parent means it will occupy the complete space available on the display of
the device. Whereas, wrap_content means it will occupy only that much space as
required for its content to display.
TextView View
When you create a new Android project, Android Studio always creates the
activity_main.xml file(located in the res/layout folder), which contains a <TextView>
element:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>
You use the TextView view to display text to the user. This is the most basic view and
one that you will frequently use when you develop Android applications. If you need to
allow users to edit the text displayed, you should use the subclass of TextView—
EditText.
Timepicker View
The TimePicker view enables users to select a time of the day, in either 24-
hour mode or AM/PM mode. The following Try It Out shows you how to use
the TimePicker in the latest version of the Android SDK.
When you are creating the project for this sample, be sure that you choose
an SDK that is level 23 or greater.
The android.widget.DatePicker is the subclass of FrameLayout class.
Using the timepicker View
3. Press Shift+F9 to debug the application on the Android emulator. Figure 5-8
shows the TimePicker in action. You can use the numeric keypad or the
time widget on the screen to change the hour and minute.
4. Back in Android Studio, add the following bolded statements to the
MainActivity.java file:
5. Press Shift+F9 to debug the application on the Android emulator. This time,
the TimePicker is displayed in the 24-hour format. Clicking the Button displays
the time that you have set in the TimePicker
How It Works
The TimePicker displays a standard UI to enable users to set a time. By
default, it displays the time in the AM/PM format.
If you want to display the time in the 24-hour format, you can use
the setIs24HourView() method.
Datepicker View
Another view that is similar to the TimePicker is the DatePicker. Using the
DatePicker, you can enable users to select a particular date on the activity. The following
Try It Out shows you how to use the DatePicker.
Using the Datepicker View
ListView Attributes
1 android:id
This is the ID which uniquely identifies the layout.
2 android:divider
This is drawable or color to draw between list items.
android:dividerHeight
3 This specifies height of the divider. This could be in px, dp, sp,
in, or mm.
android:entries
4 Specifies the reference to an array resource that will populate
the ListView.
android:footerDividersEnabled
5 When set to false, the ListView will not draw the divider before
each footer view. The default value is true.
android:headerDividersEnabled
6 When set to false, the ListView will not draw the divider after
each header view. The default value is true.
In android commonly used adapters are:
1. Array Adapter
2. Base Adapter
1.Array Adapter:
Whenever you have a list of single items which is backed by an array, you can use
ArrayAdapter. For instance, list of phone contacts, countries or names.
2.Base Adapter:
Whenever you need a customized list you create your own adapter and extend base
adapter in that. Base Adapter can be extended to create a custom Adapter for displaying a
custom list item.
1. getCount():
The getCount() function returns the total number of items to be displayed in a list.
3. getItem(int i):
This function is used to Get the data item associated with the specified position in the data
set to obtain the corresponding data of the specific location in the collection of data items.
@Override
public Object getItem(int i) {
return arrayList.get(i);
}
4. getItemId(int i):
As for the getItemId (int position), it returns the corresponding to the position item ID. The
function returns a long value of item position to the adapter.
@Override
public long getItemId(int i) {
return i;
}
In Android, Spinner provides a quick way to select one value from a set of values.
Android spinners are nothing but the drop down-list. In a default state,
a spinner shows its currently selected value. It provides a easy way to select a value
from a list of values.
<Spinner
android:id="@+id/simpleSpinner "
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
Important Note: To fill the data in a spinner we need to implement an adapter class.
A spinner is mainly used to display only text field so we can implement Array
Adapter for that. We can also use Base Adapter and other custom adapters to
display a spinner with more customize list. Suppose if we need to display
a textview and a imageview in spinner item list then array adapter is not enough for
that. Here we have to implement custom adapter in our class. Below image of
Spinner and Custom Spinner will make it more clear.
Understanding specialized Fragments
As you have learned, fragments are really “mini-activities” that have their own life
cycles. To create a fragment, you need a class that extends the Fragment base
class. In addition to the Fragment base class, you can also extend from some
other subclasses of the Fragment base class to create more specialized
fragments. The following sections discuss the three subclasses of Fragment:
ListFragment
DialogFragment
PreferenceFragment
Using a ListFragment
8. Click any of the items in the two ListView views, and you see a message
Using a DialogFragment
2. Add a Java Class file under the package and name it Fragment1.
5. Press Shift+F9 to debug the application on the Android emulator. Figure 5-20 shows
the fragment displayed as an alert dialog. Click either OK or Cancel and observe the
message displayed.
Using a preferenceFragment
In your Android applications you provide preferences for users to
personalize the application.
For example, you might allow users to save the login credentials that they
use to access their web resources.
Also, you could save information, such as how often the feeds must be
refreshed and so on.
In the social media app, a PreferenceFragment could be used to display the
app's settings screen, These XML files define preferences such as
notification settings, privacy settings, theme preferences, etc.
In Android, you can use the PreferenceActivity base class to display an
activity for the user to edit the preferences. In Android 3.0 and later, you can
use the PreferenceFragment class to do the same thing.
In preferences there are different types of preferences which are listed
below :
o EditTextPreference: this is used to get the text from the user.
o ListPreference: this option is used to display a dialog with the list of
options to choose from.
o CheckBoxPreference: this option is used to display a checkbox to
toggle a setting.
o SwitchPreference: this option is used to turn the switch on and off.
o RingtonePreference: this option is used to open the ringtone page of
your device.
o Preference with an Intent action android.intent.action.VIEW – to open
an external browser navigating to an URL.
To create a list of preferences in your Android application, you first need to create the
preferences .xml file and populate it with the various XML elements. This XML file
defines the various items that you want to persist in your application.
To create the preference fragment, you must extend the PreferenceFragment base class:
public class Fragment1 extends PreferenceFragment {
}
To load the preferences file in the preference fragment, use the
addPreferencesFromResource() method:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//---load the preferences from an XML file---
addPreferencesFromResource(R.xml.preferences);
}
To display the preference fragment in your activity, you can make use of the
FragmentManager and the FragmentTransaction classes:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
Fragment1 fragment1 = new Fragment1();
fragmentTransaction.replace(android.R.id.content, fragment1);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
You need to add the preference fragment to the back stack using the addToBackStack()
method so that 11the user can dismiss the fragment by clicking the Back button.
ImageView in Android
ImageView class is used to display any kind of image resource in the android
application either it can
be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is
a general abstraction for anything that can be drawn in Android).
ImageView class or android.widget.ImageView inherits
the android.view.View class which is the subclass of Java.
Moreover, ImageView is also used to control the size and movement of an
image.
It can be done by adding an image file that is present in the Android Studio
itself or we can add our own image file.
Android Studio owns a wide range of drawable resources which are very
common in the android application layout.
The following are the steps to add a drawable resource to the ImageView
class.
1. Open the activity_main.xml File in which the Image is to be Added
2. Switch from the Code View to the Design View of the activity_main.xml File
3. For adding an image from Android Studio, Drag the ImageView widget to
the activity area of the application, a pop-up dialogue box will open choose
from the wide range of drawable resources and click “OK“.
For adding an image from Android Studio, Drag the ImageView widget to the
activity area of the application, a pop-up dialogue box will open choose from the
wide range of drawable resources and click “OK“.
Click on the “Resource Manager” tab on the leftmost panel and select the “Import
Drawables” option.
Select the path of the image file on your computer and click “OK“. After that set, the
“Qualifier type” and “value” of the image file according to your need and click
“Next” then “Import“.
Drag the ImageView class in the activity area, a pop-up dialogue box will appear
which contains your imported image file. Choose your image file and click “OK“,
your image will be added to the activity.
XML Attributes of ImageView
XML
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/GfG_full_logo"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.078"
app:srcCompat="@drawable/full_logo" />
<ImageView
android:id="@+id/GfG_logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/GfG_full_logo"
app:srcCompat="@drawable/logo" />
</androidx.constraintlayout.widget.ConstraintLayout>
Note: All the attributes of the ImageView which are starting with
app:layout_constraint are the vertical and horizontal constraints to fix the image
position in the activity. This is very necessary to add the constraint to the ImageView
otherwise, all the images will take the position (0, 0) of the activity layout.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OUTPUT
Android - Image Switcher
Sometimes you don't want an image to appear abruptly on the screen, rather you
want to apply some kind of animation to the image when it transitions from one
image to another.
This is supported by android in the form of ImageSwitcher.
An image switcher allows you to add some transitions on the images through the
way they appear on screen.
In order to use image Switcher, you need to define its XML component first.
Its syntax is given below –
<ImageSwitcher
android:id="@+id/imageSwitcher1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >
</ImageSwitcher>
Now we create an intance of ImageSwithcer in java file and get a reference of this
XML component.
Its syntax is given below –
The last thing you need to do is to add Animation to the ImageSwitcher. You need
to define an object of Animation class through AnimationUtilities class by calling a
static method loadAnimation.
Animation in =
AnimationUtils.loadAnimation(this,android.R.anim.slide_in_
left);
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
Apart from these methods, there are other methods defined in the ImageSwitcher class.
They are defined below –
1. Using Android Studio, create a new Android project and name it ImageSwitcher.
2. Modify the activity_main.xml file by adding the following bolded statements. Please be
sure to change all instances of com.jfdimarzio to reflect the package you use in your
project:
3. Add two images to your res/mipmap folder (as you did in the previous Try It Out). For
this example, I added an image named butterfly.png and an image named windows.jpg.
GridView
The GridView shows items in a two-dimensional scrolling grid. You can use the
GridView together with an ImageView to display a series of images.
How It Works
Like the ImageSwitcher example, you first implement the ImageAdapter class and
then bind it to the GridView:
OUTPUT
Menus are useful for displaying additional options that are not directly visible on the main
user interface (UI) of an application.
There are two main types of menus in Android:
Options menu—This menu displays information related to the
current activity. In Android, you activate the options menu by
pressing the Menu button.
Context menu—This menu displays information related to a
particular view on an activity. In Android, you tap and hold a context
menu to activate it.
You can use the setAlphabeticShortcut() method to assign a shortcut key to the menu item
so that users can select an item by pressing a key on the keyboard. The setIcon() method
sets an image to be displayed on the menu item.
The menuChoice() method takes a MenuItem argument and checks its ID to determine the
menu item that is selected. It then displays a Toast message to let the user know which
menu item was selected.
Options Menu
You are now ready to modify the application to display the options menu when the user presses
the Menu key on the Android device.
Using the same project created in the previous section, add the following
bolded statements to the MainActivity.java file:
1
.
2. Press Shift+F9 to debug the application on the Android emulator. Figure 6-7 shows the
options menu that displays when you click the Menu button. To select a menu item, either
click an individual item or use its shortcut key
How It Works
To display the options menu for your activity, you need to implement two methods in your
activity:
➤➤ onCreateOptionsMenu()
➤➤ onOptionsItemSelected()
Context menu
A context menu is usually associated with a view on an activity. A context menu is
displayed when the user taps and holds an item.
For example, if the user taps a Button view and holds it for a few seconds, a context
menu can be displayed.
If you want to associate a context menu with a view on an activity, you need to call
the setOnCreateContextMenuListener() method of that particular view.
1 Using the same project from the previous example, add the following
. bolded statements to the activity_main.xml file:
3. Add the following bolded statements to the MenusActivity.java file:
4. Press Shift+F9 to debug the application on the Android emulator. Figure 6-8 shows
the context menu that displays when you click and hold the Button view.
5.
Android - WebView
WebView is a view that display web pages inside your application. You can also specify
HTML string and can show it inside your application using WebView. WebView makes
turns your application to a web application.
In order to add WebView to your application, you have to add <WebView> element to
your xml layout file. Its syntax is as follows −
<WebView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
In order to use it, you have to get a reference of this view in Java file. To get a reference,
create an object of the class WebView. Its syntax is −
In order to load a web url into the WebView, you need to call a method loadUrl(String
url) of the WebView class, specifying the required url. Its syntax is:
browser.loadUrl("https://www.tutorialspoint.com");
Apart from just loading url, you can have more control over your WebView by using the
methods defined in WebView class. They are listed as follows −
canGoBack()
1
This method specifies the WebView has a back history item.
canGoForward()
2
This method specifies the WebView has a forward history item.
clearHistory()
3
This method will clear the WebView forward and backward history.
destroy()
4
This method destroy the internal state of WebView.
findAllAsync(String find)
5
This method find all instances of string and highlight them.
getProgress()
6
This method gets the progress of the current page.
getTitle()
7
This method return the title of the current page.
getUrl()
8
This method return the url of the current page.
If you click on any link inside the webpage of the WebView, that page will not be loaded
inside your WebView. In order to do that you need to extend your class
from WebViewClient and override its method. Its syntax is −
Example
Here is an example demonstrating the use of WebView Layout. It creates a basic web
application that will ask you to specify a url and will load this url website in the WebView.
To experiment with this example, you need to run this on an actual device on which
internet is running.
Steps Description
Run the application and choose a running android device and install
5
the application on it and verify the results.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
b1=(Button)findViewById(R.id.button);
ed1=(EditText)findViewById(R.id.editText);
wv1=(WebView)findViewById(R.id.webView);
wv1.setWebViewClient(new MyBrowser());
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = ed1.getText().toString();
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl(url);
}
});
}
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
<TextView android:text="WebView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Text"
android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_marginTop="46dp"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="@+id/imageView"
android:layout_alignEnd="@+id/imageView" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_toRightOf="@+id/imageView"
android:layout_toEndOf="@+id/imageView" />
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/webView"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
<resources>
<string name="app_name">My Application</string>
</resources>
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Saving and loading user preferences
Android provides the SharedPreferences object to help you save simple application
data. For example, your application may have an option that enables users to specify the
font size used in your application. In this case, your application needs to remember the
size set by the user so that the size is set appropriately each time the app is opened. You
have several options for saving this type of preference:
➤➤ Save data to a file—You can save the data to a file, but you have to perform some
file management routines, such as writing the data to the file, indicating how many
characters to read from it, and so on. Also, if you have several pieces of information to
save, such as text size, font name, preferred background color, and so on, then the task
of writing to a file becomes more onerous.
➤➤ Writing text to a database—An alternative to writing to a text file is to use a
database.However, saving simple data to a database is overkill, both from a developer’s
point of view and in terms of the application’s run-time performance.
➤➤ Using the SharedPreferences object—The SharedPreferences object, however,
saves data through the use of name/value pairs. For example, specify a name for the
data you want to save, and then both it and its value will be saved automatically to an
XML file.
Android - Shared Preferences
Android provides many ways of storing data of an application. One of this way is
called Shared Preferences. Shared Preferences allow you to save and retrieve
data in the form of key,value pair.
Shared Preferences is the way in which one can store and retrieve small
amounts of primitive data as key/value pairs to a file on the device storage such
as String, int, float, Boolean that make up your preferences in an XML file inside
the app on the device storage.
For example, you might have a key being “username” and for the value, you
might store the user’s username. And then you could retrieve that by its key
(here username).
You can have a simple shared preference API that you can use to store
preferences and pull them back as and when needed.
The shared Preferences class provides APIs for reading, writing, and managing
this data.
In order to use shared preferences, you have to call a method
getSharedPreferences() that returns a SharedPreference instance pointing to the
file that contains the values of preferences.
SharedPreferences sharedpreferences =
getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
The first parameter is the key and the second parameter is the MODE.
This method takes two arguments, the first being the name of the SharedPreference(SP)
file and the other is the context mode that we want to store our file in.
MODE_PUBLIC will make the file public which could be accessible by other
applications on the device
MODE_PRIVATE keeps the files private and secures the user’s data.
MODE_APPEND is used while reading the data from the SharedPreference file.
Apart from the putString method , there are methods available in the editor class
that allows manipulation of data inside shared preferences. They are listed as
follows –
Example
This example demonstrates the use of the Shared Preferences. It display a screen with
some text fields, whose value are saved when the application is closed and brought back
when it is opened again.
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences =
getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor =
sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LON
G).show();
}
});
}
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shared Preference "
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="35dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="35dp"
android:textColor="#ff16ff01" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/textView2"
android:layout_marginTop="67dp"
android:hint="Name"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Pass" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText3"
android:layout_below="@+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="Email" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />
</RelativeLayout>
Now just put in some text in the field. Like i put some random name
and other information and click on save button.
Now when you press save button, the text will be saved in the shared preferences. Now
press back button and exit the application. Now open it again and you will see all the text
you have written back in your application.
Android supports the following ways of storing data in the local file system:
In this chapter we are going to look at the internal storage. Internal storage is the
storage of the private data on the device memory.
By default these files are private and are accessed by only your application and
get deleted , when user delete your application.
Writing file
In order to use internal storage to write some data in the file, call the
openFileOutput() method with the name of the file and the mode. The mode
could be private , public e.t.c.
Reading file
In order to read from the file you just created , call the openFileInput() method
with the name of the file. It returns an instance of FileInputStream.
After that, you can call read method to read one character at a time from the file
and then you can print it.
Apart from the methods of write and close, there are other methods provided by the
FileOutputStream class for better writing files.
Apart from the the methods of read and close, there are other methods provided
by the FileInputStream class for better reading files. These methods are listed
below –
Example
Here is an example demonstrating the use of internal storage to store and read files. It
creates a basic storage application that allows you to read and write from internal
storage.
package com.example.sairamkrishna.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
String data;
private String file = "mydata";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
ed1=(EditText)findViewById(R.id.editText);
tv=(TextView)findViewById(R.id.textView2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
data=ed1.getText().toString();
try {
FileOutputStream fOut =
openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(),"file
saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(file);
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp +
Character.toString((char)c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(),"file
read",Toast.LENGTH_SHORT).show();
}
catch(Exception e){
}
}
});
}
}
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:hint="Enter Text"
android:focusable="true"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6"
android:layout_below="@+id/imageView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:layout_marginTop="42dp"
android:layout_alignLeft="@+id/imageView"
android:layout_alignStart="@+id/imageView" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="load"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
android:id="@+id/textView2"
android:layout_below="@+id/editText"
android:layout_toLeftOf="@+id/button2"
android:layout_toStartOf="@+id/button2"
android:textColor="#ff5bff1f"
android:textSize="25dp" />
</RelativeLayout>
Now what you need to do is to enter any text in the field. For example , i have entered
some text. Press the save button. The following notification would appear in you AVD –
Now when you press the load button, the application will read the file , and display the
data.
Persisting Data to Files
The SharedPreferences object enables you to store data that is best stored as
name/value pairs— for example, user ID, birth date, gender, driver’s license
number, and so on. However, sometimes you might prefer to use the traditional
file system to store your data. For example, you might want to store the text of
poems you want to display in your applications. In Android, you can use the
classes in the java.io package to do so.
The first way to save files in your Android application is to write to the device’s
internal storage. The following Try It Out demonstrates how to save a string
entered by the user to the device’s internal storage.
7. Click the Load button and you should see the string appearing in the EditText
view again. This confirms that the text is saved correctly.
How It Works
To save text into a file, you use the FileOutputStream class. The openFileOutput()
method opens a named file for writing, with the mode specified. In this example, you use the
MODE_PRIVATE constant to indicate that the file is readable by all other applications:
FileOutputStream fOut = openFileOutput("textfile.txt", MODE_PRIVATE);
To convert a character stream into a byte stream, you use an instance of the
OutputStreamWriter class, by passing it an instance of the FileOutputStream
object:
You then use its write() method to write the string to the file. To ensure that all the bytes
are written to the file, use the flush() method. Finally, use the close() method to close
the file:
//---write the string to the file--- osw.write(str);
osw.flush(); osw.close();
7. To read the content of a file, you use the FileInputStream class, together with
the
InputStreamReader class: FileInputStream fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
Because you do not know the size of the file to read, the content is read in blocks of 100
characters into a buffer (character array). The characters read are then copied into a
String object:
char[] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead); s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
Sometimes, it would be useful to save them to external storage (such as an SD card) because
of its larger capacity, as well as the capability to share the files easily with other users (by
removing the SD card and passing it to somebody else).
You can use the following steps to save files to external storage.
1. Using the project created in the previous section as the example (saving text entered by the user to
the SD card), modify the onClick() method of the Save button as shown in bold here:
2. The preceding code uses the getExternalStorageDirectory() method to return
the full path to the external storage. Typically, it should return the “/sdcard” path for a
real device, and “/mnt/sdcard” for an Android emulator. However, you should never try
to hardcode the path to the SD card, as manufacturers may choose to assign a different path
name to the SD card. Be sure to use the getExternalStorageDirectory() method to
return the full path to the SD card.
6. Note that in order to write to the external storage, you need to add the
WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml file:
Choosing the Best storage option
Which one should you use in your applications? Here are some guidelines:
If you have data that can be represented using name/value pairs, then use the
SharedPreferences object. For example, if you want to store user preference
data such as username, background color, date of birth, or last login date, then the
SharedPreferences object is the ideal way to store this data. Moreover, you
don’t really have to do much to store data this way. Simply use the
SharedPreferences object to store and retrieve it.
If you need to store ad-hoc data then using the internal storage is a good option. For
example, your application (such as an RSS reader) might need to download images
from the web for display. In this scenario, saving the images to internal storage is a
good solution. You might also need to persist data created by the user, such as when
you have an application that enables users to take notes and save them for later use.
In both of these scenarios, using the internal storage is a good choice.
There are times when you need to share your application data with other users. For
example ,you might create an Android application that logs the coordinates of the
locations that a user has been to, and subsequently, you want to share all this data
with other users. In this scenario, you can store your files on the SD card of the device
so that users can easily transfer the data to other devices (and computers) for use
later.
Creating and using dataBases
So far, all the techniques you have seen are useful for saving simple sets of data.
For saving relational data, using a database is much more efficient.
For example, if you want to store the test results of all the students in a school, it is
much more efficient to use a database to represent them because you can use
database querying to retrieve the results of specific students.
Moreover, using databases enables you to enforce data integrity by specifying the
relationships between different sets of data.
Android uses the SQLite database system.
The database that you create for an application is only accessible to itself; other
applications will not be able to access it.
In this section, you find out how to programmatically create a SQLite database in
your Android application.
For Android, the SQLite database that you create programmatically in an application is
always stored in the /data/data/<package_name>/databases folder.
In particular, the DATABASE_CREATE constant contains the SQL statement for creating the
contacts table within the MyDB database.
Within the DBAdapter class, you also add a private class that extends the
SQLiteOpenHelper class. SQLiteOpenHelper is a helper class in Android to manage
database creation and version management. In particular, you must override the
onCreate() and onUpgrade() methods:
The onCreate() method creates a new database if the required database is not present.
The onUpgrade() method is called when the database needs to be upgraded. This is
achieved by checking the value defined in the DATABASE_VERSION constant. For this
implementation of the onUpgrade() method, you simply drop the table and create it
again.
You can then define the various methods for opening and closing the database, as well as the
methods for adding/editing/deleting rows in the table:
Notice that Android uses the Cursor class as a return value for queries. Think of the Cursor as a
pointer to the result set from a database query. Using Cursor enables Android to more efficiently
manage rows and columns as needed.
You use a ContentValues object to store name/value pairs. Its put() method enables you to
insert keys with values of different data types.
To create a database in your application using the DBAdapter class, you create an instance of the
DBAdapter class:
public DBAdapter(Context ctx)
{
this.context = ctx; DBHelper = new DatabaseHelper(context);
}
The constructor of the DBAdapter class will then create an instance of the DatabaseHelper class to create a
new database:
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
With the DBAdapter helper class created, you are now ready to use the database. In the following
sections, you will learn how to perform the regular CRUD (create, read, update and delete)
operations commonly associated with databases.
Adding Contacts
The following Try It Out demonstrates how you can add a contact to the table
The insertContact() method returns the ID of the inserted row. If an error occurs during the
operation, it returns –1.
To retrieve all the contacts in the contacts table, use the getAllContacts() method of the
DBAdapter class, as the following Try It Out shows.
How It Works
The getAllContacts() method of the DBAdapter class retrieves all the contacts stored in the
database. The result is returned as a Cursor object. To display all the contacts, you first need to call
the moveToFirst() method of the Cursor object. If it succeeds (which means at least one row
is available), then you display the details of the contact using the DisplayContact() method. To
move to the next contact, call the moveToNext() method of the Cursor object.
Retrieving a Single Contact
To retrieve a single contact using its ID, call the getContact() method of the DBAdapter class,
as the following Try It Out shows.
How It Works
The getContact() method of the DBAdapter class retrieves a single contact using its ID. You
pass in the ID of the contact. In this case, you pass in an ID of 2 to indicate that you want to retrieve
the second contact:
Cursor c = db.getContact(2);
Updating a Contact
To update a particular contact, call the updateContact() method in the DBAdapter class by
passing the ID of the contact you want to update, as the following Try It Out shows.
How It Works
The updateContact() method in the DBAdapter class updates a contact’s details by using the
ID of the contact you want to update. It returns a Boolean value, indicating whether the update was
successful.
Deleting a Contact
To delete a contact, use the deleteContact() method in the DBAdapter class by passing the
ID of the contact you want to update, as the following Try It Out shows.
How It Works
The deleteContact() method in the DBAdapter class deletes a contact using the ID of the
contact you want to delete. It returns a Boolean value, indicating whether the deletion was
successful.
Upgrading the Database
Sometimes, after creating and using the database, you might need to add additional tables, change
the schema of the database, or add columns to your tables. In this case, you need to migrate your
existing data from the old database to a newer one.
To upgrade the database, change the DATABASE_VERSION constant to a value higher than the
previous one. For example, if its previous value was 1, change it to 2:
When you run the application one more time, you see the following message in the logcat window of
Android Studio: