Search This Blog

Tuesday, 27 March 2012

Chapter 28:Accessing Data With Android Cursors- Transactions


Accessing Data With Android Cursors

Transactions

SQLite also supports transactions when you need to perform a series of queries that either all complete or all fail. When a SQLite transaction fails an exception will be thrown. The transaction methods are all part of the database object. Start a transaction by calling the beginTransaction() method. Perform the queries and then call the setTransactionSuccessful() when you wish to commit the transaction. Once the transaction is complete call the endTransaction() function.
         db.beginTransaction();
         Cursor cur = null;
         try {
                cur = db.query("tbl_countries", 
                        null, null, null, null, null, null);
                cur.moveToPosition(0);
                ContentValues values = new ContentValues();
                values.put("state_name", "Georgia");
                values.put("country_id", cur.getString(0));
                long stateId = db.insert("tbl_states", null, values);
                db.setTransactionSuccessful();
                view.append("n" + Long.toString(stateId));
         } catch (Exception e) {
                Log.e("Error in transaction", e.toString());
         } finally {
                db.endTransaction();
                cur.close();
         }



Start off with a call to beginTransaction() to tell SQLite to perform the queries in transaction mode. Initiate a try/catch block to handle exceptions thrown by a transaction failure. Perform the queries and then call setTransactionSuccessful() to tell SQLite that our transaction is complete. If an error isn't thrown then endTransaction() can be called to commit the transaction. Finally close the cursor when we're finished with it.

Built in android databases

The Android Operating-System provides several built-in databases to store and manage core phone application data. Before external applications may access some of these data sources access must be granted in the AndroidManifest.xml file in the root of the project. Some of the data applications can access are the bookmarks, media player data, call log, and contact data. Contact data not covered due to changes in the API between 1.x and 2.0 version of Android. See the Android Working With Contacts Tutorial. Android provides built in variables to make working with the internal SQLite databases easy.

Access permissions

Before a program accesses any of the internal Android databases the application must be granted access. This access is granted in the AndroidManifest.xml file. Before the application is installed from the market the user will be prompted to allow the program to access this data.
        <uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
        <uses-permission android:name="com.android.broswer.permission.WRITE_HISTORY_BOOKMARKS" />
        <uses-permission android:name="android.permission.READ_CONTACTS" />
These are some sample uses-permission statements to grant access to internal Android databases. These are normally placed below the uses-sdk statement in the AndroidManifest.xml file. The first 2 grant read and write access to the browser history and bookmarks. The third grants read access to the contacts. We'll need to grant READ access to the bookmarks and contacts for the rest of the code samples to work.

Managed Query

Managed queries delegate control of the Cursor to the parent activity automatically. This is handy as it allows the activity to control when to destroy and recreate the Cursor as the application changes state.
package higherpass.TestingData;

import android.app.Activity;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TextView;
import android.database.Cursor;

public class TestingData extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView view = (TextView) findViewById(R.id.hello);
        Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
                        null, null, null, null
                        );
        mCur.moveToFirst();
        int index = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
        while (mCur.isAfterLast() == false) {
                view.append("n" + mCur.getString(index));
                mCur.moveToNext();
        }
      
    }
}



The managed query functions very similar to the query function we used before. When accessing Android built in databases you should reference them by calling the associated SDK variable containing the correct database URI. In this case the browser bookmarks are being accessed by pointing the managedQuery() statement at android.provider.Browser.BOOKMARKS_URI. We left the rest of the parameters null to pull all results from the table. Then we iterate through the cursor records. Each time through the loop we append the title of the bookmark to the TextView element. If you know the name of a column, but not it's index in the results use the getColumnIndex() method to get the correct index. To get the value of a field use the getString() method passing the index of the field to return.

Bookmarks

The first Android database we're going to explore is the browser bookmarks. When accessing the internal Android databases use the managedQuery() method. Android includes some helper variables in Browser.BookmarkColumns to designate column names. They are Browser.BookmarkColumns.TITLE, BOOKMARK, FAVICON, CREATED, URL, DATE, VISITS. These contain the table column names for the bookmarks SQLite table.
package higherpass.TestingData;

import android.app.Activity;
import android.os.Bundle;
import android.provider.Browser;
import android.widget.TextView;
import android.database.Cursor;

public class TestingData extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView view = (TextView) findViewById(R.id.hello);
        String[] projection = new String[] {
                Browser.BookmarkColumns.TITLE
                , Browser.BookmarkColumns.URL
        };
        Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
                projection, null, null, null
                );
        mCur.moveToFirst();
        int titleIdx = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
        int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.URL);
        while (mCur.isAfterLast() == false) {
                view.append("n" + mCur.getString(titleIdx));
                view.append("n" + mCur.getString(urlIdx));
                mCur.moveToNext();
        }
      
    }
}



No comments:

Post a Comment