0% found this document useful (0 votes)
23 views

UNIT 2 Mobile Application Development

Uploaded by

anivenkatesh2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

UNIT 2 Mobile Application Development

Uploaded by

anivenkatesh2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

UNIT 2

Understanding the Components of a screen


 The basic unit of an Android application is an activity, which displays the UI of your
application.
 you define your UI using an XML file (for example, the activity_main.xml file located in the
res/layout folder of your project)
 During runtime, you load the XML UI in the onCreate() method handler in your Activity class,
using the setContentView() method of the Activity class:
@Override
public void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState); setContentView(R.layout.main); }

Views and Viewgroups


 An activity contains views and ViewGroups.
 A view is a widget that has an appearance on screen. Examples of views are
buttons, labels, and text boxes.
 A view derives from the base class android.view.View.
 One or more views can be grouped into a ViewGroup.
 A ViewGroup (which is itself a special type of view) provides the layout in which
you can order the appearance and sequence of views.
 Examples of ViewGroups include RadioGroup and ScrollView. A ViewGroup
derives from the base class android.view.ViewGroup.
 Another type of ViewGroup is a Layout
 A Layout is another container that derives from
android .view.ViewGroup and is used as a container for other views.
 However, whereas the purpose of a ViewGroup is to group views logically—
such as a group of buttons with a similar purpose—a Layout is used to
group and arrange views visually on the screen.
Following are common attributes and will be applied to all the layouts:

Sr.No Attribute & Description

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.

 The Layouts available to you in Android are as follows:

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.

 android:layout_width=wrap_content tells your view to size itself to the


dimensions required by its content.
This attribute tells the view to size itself to fit the content of its children. For
example, if you have a TextView with wrap_content, the view will be sized to fit the
text it contains.
 android:layout_width=fill_parent tells your view to become as big as its parent
view.
This attribute instructs the view to expand to fill the entire available space in its
parent layout.
When you set a view's width or height to match_parent, it will expand to fill the
available space in its parent.

These attributes are important for controlling the layout and appearance of views within
your Android app's user interface.

Common Attributes Used in Views and ViewGroups

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|
//INCLUDE THIS LINE
screenSize"
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

Utilizing the action bar


 In Android applications, ActionBar is the element present at the top of
the activity screen.
 Besides fragments, another feature of Android is the Action Bar.
 In place of the traditional title bar located at the top of the device’s screen, the
Action Bar displays the application icon and the activity title.
 Optionally, on the right side of the Action Bar are action items.
 The setSupportActionBar() method writes your Action Bar to the screen. The
Action Bar can be an instance of a Tool Bar.
 Components included in the ActionBar are:
1. App Icon: Display the branding logo/icon of the application.
2. View Controls: Section that displays the name of the application or current
activity. Developers can also include spinner or tabbed navigation for switching
between views.
3. Action Button: Contains some important actions/elements of the app that may
be required to the users frequently.
4. Action Overflow: Include other actions that will be displayed as a menu. Move
less often used actions to the action overflow.
Changing the ActionBar Title
 The ActionBar title displayed at the top of the screen is governed by
the AndroidManifest.xml file within the activity nodes.
 In the example below, the activity "FirstActivity" will have an ActionBar with the
string value of the resource identified by @string/activity_name.
 If the value of that resource is "Foo," the string displayed in the ActionBar for this
activity will be "Foo."

<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>

 Change the android:label or android:icon to modify the ActionBar title or icon


for a given activity or for the application as a whole.
 In any Java activity, you can also call getSupportActionBar() to retrieve a
reference to the ActionBar and modify or access any properties of the ActionBar at
runtime:

ActionBar actionBar = getSupportActionBar(); // or getActionBar();


getSupportActionBar().setTitle("My new title"); // set the top title
String title = actionBar.getTitle().toString(); // get the title
actionBar.hide(); // or even hide the actionbar

Displaying ActionBar Icon

The icon can be added with:

getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);

The above code results in:


Adding Action Items
When you want to add primary actions to the ActionBar, you add the items to the activity
context menu and if properly specified, they will automatically appear at the top right as
icons in the ActionBar.

An activity populates the ActionBar from within the onCreateOptionsMenu() method:

public class MainActivity extends AppCompatActivity {


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return 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:

<!-- Menu file for `activity_movies.xml` is located in a file


such as `res/menu/menu_movies.xml` -->
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/miCompose"
android:icon="@drawable/ic_compose"
app:showAsAction="ifRoom"
android:title="Compose">
</item>
<item
android:id="@+id/miProfile"
android:icon="@drawable/ic_profile"
app:showAsAction="ifRoom|withText"
android:title="Profile">
</item>
</menu>

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.

The above code results in two action icons being displayed:


Creating the user interface programmatically
 All the UIs are created using XML.
 Besides using XML you can also create the UI using code.
 This approach is useful if your UI needs to be dynamically generated during
runtime.
 For example, suppose you are building a cinema ticket reservation system and
your application displays the seats of each cinema using buttons. In this case, you
need to dynamically generate the UI based on the cinema selected by the user.
 The following Try It Out demonstrates the code needed to dynamically build the UI
in your activity.
 To create a user interface programmatically in Android Studio, you typically follow
these steps:

1. *Create a Layout Container*: You'll need a layout container to hold your UI


elements programmatically. This can be a LinearLayout, RelativeLayout,
ConstraintLayout, etc. You can create it directly in your activity's XML layout file or
programmatically in your Java/Kotlin code.

2. *Instantiate UI Elements*: Create instances of the UI elements you want to


include in your layout. For example, TextView, Button, EditText, etc.

3. *Set Layout Parameters*: For each UI element, create layout parameters


specifying how it should be positioned and sized within the layout container.

4. *Add UI Elements to Layout*: Add the UI elements to the layout container


using the addView() method.

5. *Set Content View*: If you created the layout container programmatically, set it
as the content view of your activity using the setContentView() method.

Creating the UI via Code (UICode.zip)

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:

import android.support.v7.app.AppCompatActivity; import android.os.Bundle;


import android.support.v7.widget.LinearLayoutCompat;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) { super.
OnCreate(savedInstanceState);
LinearLayoutCompat.LayoutParams params = new
LinearLayoutCompat.LayoutParams( LinearLayoutCompat.LayoutParams.W
RAP_CONTENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);

//---create a layout---
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
//---create a text view---

TextView tv = new TextView(this);


tv.setText("This is a TextView");
tv.setLayoutParams(params);

//---create a button---

Button btn = new Button(this);


btn.setText("This is a Button");
btn.setLayoutParams(params);

//---adds the textview---

layout.addView(tv);

//---adds the button--- layout.addView(btn);


//---create a layout param for the layout---

LinearLayoutCompat.LayoutParams layoutParam = new


LinearLayoutCompat.LayoutParams( LinearLayoutCompat.LayoutPar
ams.WRAP_CONTENT,
LinearLayoutCompat.LayoutParams.WRAP_CONTENT );
this.addContentView(layout, layoutParam);
}}
3. Press Shift+F9 to debug the application on the Android emulator.

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---

Button btn = new Button(this); btn.setText("This is a Button");


btn.setLayoutParams(params);

You then added them to the LinearLayout object:


//---adds the textview---
layout.addView(tv);
//---adds the button---
layout.addView(btn);

You also created a LayoutParams object to be used by the LinearLayout object:


//---create a layout param for the layout---
LinearLayout.LayoutParams layoutParam =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT );

Finally, you added the LinearLayout object to the activity:


this.addContentView(layout, layoutParam);
As you can see, using code to create the UI is quite a laborious affair. Hence, you should
dynamically generate your UI using code only when necessary.

Listening for UI notifications

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.

The following code snippet is an instance of such an implementation:

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:

// getBaseContext() – this method is used to retrieve the base context of an activity or


application. This context provides access to application-specific resources and
operations such as accessing files, launching activities or accessing system
services.
Designing Your User Interface with Views
View is the basic building block of UI(User Interface) in android. View refers to the
android.view.View class, which is the super class for all the GUI components like
TextView, ImageView, Button etc.

➤➤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.

Button, imageButton, edittext, CheckBox, toggleButton,


radioButton, and radiogroup Views
Besides the TextView view, which you will likely use the most often, there are some other
basic views that you will find yourself frequently using:
➤➤ Button—Represents a push-button widget.
➤➤ ImageButton—Similar to the Button view, except that it also displays an
image.
➤➤ EditText—A subclass of the TextView view, which allows users to edit its text
content.
➤➤ CheckBox—A special type of button that has two states: checked or
unchecked.
➤➤ RadioGroup and RadioButton—The RadioButton has two states: either
checked or unchecked. A RadioGroup is used to group one or more
RadioButton views, thereby allowing only one RadioButton to be checked
within the RadioGroup.
➤➤ ToggleButton—Displays checked/unchecked states using a light indicator.

Using the Basic Views (BasicViews1.zip)


1. Using Android Studio, create an Android project and name it BasicViews1.
2. Modify the activity_main.xml file located in the res/layout folder by adding the following
elements shown in bold:
3. To see the views in action, debug the project in Android Studio by pressing
Shift+F9. shows the various views displayed in the Android emulator.
4. Click each of the views and note how they vary in look and feel. Figure 5-2
shows the following
changes to the view:
➤➤ The first CheckBox view (Autosave) is checked.
➤➤ The second CheckBox View (star) is selected.
➤➤ The second RadioButton (Option 2) is selected.
➤➤ The ToggleButton is turned on.

 set the image through the src attribute.


 layout_height has been set to wrap_content so that the text entry
location automatically adjusts to fit the amount of text entered by the
user.
 If you do not like the default look of the CheckBox, you can apply a
style attribute so that the check mark is replaced by another image,
such as a star
style="?android:attr/starStyle

Using picker Views


Selecting a date and time is one of the common tasks you need to perform in a
mobile application.
Android supports this functionality through the TimePicker and DatePicker views.
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

1. Using Android Studio, create an Android project and name it BasicViews4.

2. Modify the activity_main.xml file located in the res/layout folder by adding


the following bolded lines:

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

1. Using the BasicViews4 project created earlier, modify the activity_main.xml


file as shown here:

2. Add the following bolded statements to the MainActivity.java file:


3. Press Shift+F9 to debug the application on the Android emulator. After the
date is set, clicking the Button displays the date set.

How It Works
As with the TimePicker, you call the getMonth(), getDayOfMonth(), and getYear() methods to get
the month, day, and year, respectively:

"Date selected:" + (datePicker.getMonth() + 1) +


"/" + datePicker.getDayOfMonth() + "/" + datePicker.getYear() +
"\n" +
Note that the getMonth()method returns 0 for January, 1 for February, and so on. This means you need to
increment the result of this method by one to get the corresponding month number.
Like the TimePicker, you can also display the DatePicker in a dialog window.

Using list Views to Display long lists

 List of scrollable items can be displayed in Android using ListView.


 It helps you to displaying the data in the form of a scrollable list.
 Users can then select any list item by clicking on it.
 ListView is default scrollable so we do not need to use scroll View or
anything else with ListView. ListView is widely used in android applications.
 In Android, there are two types of list views:
ListView and SpinnerView.
 A very common example of ListView is your phone contact book, where you
have a list of your contacts displayed in a ListView and if you click on it then
user information is displayed.
 A ListView is a type of AdapterView.
 In Android, AdapterView is an abstract class that acts as a parent for
several view classes like ListView, GridView, and Spinner. It's used to
display data in a scrollable format by connecting data to the respective
view.
 Using adapter, items are inserted into the list from an array or database.
For displaying the items in the list method setAdaptor() is used.
 The main purpose of the adapter is to fetch data from an array or database and
insert each item that placed into the list for the desired result.
 The ListView and GridView are subclasses of AdapterView
 Android provides several subclasses of Adapter that are useful for retrieving
different kinds of data and building views for an AdapterView ( i.e. ListView
or GridView). The common adapters are ArrayAdapter,Base Adapter,
CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and
WrapperListAdapter. We will see separate examples for both the
adapters.
 To display a list, you can include a list view in your layout XML file:

<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />

ListView Attributes

Following are the important attributes specific to GridView −


Sr.N
Attribute & Description
o

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.

ArrayAdapter adapter = new


ArrayAdapter<String>(this,R.layout.ListView,R.id.textView,StringArray);

Example of list view using Array Adapter:


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.

public class CustomAdapter extends BaseAdapter {


@Override
public int getCount() {
return 0;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
return null;
}
1. getCount():
The getCount() function returns the total number of items to be displayed in a list.

public int getCount() {


int count=arrayList.size(); //counts the total number of elements from the arrayList
return count;//returns the total count to adapter
}

2. getView(int i, View view, ViewGroup viewGroup):


This function is automatically called when the list item view is ready to be displayed or
about to be displayed.

public View getView(int i, View view, ViewGroup viewGroup) {


view = inflter.inflate(R.layout.activity_gridview, null);//set layout for displaying
items
ImageView icon = (ImageView) view.findViewById(R.id.icon);//get id for image view
icon.setImageResource(flags[i]);//set image of the item’s
return view;
}

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;
}

Below is the final output and code with explanation:


Example of list view using Custom adapter(Base adapter):
In this example we display a list of countries with flags. For this, we have to use custom
adapter.

Spinner View

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.
Here is the XML basic code for Spinner:

<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

 A list fragment is a fragment that contains a ListView, which displays a list


of items from a data source, such as an array or a Cursor.
 A list fragment is useful because it’s common to have one fragment that
contains a list of items, and another fragment that displays details about the
selected posting.
 In the chat application, a ListFragment could be used to display a list of
messages exchanged between users in a chat conversation. Each item in
the list represents a message, showing the sender's name, message
content, timestamp, and possibly other metadata such as profile pictures.
 To create a list fragment, you need to extend the ListFragment base class.

Creating and Using a List Fragment

1. Using Android Studio, create an Android project and name it ListFragmentExample.

2. Modify the activity_main.xml file as shown in bold.

3. Add an XML file to the res/layout folder and name it fragment1.xml.

4. Populate the fragment1.xml as follows:


<?xml version="1.0" encoding="utf-8"?>
5. Add a Java Class file to the package and name it Fragment1.

6. Populate the Fragment1.java file as follows:


7. Press Shift+F9 to debug the application on the Android emulator. Figure 5-18
shows the two list fragments displaying the two lists of presidents’ names.

8. Click any of the items in the two ListView views, and you see a message

Using a DialogFragment

 A dialog fragment floats on top of an activity and is displayed modally.


 Dialog fragments are useful when you need to obtain the user’s response
before continuing with execution.
 To create a dialog fragment, you must extend the DialogFragment base
class.

Creating and Using a Dialog Fragment

1. Using Android Studio, create an Android project and name it


DialogFragmentExample.

2. Add a Java Class file under the package and name it Fragment1.

3. Populate the Fragment1.java file as follows:


4. Populate the MainActivity.java file as shown here in bold:

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.

Creating and Using a preference Fragment

1. Using Android Studio, create an Android project and name it


PreferenceFragmentExample.
2. Create a new xml directory under the res folder and then add a new XML resource file
to it.
Name the XML file preferences.xml.
3. Populate the preferences.xml file as follows:

4. Add a Java Class file to the package and name it Fragment1.


5. Populate the Fragment1.java file as follows:
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class Fragment1 extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//---load the preferences from an XML file---
addPreferencesFromResource(R.xml.preferences);
}
}
7. Press Shift+F9 to debug the application on the Android emulator. Figure 5-21 shows
the preference fragment displaying the list of preferences that the user can modify.
8. When the Edit Text preference is clicked, a pop-up is displayed (see Figure 5-22).
9. Clicking Edit Text (Second Screen) causes a second preference screen to be
displayed (see Figure 5-23).
10. To dismiss the preference fragment, click the Back button on the emulator.
How It Works

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.
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 −

WebView browser = (WebView) findViewById(R.id.webview);

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 −

Sr.No Method & Description

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 −

private class MyBrowser extends WebViewClient {


@Override
public boolean shouldOverrideUrlLoading(WebView view,
String url) {
view.loadUrl(url);
return true;
}
}

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

You will use Android studio to create an Android application under a


1
package com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add WebView code.

3 Modify the res/layout/activity_main to add respective XML components

4 Modify the AndroidManifest.xml to add the necessary permissions

Run the application and choose a running android device and install
5
the application on it and verify the results.

Following is the content of the modified main activity file src/MainActivity.java.

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;

public class MainActivity extends Activity {


Button b1;
EditText ed1;

private WebView wv1;


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

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;
}
}
}

Following is the modified content of the


xml res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<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>

Following is the content of the res/values/string.xml.

<resources>
<string name="app_name">My Application</string>
</resources>

Following is the content of AndroidManifest.xml file.

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<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.

Following are the methods of Shared Preferences

1. contains(String key): This method is used to check whether the preferences


contain a preference.
2. edit(): This method is used to create a new Editor for these preferences, through
which you can make modifications to the data in the preferences and atomically
commit those changes back to the SharedPreferences object.
3. getAll(): This method is used to retrieve all values from the preferences.
4. getBoolean(String key, boolean defValue): This method is used to retrieve a
boolean value from the preferences.
5. getFloat(String key, float defValue): This method is used to retrieve a float value
from the preferences.
6. getInt(String key, int defValue): This method is used to retrieve an int value from
the preferences.
7. getLong(String key, long defValue): This method is used to retrieve a long value
from the preferences.
8. getString(String key, String defValue): This method is used to retrieve a String
value from the preferences.
9. getStringSet(String key, Set defValues): This method is used to retrieve a set of
String values from the preferences.
10. registerOnSharedPreferencechangeListener(SharedPreferences.OnShared
PreferencechangeListener listener): This method is used to register a callback to
be invoked when a change happens to a preference.
11. unregisterOnSharedPreferencechangeListener(SharedPreferences.OnShar
edPreferencechangeListener listener): This method is used to unregister a
previous callback.

You can save something in the sharedpreferences by using SharedPreferences.Editor


class. You will call the edit method of SharedPreference instance and will receive it in an
editor object. Its syntax is –

Editor editor = sharedpreferences.edit();


editor.putString("key", "value");
editor.commit();

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.
Following is the content of the modified MainActivity.java.

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


EditText ed1,ed2,ed3;
Button b1;

public static final String MyPREFERENCES = "MyPrefs" ;


public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";

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();
}
});
}

Following is the content of the modified main activity


fileres/layout/activiy_main.xml.

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

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:

 Files - You can create and update files


 Preferences - Android allows you to save and retrieve persistent key-value pairs of
primitive data type.
 SQLite database - instances of SQLite databases are also stored on the local file system.

Android - Internal Storage


 Android provides many kinds of storage for applications to store their data. These
storage places are shared preferences, internal and external storage, SQLite
storage, and storage via network connection.

 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.

 Its syntax is given below –

FileOutputStream fOut = openFileOutput("file name


here",MODE_WORLD_READABLE);

The method openFileOutput() returns an instance of FileOutputStream. So you receive


it in the object of FileInputStream. After that you can call write method to write data on
the file.

Its syntax is given below –

String str = "data";


fOut.write(str.getBytes());
fOut.close();

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.

 Its syntax is given below –

FileInputStream fin = openFileInput(file);

 After that, you can call read method to read one character at a time from the file
and then you can print it.

Its syntax is given below –

int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}

//string temp contains all the data of the file.


fin.close();

Apart from the methods of write and close, there are other methods provided by the
FileOutputStream class for better writing files.

These methods are listed below –

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.

Following is the content of the modified main activity


file src/MainActivity.java.

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;

public class MainActivity extends Activity {


Button b1,b2;
TextView tv;
EditText ed1;

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){
}
}
});
}
}

Following is the modified content of the


xml res/layout/activity_main.xml.

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Internal storage"


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" />

<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.

You might also like