Saturday, December 13, 2014

ViewGroups

ViewGroup

One or more views can be grouped together into a ViewGroup

A ViewGroup (which is itself a special type of view) provides the layout in which you can order the appearance and sequence of views

A ViewGroup derives from the base class android.view.ViewGroup

LinearLayout
AbsoluteLayout
TableLayout
RelativeLayout
FrameLayout
ScrollView

LinearLayout

The LinearLayout arranges views in a single column or a single row.
Default orientation is horizontal


using layout_gravity and layout_weight:

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






Absolute Layout

The AbsoluteLayout enables you to specify the exact location of its children.

However, there is a problem with the AbsoluteLayout when the activity is viewed on a highresolution
screen. For this reason, the AbsoluteLayout has been deprecated since Android 1.5

TableLayout

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

The RelativeLayout enables you to specify how child views are positioned relative to each other.

FrameLayout

The FrameLayout is a placeholder on screen that you can use to display a single view.

Views that you add to a FrameLayout are always anchored to the top left of the layout.

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


Saturday, September 27, 2014

IntentService

IntentService allows execution of asynchronous Tasks on Separate Threads.

It is important to note that once your service has finished executing a task, it should be stopped as soon as possible so that it does not unnecessarily hold up valuable resources.

Unfortunately, a lot of developers often forgot to terminate a service when it is done performing its task.

It executes its task within a worker thread and terminates itself when the task is completed

    public void startService(View view)
    {
    startService(new Intent(getBaseContext(), MyIntentService.class));
    }

public class MyIntentService extends IntentService 
{

public MyIntentService(String name) {
super("MyIntentServiceName");
// TODO Auto-generated constructor stub
}

protected void onHandleIntent(Intent intent)
{
try
{
int result = downloadFile(new URL("http://www.amazon.com/somefile.pdf"));
}catch(MalformedURLException e)
{
e.printStackTrace();
}
}

private int downloadFile(URL url)
{
try
{
Thread.sleep(5000);
}catch(InterruptedException e)
{
e.printStackTrace();
}

return 100;
}
}    

Friday, September 12, 2014

Context Object

Activity class is a subclass of Context, you can use the this keyword to represent the Context object.

Instances of the Context class are often used to provide references to your application.

Context 
    ^
    |
    |
Activity

When creating a view dynamically in an activity.
The constructor for the TextView class takes a Context object.

TextView tv = new TextView(this);


Because the Toast() class is not used directly in the activity (it is used within the AlertDialog class), you need to return an instance of the Context class by using the getBaseContext() method.

.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT)
.show();
}


Saturday, August 30, 2014

Native Android Content Providers

Android exposes several native databases using Content Providers
Android.provider package includes classes that can simplify access to many of the most useful providers

Browser
Browser Content Provider to read or modify bookmarks, browser history, or web searches

CallLog
View or update the call history, including both incoming and outgoing calls, together with missed calls and call details like caller ID and call durations

ContactsContract
to retrieve, modify, or store your contacts’ details

MediaStore
centralized, managed access to the multimedia on your device, including audio, video, and images

Settings
access the device’s preferences using the Settings provider

UserDictionary
Access (or add to) the user defined words added to the dictionary for use in IME predictive text input


Using the Media Store Provider

The MediaStore class includes Audio, Video, and Images subclasses, which in turn contain subclasses that are used to provide the column names and content URIs for each media provider

The Media Store segregates media kept on the internal and external volumes of the host device

MediaStore.<mediatype>.Media.EXTERNAL_CONTENT_URI
MediaStore.<mediatype>.Media.INTERNAL_CONTENT_URI

// Get a cursor over every piece of audio on the external volume.
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                                           null, null, null, null); 

// Let the activity manage the cursor lifecycle.
startManagingCursor(cursor);

// Use the convenience properties to get the index of the columns
int albumIdx = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM); 
int titleIdx = cursor. getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);

String[] result = new String[cursor.getCount()];
if (cursor.moveToFirst())
  do { 
    // Extract the song title.
    String title = cursor.getString(titleIdx);
    // Extract the album name.
    String album = cursor.getString(albumIdx);

    result[cursor.getPosition()] = title + " (" + album + ")";
  } while(cursor.moveToNext());

Using the Contacts Provider

Android exposes  all the information available from the contacts database to any application granted the READ_CONTACTS permission

Introducing the Contacts Contract Content Provider

Reading Contact Details

Modifying and Augmenting Contact Details


Friday, August 29, 2014

Content Provider

Database is accessible to only the package that created it.

Android's way of sharing data across packages is through the use of content providers.

A content provider behaves very much like a database - you can query it, edit its contents, as well as add or delete content.

The data can be stored in a database, in files, or even over a network.

Android ships with many useful content providers

Browser : Stores data such as browser bookmarks, browser history, and so on
CallLog : Stores data such as missed calls, call details, and so on
Contacts : Stores contact details
MediaStore : Stores media fi les such as audio, video, and images
Settings : Stores the device’s settings and preferences

Querying a content provider

To query a content provider, you specify the query string in the form of a URI, with an optional
specifier for a particular row.

<standard_prefix>://<authority>/<data_path>/<id>

standard_prefix
The standard prefix for content providers is always content://

authority
The authority specifies the name of the content provider
Eg:
     contacts: Built-in contacts provider
     <fully qualified name>: for third party content providers

data_path
The data path specifies the kind of data requested
Eg.
    people: content://contacts/people

id
The id specifies the specific record requested
Eg.
content://contacts/people/2

Example Query Strings:

content://media/internal/images
content://media/external/images
content://call_log/calls
content://browser/bookmarks

Predefined Query String Constants

you can use a list of predefi ned query string constants in Android to specify the URI for the different data types.

Uri allContacts = Uri.parse(“content://contacts/people”);

Uri allContacts = ContactsContract.Contacts.CONTENT_URI;

Some examples of predefi ned query string constants

Browser.BOOKMARKS_URI
Browser.SEARCHES_URI
CallLog.CONTENT_URI
MediaStore.Images.Media.INTERNAL_CONTENT_URI
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
Settings.CONTENT_URI

To access the phone number of a contact, you need to query against the URI stored in ContactsContract.CommonDataKinds.Phone.CONTENT_URI

https://github.com/coderetriever/Android/tree/master/Provider

Projections

Specify the exact columns to return by creating an array containing the names of the column to return

Cursor c = managedQuery(allContacts, projection, null, null, null);

CursorLoader cursorLoader = new CursorLoader(this, allContacts, projection, null, null, null);
Cursor c = cursorLoader.loadInBackground();

String[] projection = new String[]
{ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER};

Filtering 

SQL WHERE clause to filter the result of the query

third and fourth parameters
c = managedQuery(allContacts, projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ‘%Lee’”, null, null);

Cursor c;
if (android.os.Build.VERSION.SDK_INT <11) {
//---before Honeycomb---
c = managedQuery(allContacts, projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ?”,
new String[] {“%Lee”}, null);

fourth and fifth parameters
CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ‘%Lee’”,
null ,
null);
c = cursorLoader.loadInBackground();

CursorLoader cursorLoader = new CursorLoader(
this,
allContacts,
projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ?”,
new String[] {“%Lee”},
null);
c = cursorLoader.loadInBackground();

Sorting

SQL ORDER BY clause to sort the result of the query

last parameter of managedQuery
c = managedQuery(allContacts, projection,
ContactsContract.Contacts.DISPLAY_NAME + “ LIKE ?”,
new String[] {“%Lee”},
ContactsContract.Contacts.DISPLAY_NAME + “ ASC”);

Creating a custom content provider

To create a new Content Provider, extend the abstract ContentProvider class.

Override the onCreate method to create (and initialize) the underlying data source you’re planning to publish with this provider

import android.content.*;
import android.database.Cursor;
import android.net.Uri;
import android.database.SQLException;

public class MyProvider extends ContentProvider {

  @Override
  public boolean onCreate() {
    // TODO Construct the underlying database.
    return true;
  }
}

Expose a public static CONTENT_URI property that returns the full URI of this provider

content://com.<CompanyName>.provider.<ApplicationName>/<DataPath>

Content URIs can represent either of two forms:

Request for all values of that type (in this case all elements)
content://com.paad.provider.myapp/elements

Request for a single record
content://com.paad.provider.myapp/elements/5

It’s good practice to support access to your provider for both of these forms. The simplest way to do this is to use a UriMatcher

Using the UriMatcher to handle single or multiple query requests

public class MyProvider extends ContentProvider {

  private static final String myURI = "content://com.paad.provider.myapp/items";
  public static final Uri CONTENT_URI = Uri.parse(myURI);

  @Override
  public boolean onCreate() {
    // TODO: Construct the underlying database.
    return true;
  }

  // Create the constants used to differentiate between the different URI 
  // requests.
  private static final int ALLROWS = 1;
  private static final int SINGLE_ROW = 2;
  
  private static final UriMatcher uriMatcher;

  // Populate the UriMatcher object, where a URI ending in 'items' will correspond to a request for all items, and 'items/[rowID]' represents a single row.
  static {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI("com.paad.provider.myApp", "items", ALLROWS);
    uriMatcher.addURI("com.paad.provider.myApp", "items/#", SINGLE_ROW);
  }
}

You can use the same technique to expose alternative URIs for different subsets of data

Exposing Access to the Data Source

Expose queries and transactions on your Content Provider by implementing the delete, insert, update, and query methods
These methods are the interface used by the Content Resolver to access the underlying data

Defining the MIME type that identifies the data the provider returns.
Override the getType method to return a String that uniquely describes your data type
Single item vnd.<companyname>.cursor.item/<contenttype>
All items vnd.<companyName>.cursor.dir/<contenttype>

@Override
public Cursor query(Uri uri, 
                    String[] projection, 
                    String selection, 
                    String[] selectionArgs, 
                    String sort) {
      
  // If this is a row query, limit the result set to the passed in row.        
  switch (uriMatcher.match(uri)) {
    case SINGLE_ROW : 
      // TODO: Modify selection based on row id, where:
      // rowNumber = uri.getPathSegments().get(1));
  }
  return null;
}

@Override
public Uri insert(Uri _uri, ContentValues _initialValues) {
  long rowID = [ ... Add a new item ... ]
        
  // Return a URI to the newly added item.
  if (rowID > 0) {
    return ContentUris.withAppendedId(CONTENT_URI, rowID);
  }
  throw new SQLException("Failed to add new item into " + _uri);
}

@Override
public int delete(Uri uri, String where, String[] whereArgs) {
  switch (uriMatcher.match(uri)) {
    case ALLROWS: 
    case SINGLE_ROW:
    default: throw new IllegalArgumentException("Unsupported URI:" + uri);
  }
}

@Override
public int update(Uri uri, ContentValues values, String where, String[] 
whereArgs) {
  switch (uriMatcher.match(uri)) {
    case ALLROWS: 
    case SINGLE_ROW:
    default: throw new IllegalArgumentException("Unsupported URI:" + uri);
  }
}

@Override
public String getType(Uri _uri) {
  switch (uriMatcher.match(_uri)) {
    case ALLROWS: return "vnd.paad.cursor.dir/myprovidercontent";
    case SINGLE_ROW: return "vnd.paad.cursor.item/myprovidercontent";
    default: throw new IllegalArgumentException("Unsupported URI: " + _uri);
  }
}

Registering Your Provider

Once you have completed your Content Provider, it must be added to the application manifest.

Use the authorities tag to specify its base URI,

<provider android:name="MyProvider" android:authorities="com.paad.provider.myapp"/>

USING CONTENT PROVIDERS

Each application Context includes a ContentResolver instance

ContentResolver cr = getContentResolver();

Querying for Content

Using the query method on the ContentResolver object, pass in:

The URI of the Content Provider data you want to query
A projection that lists the columns you want to include in the result set\
A where clause that defines the rows to be returned. an include ? wildcards that will be
replaced by the values passed into the selection argument parameter
An array of selection argument strings that will replace the ?s in the where clause
A string that describes the order of the returned rows

ContentResolver cr = getContentResolver();

// Return all rows
Cursor allRows = cr.query(MyProvider.CONTENT_URI, null, null, null, null);

// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor someRows = cr.query(MyProvider.CONTENT_URI, 
                           null, where, null, order);

Adding, Updating, and Deleting Content

To perform transactions on Content Providers, use the delete, update, and insert methods on the ContentResolver object.

Inserts

// Get the Content Resolver
ContentResolver cr = getContentResolver();

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();

// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]

Uri myRowUri = cr.insert(MyProvider.CONTENT_URI, newValues);

// Create a new row of values to insert.
ContentValues[] valueArray = new ContentValues[5];

// TODO: Create an array of new rows
int count = cr.bulkInsert(MyProvider.CONTENT_URI, valueArray);

Deletes

ContentResolver cr = getContentResolver();

// Remove a specific row.
cr.delete(myRowUri, null, null);
// Remove the first five rows.
String where = "_id < 5";
cr.delete(MyProvider.CONTENT_URI, where, null);

Updates

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();

// Create a replacement map, specifying which columns you want to
// update, and what values to assign to each of them.
newValues.put(COLUMN_NAME, newValue);

// Apply to the first 5 rows.
String where = "_id < 5";

getContentResolver().update(MyProvider.CONTENT_URI, newValues, where, null);

Accessing Files in Content Providers

Content Providers represent files as fully qualified URIs rather than as raw file blobs

// Insert a new row into your provider, returning its unique URI.
Uri uri = getContentResolver().insert(MyProvider.CONTENT_URI, newValues);

try {
  // Open an output stream using the new row's URI.
  OutputStream outStream = getContentResolver().openOutputStream(uri);
  // Compress your bitmap and save it into your provider.
  sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
}
catch (FileNotFoundException e) { }


SQLite

Android databases are stored in the /data/data/<package_name>/databases folder on your device

By default all databases are private, accessible only by the application that created them

SQLite is a well regarded relational database management system (RDBMS).

SQLite differs from many conventional database engines by loosely typing each column, meaning that column values are not required to conform to a single type

https://github.com/coderetriever/Android/tree/master/Databases

Introducing the SQLiteOpenHelper

SQLiteOpenHelper is an abstract class used to implement the best practice pattern for creating, opening, and upgrading databases

The onCreate() method creates a new database if the required database is not present.

The onUpgrade() method is called when the database needs to be upgraded.

  private static class myDbHelper extends SQLiteOpenHelper {
    public myDbHelper(Context context, String name, 
                      CursorFactory factory, int version) {
      super(context, name, factory, version);
    }

    // Called when no database exists in disk and the helper class needs to create a new one. 
    @Override
    public void onCreate(SQLiteDatabase _db) {
      _db.execSQL(DATABASE_CREATE);
    }

    // Called when there is a database version mismatch meaning that the version of the database on disk needs to be upgraded to the current version.
    @Override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
      // Log the version upgrade.
      Log.w("TaskDBAdapter", "Upgrading from version " + 
                             _oldVersion + " to " +
                             _newVersion + ", which will destroy all old data");
        
      // Upgrade the existing database to conform to the new version. Multiple previous versions can be handled by comparing _oldVersion and _newVersion values.

      // The simplest case is to drop the old table and create a new one.
      _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
      // Create a new one.
      onCreate(_db);
    }
  }
}

dbHelper = new myDbHelper(context, DATABASE_NAME, null, DATABASE_VERSION);

SQLiteDatabase db;
try {
  db = dbHelper.getWritableDatabase();
}
catch (SQLiteException ex){
  db = dbHelper.getReadableDatabase();

} 

Opening and Creating Databases without SQLiteHelper

Setting up a database is a two-step process
  • First call openOrCreateDatabase to create the new database
  • Then call execSQL on the resulting database instance to run the SQL commands that will create your tables and their relationships

        private static final String DATABASE_NAME = "myDatabase.db";
private static final String DATABASE_TABLE = "mainTable";

private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " ( _id integer primary key autoincrement,"
+ "column_one text not null);";

SQLiteDatabase myDatabase;

private void createDatabase() {
myDatabase = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE,
null);
myDatabase.execSQL(DATABASE_CREATE);
}

Querying a Database

Each database query is returned as a Cursor. Think of the Cursor as a pointer to the result set from a database query

To execute a query on a database use the query method
  • should contain only unique values?
  • The name of the table to query
  • lists the columns to include in the result set
  • A ‘‘where’’ clause that defines the rows to be returned. can include ? wildcards that will be replaced by the values passed in through the selection argument parameter
  • An array of selection argument strings that will replace the ?’s in the where clause
  • A ‘‘group by’’ clause that defines how the resulting rows will be grouped
  • A ‘‘having’’ filter that defines which row groups to include if you specified a group by clause
  • A string that describes the order of the returned rows
  • An optional string that defines a limit for the number of returned rows

// Return all rows for columns one and three, no duplicates
String[] result_columns = new String[] {KEY_ID, KEY_COL1, KEY_COL3};
Cursor allRows = myDatabase.query(true, DATABASE_TABLE, result_columns,
null, null, null, null, null, null);
// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor myResult = myDatabase.query(DATABASE_TABLE, null, where,
null, null, null, order)

Extracting Results from a Cursor

Cursors are pointers to the result set within the underlying data. Cursor class includes a number of navigation functions.

moveToFirst
moveToNext
moveToPrevious
getCount
getColumnIndexOrThrow
getColumnName
getColumnNames
moveToPosition
getPosition

The startManagingCursor method integrates the Cursor’s lifetime into the calling Activity’s. When you’ve finished with the Cursor, call stopManagingCursor to do just that.

First use the moveTo<location> methods to position the cursor at the correct row of the result Cursor
Then use the type safe get<type> methods (passing in a column index) to return the value

String columnValue = myResult.getString(columnIndex);

int GOLD_HOARDED_COLUMN = 2;
Cursor myGold = myDatabase.query("GoldHoards", null, null, null, null, null, null);
float totalHoard = 0f;
// Make sure there is at least one row.
if (myGold.moveToFirst()) {
// Iterate over each cursor.
do {
float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);
totalHoard += hoard;
} while(myGold.moveToNext());
}
float averageHoard = totalHoard / myGold.getCount();

Content Values

ContentValues are used to insert new rows into tables.

Its put() method enables you to insert keys with values of different data types.

Adding, Updating, and Removing Rows

The SQLiteDatabase class exposes insert, delete, and update methods that encapsulate the SQL statements required to perform these actions

The execSQL method lets you execute any valid SQL on your database tables

Any time you modify the underlying database values, you should call refreshQuery on each Cursor that has a view on the affected table

Inserting New Rows

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
// Insert the row into your table
myDatabase.insert(DATABASE_TABLE, null, newValues);

Updating a Row

Call update on the database, passing in the table name, the updated Content Values object, and a where clause that specifies the row(s) to update

// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
String where = KEY_ID + "=" + rowId;
// Update the row with the specified index with the new values.
myDatabase.update(DATABASE_TABLE, newValues, where, null);

Deleting Rows

specifying the table name and a where clause

myDatabase.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null);

Upgrading the Database

Sometimes, after creating and using the database, you may need to add additional tables, change
the schema of the database, or add columns to your tables. In this case, you need to migrate your
existing data from the old database to a newer one

To upgrade the database, change the DATABASE_VERSION constant to a value higher than the
previous one.

static final int DATABASE_VERSION = 2;

Pre-Creating the Database

In real-life applications, sometimes it would be more effi cient to pre-create the database at design
time rather than runtime.

To pre-create a SQLite database, you can use SQLite Database Browser

With the database created at design time, the next thing you should do is bundle it together with
your application so that you can use it in your application

NOTE Note that a filename for files added to the assets folder must be in
lowercase letters. As such, a filename such as MyDB is invalid, whereas mydb is fine.

When the activity is created, you copy the database fi le located in the assets folder into the /data/
data/net.learn2develop.Databases/databases/ folder on the Android device

You copy the database fi le only if it does not exist in the destination folder