Wednesday 29 April 2015

HB Blog 70: Metadata In Android Manifest.

A name-value pair for an item of additional, arbitrary data that can be supplied to the parent component. A component element can contain any number of <meta-data> subelements. The values from all of them are collected in a single Bundle object and made available to the component as the PackageItemInfo.metaData field.
It is mostly used to store set up some app-wide configuration information in an Android app or need to create a class that can be used in multiple projects with a generic way of setting configuration values. This is particularly useful for things like API keys that will probably be different across apps but should be accessible in the same way.

This field can be used to store a boolean, float, int, or String and is later accessed by the Bundle method for your data type.

Refer the below link for complete sample code:-
Download Sample Code
Download Apk File
Have a look on few code snippets, 
AndroidManifest.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.metadata_as" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

       <meta-data android:name="hbdata" android:value="@string/app_name"></meta-data>
    </application>

</manifest> 
 
 
 
MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class MainActivity extends Activity {

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

        getMetadataValue();
    }

    private void getMetadataValue(){
        try {
            ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;
            String metadataValue = bundle.getString("hbdata");
            System.out.println("API KEY : " + metadataValue);
        } catch (Exception e){
            System.out.println("Exception "+e.getMessage());
        }
    }
}

Saturday 25 April 2015

HB Blog 69: Design Patterns In Mobile Development - Android/iOS.

Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects.
Generally, In mobile applications where user interface is most important aspect of development as a developer MVC design pattern is most commonly heard. But, a developer uses multiple design patterns that are suitable for that process and phase. Android latest developed version lollipop as well as devices wearable are more concentrating on design patterns that can make application more resuable and standardize. 

There are many design patterns that used in mobile development. In this post I would try to put how does design pattern are used in Android and iOS mobile development.

Model-View-Controller (MVC) is a software architectural pattern for implementing user interfaces. In Android, database or preferences are model, UI created in xml file is view and java file coding logic is controller. Similarly, in iOS, database or core data is model, UI created in xib or storyboard is view and .m or .h files acts as controller. In MVC pattern most important aspect is that model never communicates with view directly, always controller acts as a middle man.

Singleton design pattern is another important design pattern used in mobile development. In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. In Android, extending application class makes the class singleton. In iOS, sharedInstance is used to return singleton object.

Delegation pattern is a design pattern in object-oriented programming where an object, instead of performing one of its stated tasks, delegates that task to an associated helper object. In Android,
delegation pattern is not directly used but we find it during our listeners(onclick, ontouch, etc.) as well as during startActivityForResult(). In iOS, delegation is most excessively used concept during predefine delegates such as UITextFieldDelegate, etc. as well as custom made delegates.

Observer design pattern in which an object maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. In Android, we hav observer class also observer is seen during LocationListener method onLocationChange() which observes change in location and updates the latitude and longitude. Broadcase reciever is also a part of these pattern. In iOS, Observer is seen in notification as well as KVO(Key-Value Observing).  

Adapter pattern help us to translate one interface to a compatible one. In Android, we can see these pattern during listview adapter such as array adapter, list adapter, cursor adapter, etc. In iOS, we have UITableViewDelegate, UIScrollViewDelegate, etc using adapter design pattern.

Saturday 18 April 2015

HB Blog 68: Midlet Programming.

A MIDlet is an application that uses the Mobile Information Device Profile (MIDP) of the Connected Limited Device Configuration (CLDC) for the Java ME environment. Sun Microsystems uses the "let" suffix to name several different types of programs that fall within the Java technology umbrella. Applets, servlets,etc.

The development process for MIDlet is as follows,
1)Edit 
Sun Java Wireless Toolkit (SJWTK) is an environment used as editore for midlet programming. It is similar to java Applet.
The editor provides all features that are essential to develop midlet program.
2)Compile
Compilation is the process of compiling the Java source files into executable byte code. The compiler of the virtual machine compiles the Java source code.
3)Verification
Before execution process the pre-verification is process is performed. The byte code is verified as security aspect and then signed .jar file is created.
4)Run
Finally, the midelet program is ready to run on MIDP devices.

A MIDlet's main class extends javax.microedition.midlet.MIDlet. The main class defines three life-cycle notification methods: startApp(), pauseApp(), and destroyApp().
There are three possible states in a MIDlet's life-cycle:
Paused: The MIDlet instance has been constructed and is inactive. 
Active: The MIDlet is active. 
Destroyed: The MIDlet has been terminated and is ready for reclamation by the garbage collector.

The startApp() lifecycle method initiates active state whereas, pausedApp() method handles paused state. And destroyApp() method is used to manage destroyed state.

Here is a hello world program for MIDlet application,

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class HelloWorld extends MIDlet implements CommandListener {
    private Command exitCommand;
    private TextBox tbox;

    public HelloWorld() {
        exitCommand = new Command("Exit", Command.EXIT, 1);
        tbox = new TextBox("Hello world MIDlet", "Hello World!", 25, 0);
        tbox.addCommand(exitCommand);
        tbox.setCommandListener(this);
    }

    protected void startApp() {
        Display.getDisplay(this).setCurrent(tbox);
    }

    protected void pauseApp() {}
    protected void destroyApp(boolean bool) {}

    public void commandAction(Command cmd, Displayable disp) {
        if (cmd == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        }
    }
}

Friday 10 April 2015

HB Blog 67: Wireless Application Protocol (WAP) Architecture.

I have been blogging related to Open Systems Interconnection Model (OSI Model). Here, is the link to my post HB Blog 53: Open Systems Interconnection Model (OSI Model).
Similar, to  OSI model we have Wireless Application Protocol (WAP) standard for accessing information over a mobile wireless network. The WAP protocol stack has a multi-layered architecture (this is very similar to the seven layers model of OSI as follows,

1)Application Layer (WAE) - Wireless Application Environment
2)Session Layer (WSP) - Wireless Session Protocol
3)Transaction Layer (WTP) - Wireless Transaction Protocol
4)Security Layer (WTLS) - Wireless Transport Layer Security
5)Transport Layer (WDP) - Wireless Datagram Protocol
6)Bearer Layer (GSM, CDMA, GPRS, etc.)

Application Layer
The WAE provides a general purpose application environment based on a combination of WWW and Mobile Telephony technologies. The primary objectives is to establish an interoperable environment that will allow operators and service providers to build applications and services that can reach a wide variety of different wireless platforms containing the various functionalities such as Wireless Markup language(WML), WML Script, Wireless Telephony Application etc.

Session Layer
Wireless Session Protocol (WSP) is an open standard for maintaining high level session. Wireless session is nothing but a normal Web browsing session that starts when the user connects to one URL and ends when the user leaves that URL.

Transaction Layer
Wireless transaction protocol is a layer of the Wireless Application Protocol (WAP) that is intended to bring Internet access to mobile phones. WTP provides functions to similar to TCP,except that WTP has reduced amount of information needed for each transaction. WTP saves processing and memory cost as compared to TCP. It Supports 3 types of transaction : 1.Unreliable One-Way Request 2.Reliable One-Way Request 3.Reliable Two-Way request.The WTP runs on top of a datagram service such as User Datagram Protocol (UDP) and is part of the standard suite of TCP/IP protocols used to provide a simplified protocol suitable for low bandwidth wireless stations.

Security Layer
The Wireless Transport Layer Security is the layer that handles security of data and validity of data between two communicating to manage, start, and finish security issues between two portable devices. WTLS incorporates security features that are based upon the established Transport Layer Security (TLS) protocol standard. It includes data integrity checks, privacy, service denial, and authentication services.

Transport Layer
Wireless Datagram Protocol defines the movement of information from receiver to the sender and resembles the User Datagram Protocol in the Internet protocol suite. The Wireless Datagram Protocol (WDP), a protocol in WAP architecture, covers the Transport Layer Protocols in the Internet model. The WDP presents a consistent data format to the higher layers of the WAP protocol stack, thereby offering the advantage of bearer independence to application developers.

Bearer Layer
The bearers of WAP are the products or other types of medium that implements WAP in their network and in their technology, such as GSM, CDMA, GPRS, etc.

Friday 3 April 2015

HB Blog 66: Android Persistent Application Storage.

Storing data has always been a important factor of every programming platforms. In Android specifically, there are several options for you to save persistent application data as follows,

Shared Preferences
    Store private primitive data in key-value pairs.
Internal Storage
    Store private data on the device memory.
External Storage
    Store public data on the shared external storage.
SQLite Databases
    Store structured data in a private database.
Network Connection
    Store data on the web with your own network server.

Shared Preferences is simply and editor which allows to store data in key-value pair. It is generally managed by getters and setters.You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. 
To write values:
    Call edit() to get a SharedPreferences.Editor.
    Add values with methods such as putBoolean() and putString().
    Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().

Internal storage allows to store data on device memory and it is used for private data.
To create and write a private file to the internal storage:
    Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.
    Write to the file with write().
    Close the stream with close().
To read a file from internal storage:
    Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
    Read bytes from the file with read().
    Then close the stream with close().

External storage is the storage place provided on sd-card. The data is public and can be accces by users directly.In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions.
Below is the code snippet, to save database file to Sd-Card,
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 public static void saveDatabaseToSdcard(Context context) {
        try {
            InputStream myInput = new FileInputStream("/data/data/com.example/databases/" + "MyDB.db");

            File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + "MyDB.db");
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                }
            }

            OutputStream myOutput = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + "MyDB.db");

            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }

            //Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
        } catch (Exception e) {
        }
    }

SQLite Databases allows to store structured data in a private database. SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database.

Network Connection allows to store data on the web with your own network server. To store and retrieve data web-based services can be written. To do network operations, use classes in the following packages,

    java.net.*
    android.net.*