UNIT 2 Mobile Application Development
UNIT 2 Mobile Application Development
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|
//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
<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.
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
How It Works
As with the TimePicker, you call the getMonth(), getDayOfMonth(), and getYear() methods to get
the month, day, and year, respectively:
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
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.
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.
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;
}
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" />
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.
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.
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;
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.
int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}
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">
<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.