Wednesday 4 November 2015

Learn Android through examples

Create HelloWorld Activity

In this example, we show you how to create a simple “hello world” Android project in Eclipse IDE + ADT plugin, and run it with Android Virtual Device (AVD). The Eclipse ADT plugin provided easy Android project creation and management, components drag and drop, auto-complete and many useful features to speed up your Android development cycles.
tutorial
Summary steps to develop an Android application :
Install Android SDK
Install ADT Eclipse plugin
Create an Android Virtual Device (AVD)
Create Android Project with Eclipse (Wizard)
Code it…
Start it in Android Virtual Device (AVD)


Tools used in this Example:
JDK 1.6
Eclipse IDE 3.7 , Indigo
Android SDK


Activity lifecycle

An activity can be in different states depending how it is interacting with the user.

Activity state

Running : Activity is visible and interacts with the user.

Paused : Activity is still visible but partially obscured, instance is running but might be killed by the system.
Stopped : Activity is not visible, instance is running but might be killed by the system.
Killed : Activity has been terminated by the system of by a call to its destroy() method.

https://bitbucket.org/meritcampus/android-activity-life-cycle

Merge Two Names

In this example we will merge two names. We create a layout with two EditText fields to take names, and We create an Add Button to perform merge operation. We will learn how to add onClickListeners to a Button, and we will also see how to display the output in a TextView.

Add Two Numbers

In this example, we will add two numbers and display the output. We create a layout with two EditText fields to take the numbers from the user, and We create an Add Button to perform addition operation. We will add onClickListeners to the Button and displays the output in the TextView

ActionBar Menu

Android action bar was introduced to maintain a consistent navigation across the application. It has the powerful capabilities like adapting to screen configurations (landscape & portrait), prioritizing important actions, adding widgets to action bar (search, sharing etc.), providing navigation between screens (drop-down & tabbed navigation) and much more.

In this example, we are going to cover most of the action bar functionality.


Android Flames 

In this example, we will find the FLAMES status between two given names. We create a layout with two EditText fields to take names, and We create an Result Button to perform operation. We will write our logic for calculating FLAMES in onClick() method and displays the result in TextView.

Love Index 

In this example, we will find the Love Index between two names. We create a layout with two EditText fields to take names, and We create an Result Button to perform operation. We will write our logic for calculating love index in onClick() method and displays the result in TextView.

Simple Interest (PTR / 100 )

In this example, we will  find the Simple Interest for the given amount with respect to time and rate of interest. We create a layout with three EditText fields to take the amount, time and rate of interest, we will create a calculate Button to find the Simple Interest. We write our logic in onClick() method. When we click on the calculate button it will automatically goes to onClick() method, in onClick() we get the id's of EditText and Button from resource layout and calculate the Simple Interest and displays the result in TextView.

EMI Calculator

In this example we will  find the EMI for the given loan with respect to loan tenure month and rate of interest. We create a layout with three EditText fields to take the amount, months and rate of interest, we will create a find Button to find the EMI. We write our logic in onClick() method. When we click on the Find button it will automatically goes to onClick() method, in onClick() we get the id's of EditText and Button from resource layout and calculate the EMI and displays the result in TextView.

ListView

One of the UI component we use often is ListView, for example when we need to show items in a vertical scrolling list. One interesting aspect is this component can be deeply customized and can be adapted to our needs. In this example we will analyze the basic concepts behind it and how to use this component.
In order to show items inside the list, this component uses an adapter, so if we want to populate the list we have first create or use existing adapters. Android SDK has some standard adapters that are useful in many cases.
ArrayAdapter : ArrayAdapter uses a Text View to display each item within it. Behind the scenes, it uses the toString() method of each object that it holds and displays this within the TextView. ArrayAdapter has a number of constructors that can be used and the one that you have used in your example is :ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
By default, ArrayAdapter uses the default TextView to display each item. But if you want, you could create your own TextView and implement any complex design you'd like by extending the TextView class. This would then have to go into the layout for your use. You could reference this in the textViewResourceId field to bind the objects to this view instead of the default.

GridView 

Android Grid view is a type of 2-D(Two dimensional) view used to show images into grid thumbnail format. Grid view is also scrollable type view because after adding elements in grid view it will automatically set all these elements into scrollable view. This type of view basically used to show images on small small grid format on a single screen platform. So application user can easily show them equally.

Android grid view gives complete dynamic environment to its developer. App developer can insert multiple images, items into Grid view using list adapter. All you have to need some basic knowledge to use list adapter. Grid view also shows us small images thumbnails like you see in your android image system image gallery. Every image has its own thumbnail.

Spinner

In this example, we will create an Android application with a spinner widget containing a list of countries. On selecting a country from the list, the selected country will be displayed in a TextView widget.
Listining spinner using OnItemSelectedListener.Mind that never use OnItemClickListener for spinner.when you use spinner then set OnItemSelectedListener for get selected item from spinner.you can get Selected value from spinner using getSelectedItem in onItemSelected method.
And onNothingSelected method is called when you choose nothing from spinner.
When you setOnItemSelectedListener to spinner it called when your Activity
start .and its called onItemSelected method.So you can get default selected value from spinner.


TimePicker

In this Example we will see about Android TimePicker Dialog ,we will see an example of selecting Time from Timepicker dialog and display it in the TextView.This dialog will disable the background activity until the user select the time and click ‘ok’ tab of the dialog shown.

Firstly We get the instance of calender class and get the minute and hour of the system and set it to Textview.

DatePicker

Using DatePicker user can set a specific date by setting the day, month and year of Date Picker. In our example  there will be one button 'selectDate'. When user clicks on selectDate it will display a dialog box and user will select the date and will click on 'ok' it will display the date previously selected by user.

https://bitbucket.org/meritcampus/android-date-picker

Camera 

In this example, we will take a look at how to integrate camera with our Android application. Android provides you with 2 options while working with Camera:

Use an existing Camera application
Work with Camera hardware API directly

If you are developing a full fledged camera application, then you need to work with the Camera API directly as it gives you more control but it involves a lot more coding. If you just want to integrate the camera with your app, the first option is better and simpler. In this example, we will learn how to use an existing camera app with our application. We will create a simple application that will take pictures and display the picture in the Acitity using onActitivityResult() method.
In this example, we will show you how to create a calculator application in Android. It will have the following functionality: division, multiplication, subtraction, addition, decimal place, decimal calculations and a cancel button.

Custom ListView

ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list.

In this example, we show you how to create a custom list view with some images, texts... We want to make a list view to store information about a list of movies, in particular each row has to contain: an image of the movie, name of the movie, name of the hero, name of the music director and name of the director.

https://bitbucket.org/meritcampus/android-custom-list-view

Fragment

Fragment is modular section of an activity, which has its own lifecycle, receives its own input events, can be dynamically or statically added to a layout.

To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop() .

Usually, one should implement at least the following lifecycle methods:

onCreate() : The system calls this when creating the fragment. In this call, we can initialize essential components of the fragment that we want to retain when the fragment is paused or stopped, then resumed.

onCreateView() : The system calls this when it’s time for the fragment to draw its user interface for the first time. To draw a UI we must return a View from this method that is the root of fragment’s layout. We can return null if the fragment does not provide a UI.

onPause() : The system calls this method as the first indication that the user is leaving the fragment.

ListFragment

In this example we shall see how to create a simple list fragment that uses array adapter to bind data to items of listview.

Create a class CountryListFragement and extend it to ListFragment .
Inside the onCreateView() method , inflate the view.
Inside the onActivityCreated() method , set adapter to listview and also set the onItemlong click Listener .
Inside the onListItemClick() method , display a toast message with Item name which is being clicked.

Service LifeCycle

A service is a application component used to perform long running tasks in background like  downloading of data from internet, saving multiple records into database, perform file I/O, etc. For such long running tasks, Service is the alternative.
A service doesn’t have any user interface and neither can directly communicate to an activity.
A service can run in the background indefinitely, even if component that started the service is destroyed.
Usually a service always performs a single operation and stops itself once intended task is completed.
A service runs in the main thread of the application instance. It doesn’t create its own thread.
onCreate() : This method is Called when the service is first created
onStartCommand(Intent intent, int flags, int startId) : This method is called when the service is started
onBind(Intent intent) : This method must be called when you want to bind with any activity
onUnbind(Intent intent) : This method is Called when the service will un-binded from activity
onRebind(Intent intent) : This method is called when you want to Re-bind service after calling un-bind method
onDestroy() : This method is called when The service is no longer used and is being destroyed

Intent Service 

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand.The IntentService is used to perform a certain task in the background. Once done, the instance of IntentService terminates itself automatically.

The intentService class provides a method onHandleIntent() which will be asynchronously called by the Android system.

Another interesting aspect is how we can get the values back from the IntentService. As we, already, know the calling activity doesn’t wait for the result, so we have to find another way. Generally speaking there are different ways to solve this problem, in this example we will see how to use ResultReceiver. 

Bound Service

A bound service is an implementation of the Service class that allows other applications to bind to it and interact with it. To provide binding for a service, you must implement the onBind() callback method. This method returns an IBinder object that defines the programming interface that clients can use to interact with the service.
A client can bind to the service by calling bindService(). When it does, it must provide an implementation ofServiceConnection, which monitors the connection with the service. The bindService() method returns immediately without a value, but when the Android system creates the connection between the client and service, it calls onServiceConnected() on the ServiceConnection, to deliver the IBinder that the client can use to communicate with the service.

BroadCast Alarm Notification

Sometimes we need to create an application that notifies a user at a particulartime/date even though the user has not opened the application. The Android SDK provides developers an abstract class called BroadcastReceiver which is used to pass a notification to the user in case any specific event occurs.
In addition, developers can also schedule and add events using theAlarmManager class. As stated in the Android developer’s guide, when an alarm goes off, the Intent that had been registered using AlarmManager is broadcasted by the system, automatically starting the target application if it is not already running.
Using the above concepts, we will now create an Android application that sends a notification message to the user at a particular time (for example: 9:25:00 AM).


Order BroadCast

Broadly there are two major classes of broadcasts:

Normal Broadcasts : Normal broadcasts are not orderly. Therefore, the registered receivers often run all at the same time. This is very efficient, but the Receivers are unable to utilize the results.

Ordered Broadcasts : These Ordered Broadcasts are synchronous, and therefore follow a specific order. The order is defined using android: priority attribute. The receivers with greater priority would receive the broadcast first. In case there are receivers with same priority levels, the broadcast would not follow an order. Each receiver (when it receives the broadcast) can either pass on the notification to the next one, or abort the broadcast completely. On abort, the notification would not be passed on to the receivers next in line.

BroadCast Alarm Manager

Sometimes we need to create an application that notifies a user at a particulartime/date even though the user has not opened the application. The Android SDK provides developers an abstract class called BroadcastReceiver which is used to pass a notification to the user in case any specific event occurs.

In addition, developers can also schedule and add events using the AlarmManager class. As stated in the Android developer’s guide, when an alarm goes off, the Intent that had been registered using AlarmManager is broadcasted by the system, automatically starting the target application if it is not already running.
Using the above concepts, we will now create an Android application that Vibrate the mobile phone.

Sqlite Database Create Table

Android provides several ways to store user and app data. SQLite is one way of storing user data. SQLite is a very light weight database which comes with Android OS.

To create and upgrade a database in your Android application you create a subclass of the SQLiteOpenHelper class. In the constructor of your subclass you call the super() method of SQLiteOpenHelper, specifying the database name and the current database version.

In this class you need to override the following methods to create and update your database.

onCreate() - is called by the framework, if the database is accessed but not yet created.
onUpgrade() - called, if the database version is increased in your application code. This method allows you to update an existing database schema or to drop the existing database and recreate it via the onCreate() method.

Both methods receive an SQLiteDatabase object as parameter which is the Java representation of the database.

The SQLiteOpenHelper class providesthe getReadableDatabase() and getWriteableDatabase() methods to get access to an SQLiteDatabase object; either in read or write mode.


https://bitbucket.org/meritcampus/android-database-create-table

Insert Student Data Into DataBase


DataBaseHelper class defines a method  that accept object that provides values to be inserted into the database. There are two instances of type SQLiteDatabase and ContentValues class types, created respectively. A put() method initializes values to be inserted into the database and insert() method of SQLiteDatabase class is used to insert record into the database that accept three parameters “table-name”, second will remain null and third will be the ContentValues class type instance variable. Once a record is inserted into the database, database connection should be closed using SQLiteDatabase class method close().
https://bitbucket.org/meritcampus/android-student-database


Insert Update Delete Database Example

Insert : Defines a method inside database helper class that accept object that provides values to be inserted into the database. There are two instances of type SQLiteDatabase and ContentValues class types, created respectively. A put() method initializes values to be inserted into the database and insert() method of SQLiteDatabase class is used to insert record into the database that accept three parameters “table-name”, second will remain null and third will be the ContentValues class type instance variable. Once a record is inserted into the database, database connection should be closed using SQLiteDatabase class method close().

Update : The update method of an instance of SQLiteDatabase class updates the data in a row or in multiple rows of a database table. Like with the insert method, you could use the execSQL query to run a SQL UPDATE query, but using the updatemethod is safer.

Delete : The delete method of an instance of the SQLiteDatabase class deletes a row or in multiple rows of a database table. Like with the insert method, you could use the execSQL query to run a SQL UPDATE query, but using the delete method is safer

https://bitbucket.org/meritcampus/android-database-example


Find Latitude and Longitude

In this example you will learn about Geocoding and how to find latitude / longitude for a given address location.
Geocoding is, converting the physical location address to latitude and longitude. Reverse geocoding is finding the location address based on the latitude and longitude.
We should instantiate the Geocoder class and use the method getFromLocationName to get the complete address which includes the latitude and longitude.

https://bitbucket.org/meritcampus/android-latitude-and-longitude


Navigation Drawer Layout

In most of the android applications like Facebook , Gmail ,you tube, amazon kindle , true caller .. etc we have seen a side menu which appears on click of an icon on top left corner or by dragging on to the screen from left to right , so here in this example we shall see how to create the sliding menu for our android applications .
https://bitbucket.org/meritcampus/android-navigation-drawer-layout

Page to Page Navigation

In this example we will learn how to do page to page navigation using android animations
When you start an activity or finish the current activity the transition between the activities can be animated using the method overridePendingTransition. You have to give the resource Id of the animation resource to use for the incoming activity and the outgoing activity. If you don't want to provide any animation just pass 0 instead of the animation resource In this example we will review how to push a new activity screen from the bottom and push out the calling activity from the top. When finished with the called activity we just do the opposite basically the screen drops from the top to the bottom. Also in this example we have the animation resources for sliding the screen from left to right and vice versa. You have to create a folder named anim inside the res folder and drop the animation resources there.

https://bitbucket.org/meritcampus/android-page-to-page-animation


View Flipper

Android provide us many ways through which we can create swiping views, Android ViewFlipper class is one of the such ways. Its not just swiping screen, we can build much more functionality from it like slideshows. Android ViewFlipper’s xml layout has two special attributes which facilitate this function. These attributes are android:autoStart and android:flipInterval, they function as their name suggests, autoStart specifies that whether the ViewFlipping should start automatically or not when view appears. flipInterval specifies the interval between a flip. In this example we will see how to use View Flipper in our Android applications.


No comments:

Post a Comment