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

Week 1 Android Programming What Is Android?

Android is an open source operating system used in mobile devices. It was developed by Google and other companies. The document discusses Android features, how to set up an Android development environment, and steps to create a simple "Hello World" Android app using Eclipse IDE, including creating an Android Virtual Device for testing. It also covers Android app components, XML resources, and common UI layouts like LinearLayout and RelativeLayout.

Uploaded by

nino sulit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Week 1 Android Programming What Is Android?

Android is an open source operating system used in mobile devices. It was developed by Google and other companies. The document discusses Android features, how to set up an Android development environment, and steps to create a simple "Hello World" Android app using Eclipse IDE, including creating an Android Virtual Device for testing. It also covers Android app components, XML resources, and common UI layouts like LinearLayout and RelativeLayout.

Uploaded by

nino sulit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 47

WEEK 1

INTRODUCTION
ANDROID PROGRAMMING
What is Android?
Android is an open source (free to use) and Linux-based Operating System for mobile devices such as
tablets and smartphones. It was developed by the Open Handset Alliance, led by Google, and other
companies.
The first beta version of the Android Software Development Kit (SDK) was released by Google in 2007,
whereas the first commercial version, Android 1.0, was released in September 2008.
On June 27, 2012, at the Google I/O conference, Google announced the next Android version, 4.1 Jelly
Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in
terms of functionality and performance.
Some great features of Android
1. Beautiful UI - Android OS’s screen has beautiful and intuitive user interface
2. Connectivity – Wi-fi, Bluetooth, WiMAX, LTE, GSM/EDGE, Etc.
3. Storage – SQLite, a built-in lightweight relational database that is used for data storage
purposes. SQLite’s syntax is the almost same as SQL databases.
4. Media Support – Audio file like: Ogg, Vorbis, Wav and MP3. Image file like: PNG, GIF, JPEG,
and BMP
5. Messaging – SMS and MMS
6. Web Browser – Based on the open-source WebKit layout engine, coupled with Chrome’s V8
JavaScript engine supporting HTML5 and CSS3.
7. Multi-touch – Native support for multi-touch.
8. Multi-tasking – User can jump from one task to another and same time various application
can run simultaneously.
Android Apps
Android applications are usually developed in the Java language using the Android Software
Development Kit.
Once developed, Android applications can be packaged easily and sold out either through a store such
as Google Play or the Amazon Appstore. Android powers hundreds of millions of mobile devices in more
than 190 countries around the world. It's the largest installed base of any mobile platform and is
growing fast. Every day more than 1 million new Android devices are activated worldwide

Environment Setup
Android application development can start with:
1. Microsoft Windows XP or later version
2. Mac OS X 10.5.8 or later version with Intel chip
3. Linux including GNU C Library 2.7 or later
4. Minimum of 2GB of RAM (4GB is preferred)
5. 1.5GB of available disk space
Tools for developing Android app:
1. Java JDK5 or JDK6
2. Android SDK
3. Eclipse IDE for Java Developers
4. Android Development Tools (ADT) Eclipse Plugin

Steps on how to start your first Android App.


1. Open Eclipse IDE

2. Choose workspace (folder where your project will be placed)

3. Eclipse ADT environment


4. Create new project: File -> New -> Android Application Project
5. Provide necessary application set, press next.

6. Finish
5. Package Explorer – where all resources including source code, XML file, AndroidManifest, and
other related file is located. Package explorer serves as navigation for coding, changing design
and adding resources in your application.
6. The graphical layout of the App

NOTE: Android applications can only be ran in an android device. Thus, for our app to run on computer,
we need to have an Emulator. Android eclipse supports default emulator: Android Virtual Device (AVD)

To create an AVD, click Android Virtual Device Manager.


6. Create new AVD.
a. AVD List
b. AVD Set up
c. Back to AVD List
7. Run project. Right click -> Run as -> Run Configurations…
8. Choose the created AVD. Target tab -> Choose MyVirtualDevice AVD.
9. Android Emulator loading screen 10. After the emulator finished loading,
MyFirstAndroidApp should run.

A. Project components

src – your source code

gen – auto-generated code (usually just R.java)

Included libraries

Resources

- Drawables (like .png images)


- Layouts
- Values (like strings)
B. XML Sources

Used to define some of the resources like:


- Layouts (UI)
- Strings

Manifest file

- Shouldn’t usually have to edit it directly, Eclipse can do that for you

Preferred way of creating UIs

- Separates the description of the layout from any actual code that controls it
- Can easily take a UI from one platform to another
C. R Class

Auto-generated: you shouldn’t edit it

Contains IDs of the project resources

Enforces good software engineering

Use findViewById and Resources object to get access to the resources

- Ex. Button b = (Button)findViewById(R.id.button1)


- Ex. getResources().getString(R.string.hello));
D. Strings

In res/values

- strings.xml

Application wide available strings

Promotes good software engineering

UI components made in the UI editor should have text defined in strings.xml

E. Manifest File

Contains characteristics about your application

When have more than one Activity in app, NEED to specify it in manifest file

- Go to graphical view of the manifest file


- Add an Activity in the bottom right
- Browse for the name of the activity

Need to specify Services and other components too

Also important to define permissions and external libraries, like Google Maps API
WEEK 2
Activity, Activity Life Cycle, UI Layouts, UI Controls
Activity

The basis of android applications

A single Activity defines a single viewable screen

- the actions, not the layout

Can have multiple per application

Each is a separate entity

They have a structured life cycle

- Different events in their life happen either via the user touching buttons or
programmatically
Activity Life Cycle
UI Layouts

- The basic building block for user interface is a View object which is created from the View class and
occupies a rectangular area on the screen and is responsible for drawing and event handling. View
is the base class for widgets, which are used to create interactive UI components like buttons, text
fields, etc.

- The ViewGroup is a subclass of View and provides invisible container that hold other Views or other
ViewGroups and define their layout properties.

- Once your layout is defined, you can load the layout resource from your application code, in your
Activity.onCreate() callback implementation as shown below.

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Android Layout Types

There are number of Layouts provided by Android which you will use in almost all the Android
applications to provide different view, look and feel.

# Layout Description
1. Linear Layout LinearLayout is a view group that aligns all children in a single
direction, vertically or horizontally.
2. Relative Layout RelativeLayout is a view group that displays child views in relative
positions.
3. Table Layout TableLayout is a view that groups views into rows and columns.
4. Absolute Layout AbsoluteLayout enables you to specify the exact location of its
children.
5. Frame Layout The FrameLayout is a placeholder on screen that you can use to
display a single view.
6. List View ListView is a view group that displays a list of scrollable items.
7. Grid View View GridView is a ViewGroup that displays items in a two-
dimensional, scrollable grid.

Layout Attributes

Each layout has a set of attributes which define the visual properties of that layout. There are few
common attributes among all the layouts and there are other attributes which are specific to that
layout. Following are common attributes and will be applied to all the layouts:
Layout Attribute Description
android:id This is the ID which uniquely identifies the view.

android:layout_width This is the width of the layout

android:layout_height This is the height of the layout

android:layout_marginTop This is the extra space on the top side of the layout.

android:layout_marginBottom This is the extra space on the bottom side of the layout.

android:layout_marginLeft This is the extra space on the left side of the layout.

android:layout_marginRight This is the extra space on the right side of the layout.

android:layout_gravity This specifies how much of the extra space in the layout should be
allocated to the View.
android:layout_weight This specifies how child Views are positioned.

android:layout_x This specifies the x-coordinate of the layout.

android:layout_y This specifies the y-coordinate of the layout.

android:layout_width This is the width of the layout.

android:paddingLeft This is the left padding filled for the layout.

android:paddingRight This is the right padding filled for the layout.

android:paddingTop This is the top padding filled for the layout.

android:paddingBottom This is the bottom padding filled for the layout.

Here width and height are the dimension of the layout/view which can be specified in terms of dp
(Density-independent Pixels), sp (Scale-independent Pixels), pt (Points which is 1/72 of an inch), px
(Pixels), mm (Millimeters) and finally in (inches).

Gravity attribute (android:layout_gravity & android:gravity) – posibile values:

Constant Value Description


top 0x30 Push object to the top of its container, not changing its
size.
bottom 0x50 Push object to the bottom of its container, not changing
its size.
left 0x03 Push object to the left of its container, not changing its
size.
right 0x05 Push object to the right of its container, not changing its
size.
center_vertical 0x10 Place object in the vertical center of its container, not
changing its size.
fill_vertical 0x70 Grow the vertical size of the object if needed so it
completely fills its container.
center_horizontal 0x01 Place object in the horizontal center of its container, not
changing its size.
fill_horizontal 0x07 Grow the horizontal size of the object if needed so it
completely fills its container.
center 0x11 Place the object in the center of its container in both the
vertical and horizontal axis, not changing its size.
fill 0x77 Grow the horizontal and vertical size of the object if
needed so it completely fills its container.
clip_vertical 0x80 Additional option that can be set to have the top and/or
bottom edges of the child clipped to its container's
bounds. The clip will be based on the vertical gravity: a top
gravity will clip the bottom edge, a bottom gravity will clip
the top edge, and neither will clip both edges.
clip_horizontal 0x08 Additional option that can be set to have the left and/or
right edges of the child clipped to its container's bounds.
The clip will be based on the horizontal gravity: a left
gravity will clip the right edge, a right gravity will clip the
left edge, and neither will clip both edges.
start 0x00800003 Push object to the beginning of its container, not changing
its size.
end 0x00800005 Push object to the end of its container, not changing its
size.

View Identification

A view object may have a unique ID assigned to it which will identify the View uniquely within the tree.
The syntax for an ID, inside an XML tag is:

android:id="@+id/my_button"

Following is a brief description of @ and + signs:

- The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and
expand the rest of the ID string and identify it as an ID resource.
- The plus-symbol (+) means that this is a new resource name that must be created and added to our
resources. To create an instance of the view object and capture it from the layout, use the
following:
Button myButton = (Button) findViewById(R.id.my_button);

Android UI Controls

There are number of UI controls provided by Android that allows you to build the graphical user
interface for your app.

# UI Control Description
1. TextView This control is used to display text to the user.

2. EditText EditText is a pre-defined subclass of TextView that includes rich


editing capabilities.
3. AutoCompleteTextView The AutoCompleteTextView is a view that is similar to EditText,
except that it shows a list of completion suggestions
automatically while the user is typing.
4. Button A push-button that can be pressed, or clicked, by the user to
perform an action.
5. ImageButton A push-button that can be pressed, or clicked, by the user to
perform an action. Unlike a simple Button, ImageButton has an
Image on it for design purposes.
6. AbsoluteLayout enables you to specify the exact location of its children.

7. CheckBox An on/off switch that can be toggled by the user. You should use
checkboxes when presenting users with a group of selectable
options that are not mutually exclusive.
8. ToggleButton An on/off button with a light indicator.

9. RadioButton The RadioButton has two states: either checked or unchecked.

10. RadioGroup A RadioGroup is used to group together one or more


RadioButtons.
11. ProgressBar The ProgressBar view provides visual feedback about some
ongoing tasks, such as when you are performing a task in the
background.
12. Spinner A drop-down list that allows users to select one value from a set.

13. TimePicker The TimePicker view enable users to select a time of the day, in
either 24-hour mode or AM/PM mode.
14. DatePicker The DatePicker view enable users to select a date of the day.
Create UI Controls

<?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:id="@+id/text_id"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="I am a TextView" />

</LinearLayout>

Then finally create an instance of the Control object and capture it from the layout, use the following:

TextView myText = (TextView) findViewById(R.id.text_id);


WEEK 3
Java Programming Basics

Data types

Type Represents Range value Default


value
boolean Boolean value true or false False
byte 8-bit unsigned -127 to 128 0
integer
short 16-bit signed -32,768 to 32,767 0
integer
int 32-bit signed -2,147,483,648 to 2,147,483,647 0
integer
long 64-bit signed -923,372,036,854,775,808 to 0
integer 9,223,372,036,854,775,807
float 32-bit single- -3.4 x 10^38 to + 3.4 x 10^38 0.0F
precision floating
point type
double 64-bit double- (+/-)5.0 x 10^-324 to (+/-)1.7 x 0.0D
precision floating 10^308
point type
String fixed array of 32 byte characters (2, 147, 483, 648 Null
characters characters)
Char 16-bit Unicode U +0000 to U +ffff ‘\0’
character

Looping Statements in Java

- Java has four (4) looping keywords that are used for iterating statements. They are:
o While loop
 Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.
 Syntax:
 while(<condition>){ <Statements> }
o Do-while loop
 Like while statement, except that it tests the condition at the end of the loop body.
 Syntax:
 do{ <statements> } while(<condition>);
o For loop
 Execute a sequence of statements multiple times and abbreviates the code that
manages the loop.
 Syntax:
 for(<initialization> ; <condition> ; <inc/dec>) { <Statements>}
o Enhanced for loop
 This for loop can traverse a collection of elements such as arrays.
 Syntax:
 for(<element holder declaration>: <array/collection>){ <Statements> }

Functions in Java

- A function is a block of code that has a name and property that is reusable. It can be executed from
as many different points in program as required.
- In Java, functions are defined inside classes.

Two types of function

1. Java Default Function


2. User-defined Function

Java default functions

- These functions are defined inside any Java IDE.


- Example of Classes that has default functions
o Activity (onCreate, onPause, onResume, etc.)
o Random (nextInt, nextDouble, nextFloat, etc)
o String (equals, compareTo, toArray, etc.)
o Button (setText, setOnClickListener, etc.)
Java user-defined functions

Examples:

Function to get the sum of two parameter

public class UserDefined{

private int firstNumber = 10;

private int secondNumber = 20;

public static void main(String [] args)

int sum = getSum(firstNumber, secondNumber);

private int getSum(int first, int second)

return first + second;

WEEK 4
Event Handling

Events in Android

- Events are a useful way to collect data about a user's interaction with interactive components of
your app, like button presses or screen touch etc.

* These are following three concepts related to Android Event Management:

Event Listeners

- The View class is mainly involved in building up an Android GUI, same View class provides a number
of Event Listeners. The Event Listener is the object that receives notification when an event occurs.

Event Listeners Registration

- Event Registration is the process by which an Event Handler gets registered with an Event Listener
so that the handler is called when the Event Listener fires the event.
Event handler

- When an event happens and we have registered an event listener for the event, the event listener
calls the Event Handlers, which is the method that actually handles the event.

Examples

Event Handler Event Listener & Description


onClick() OnClickListener
This is called when the user either clicks or touches or focuses
upon any widget like button, text, image etc. You will use onClick()
event handler to handle such event.
onLongClick() OnLongClickListener
This is called when the user either clicks or touches or focuses
upon any widget like button, text, image etc. for one or more
seconds. You will use onLongClick() event handler to handle such
event.
onFocusChange() OnFocusChangeListener
This is called when the widget loses its focus i.e. user goes away
from the view item. You will use onFocusChange() event handler
to handle such event.

onKey() OnKeyListener
This is called when the user is focused on the item and presses or
releases a hardware key on the device. You will use onKey() event
handler to handle such event.
onTouch OnTouchListener
This is called when the user presses the key, releases the key, or
any movement gesture on the screen. You will use onTouch()
event handler to handle such event.
onMenuItemClick() OnMenuItemClickListener
This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.

There are many more event listeners available as a part of View class like OnHoverListener,
OnDragListener etc., which may be needed for your application.
Steps on creating Event in Android:

Step 1:

Create a new project name it EventListerProject. Just leave all default settings of your project.

Step 2:

In your activity_main.xml, place a two textboxes and a button. Make sure to change the default layout
(RelativeLayout) to LinearLayout.
Graphical Layout:

strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">EventListenerProject</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="add">Add Numbers</string>

</resources>

activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<EditText
android:id="@+id/etNum1"
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" >

<requestFocus />
</EditText>

<EditText
android:id="@+id/etNum2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />

<Button
android:id="@+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/add" />

</LinearLayout>

 Notice that IDs of textboxes and the button is changed.

Step 3:

Paste the following code on your MainActivity


package com.example.eventlistenerproject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity{

Button btnAdd;
EditText etNum1, etNum2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewByIds(); // USER DEFINED FUNCTION
btnAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int num1 =
Integer.parseInt(etNum1.getText().toString());
int num2 =
Integer.parseInt(etNum2.getText().toString());
int sum = getSum(num1, num2); // USER-DEFINED
FUNCTIONs
Toast.makeText(MainActivity.this, "The sum is: "+sum,
Toast.LENGTH_SHORT).show();
}
});
}

private void findViewByIds()


{
btnAdd = (Button) findViewById(R.id.btnAdd);
etNum1 = (EditText) findViewById(R.id.etNum1);
etNum2 = (EditText) findViewById(R.id.etNum2);
}
private int getSum(int num1, int num2)
{
return num1 + num2;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Step 4:

Run your Android Application Project. Make sure you have your default emulator.

Conclusion: The app will accept two numbers using EditTexts, and add the input when the button was
clicked. The sum will be displayed in a Toast notification.
WEEK 5
Threads and Splash Screen
Starting a new Activity
- If you want to open multiple xml Layout within your app, you have to create new Class and XML
files that will handle your layouts.
Steps on starting a new Activity.
Step 1:
Create a new android application project, name it StartingNewActivity. Just leave all the default settings
for your project.

Step 2:

Aside from activity_main.xml, create a new xml file name it activity_two. Then paste the following code.

1. activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>

<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_gravity="center"
android:text="@string/next" />

</LinearLayout>

2. activity_two.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textSize="20sp"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="@string/second"

/>
</LinearLayout>

3. add this line of code to strings.xml

<string name="second">This is second activity</string>

Step 3:

Add new class to your package, name it NextActivity. Paste the following code on your classes.

MainActivity:
package com.example.startingnewactivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button btnNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnNext = (Button) findViewById(R.id.btnNext);
btnNext.setOnClickListener((OnClickListener) this);
}

public void onClick(View v)


{
if(v.getId() == R.id.btnNext)
{
Intent i = new Intent();
i.setClass(MainActivity.this, NextActivity.class);
startActivity(i);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

NextActivity.java:
package com.example.startingnewactivity;

import android.app.Activity;
import android.os.Bundle;

public class NextActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);

}
Step 4:

We have to declare our NextActivity class to our AndroidManifest file for it to be recognized as a valid
Class. If we do not do this, NextActivity will not display any layout, hence, a force close.

Paste the following code on AndroidManifest file.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.startingnewactivity"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity <!-- here's for MainActivity -->
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>
<activity <!-- here's for the NextActivity -->
android:name=".NextActivity"
android:label="@string/app_name" >
</activity>
</application>

</manifest>

Step 5:

Run the Application.

Conclusion: The application will be directed to another layout/view when the button was clicked.
Splash Screen

- Splash screens are typically used by particularly large applications to notify the user that the
program is in the process of loading. They provide feedback that a lengthy process is underway.
- The following are sample splash screen of popular android apps.

Threads

- A thread is an independent path of execution within a program. Many threads can run concurrently
within a program. Every thread in Java is created and controlled by the java.lang.Thread class. A
Java program can have many threads, and these threads can run concurrently, either
asynchronously or synchronously.
- Multithreading has several advantages over Multiprocessing such as:
o Threads are lightweight compared to processes.
o Threads share the same address space and therefore can share both data and code.
o Context switching between threads is usually less expensive than between processes.
o Cost of thread intercommunication is relatively low that that of process
intercommunication.
o Threads allow different tasks to be performed concurrently.

You can use Threads in Java to make a splash screen of your application. The following is an example of
a splash screen program in Android:

Step 1:
Create a new android application project, name it SplashActivity. Just leave all the default settings for
your project. Just leave all default settings for your project.
Step 2:
In your res folder, create a new folder and name it raw.
Step 3:
Drag and drop any image to raw folder except PNG file and select copy files.
Splash image should appear in raw folder. The image should also be named Splash.jpeg
Step 4:
Make an ImageView to have a splash screen image. Paste the FF. code to your activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@raw/Splash" />

</LinearLayout>

Layout:

Step 5:

Inside your MainActivity, you must create a thread that handles how long the splash screen will stay.
Paste the following code in MainActivity class.
package com.example.splashactivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent();
i.setClass(MainActivity.this, NextActivity.class);
startActivity(i);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

You’ll notice that NextActivity class is not yet created. So, you need to create it first.
Step 6:

Create NextActivity, just leave default settings but make sure to extend the NextActivity with Activity
class and implement onCreate Method. Code is as follows.

package com.example.splashactivity;

import android.app.Activity;
import android.os.Bundle;

public class NextActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app);
}

You’ll notice that the layout activity_app is not yet created. So you should create one.

Step 7:

Go to your layout folder, and create activity_app.xml. Paste the following code.

package com.example.splashactivity;

import android.app.Activity;
import android.os.Bundle;

public class NextActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app);
}
}

Run your android app.

Conclusion: You have created a simple splash screen for your application.

Source: http://www.wideskills.com/java-tutorial/java-threads-tutorial
WEEK 7
Session Handling

Session
- Session helps you when want to store user data outside your application, so that when the next
time user use your application, you can easily get back his details and perform accordingly. This can
be done in many ways. But the most easiest and nicest way of doing this is through Shared
Preferences.

SharedPreferences
- allows you to save and retrieve data in the form of key value pair. In order to use shared
preferences
- You have to call the method getSharedPreferences() that returns a SharedPreference instance
pointing to the file that contains the values of preferences.

Syntax for declaring a SharedPreferences Class:


- SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
- In order for us to save data in the SharedPrefereces, we should first access the Editor class which is
a Subclass of SharedPreferences. We should call the edit mode of SharedPreferences instance and
will receive it in an editor object. Its syntax is as follows:
o Editor editor = sharedpreferences.edit(); // get the edit mode instance
o editor.putString("key", "value"); // put a string value to a key.
o editor.commit() // Save changes
NOTE:
1. a “key” is basically an identifier to a value. I terms of database, its equivalent is column, but a
key holds only one value.
2. Session Handling in terms of Android Development is usually used for saving miscellaneous data
like volume, screen resolutions and sometimes, game progress.
There are also other methods of Editor we can use beside putString(), these are some:

Sample Program:

1. Create a new Android Application Project, name it: SharedPreferencesDemo


2. Necessary files are as follows.

activity_main.xml
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_gravity="center_horizontal"
android:text="@string/sesion_handling" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
>
<EditText
android:id="@+id/etData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/save"
/>
</LinearLayout>
</RelativeLayout>

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SharePreferencesDemo</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="sesion_handling">Working with Session Handling</string>
<string name="save">Save Data</string>
</resources>

MainActivity.java
package com.pdm.sharepreferencesdemo;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {


// shared prefs variables
SharedPreferences sharedPrefs;
String sharedPrefsName = "myPrefs";
String keyData = "data";
// layout variables
Button btnSave;
EditText etData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initComponent();
initListener();
initObject();
// after onCreate() method, onResume() will automatically be invoked
}

@Override
protected void onResume()
{
if(sharedPrefs.contains(keyData)){
String data = sharedPrefs.getString(keyData, ""); // param1
is the key and param2 is the default value if key has no value
etData.setText(data);
}
}

private void initComponent() {


btnSave = (Button) findViewById(R.id.btnSave);
etData = (EditText) findViewById(R.id.etData);
}
private void initListener() {
btnSave.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Editor editor = sharedPrefs.edit();
// get the values of editTexts
String data = etData.getText().toString();
// set the key of shared preferences
editor.putString("data", data);
editor.commit();
}
});
}
private void initObject()
{
sharedPrefs = getSharedPreferences(sharedPrefsName,
Context.MODE_PRIVATE);
}
}

Finally, run the app.

Conclusion:
we created an app that saves the entered data of the user.
WEEK 8-9
SQLite Database in Android

You might also like