Using a Bean Data Control in Oracle ADF 11g

Hi All, here is small tutorial in Oracle ADF technology, how to use Data Controls. Basically there are three different types of data controls in ADF

  • Bean Data Control
  • URL service Data Control
  • PlaceHolder Data Control

In this tutorial i am going to elaborate on Bean Data control.this tutorial shows a simple databound application using JavaBeans and Oracle ADF Faces.

Step 1: Create a New Application and Project

From the main menu, choose File > New. In the New Gallery, expand the General category and select Applications. Then in the Items list, select Custom Application and click OK.

new_project

2. To follow along with the example, enter DataBoundADF as the application name and click Next.
3. Enter Model as the project na
4. Click Finish.

The Projects panel in the Application Navigator should look like this:
Model

Step 2: Create a Simple JavaBean Class

In the Application Navigator, right-click the project you just created and choose New > General > Java Class, then click OK.

new_javaclass

2.In the Create Java Class dialog, enter Contact as the class name, and com.spark.adf.tutorial as the package name. Accept the default values and click OK.

3.In the source editor, add code to create a simple JavaBean class.

package com.spark.adf.tutorial;

/**
 * @author Pavan Kumar Mantha
 */
public class Contact {

    private String name;
    private String email;

    public Contact() {
        super();
    }

    public Contact(String name, String email) {
        this.name = name;
        this.email = email;
    }

    /**
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *
     * @return
     */
    public String getName() {
        return name;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }
}

Click saveall icon Save All to save your work.

In the Application Navigator, you should see Contact.java in the com.spark.adf.tutorial package in the Application Sources folder.

Step 3: Create a Service Class

In the Application Navigator, right-click the Model project and choose New > General > Java Class, then click OK.

In the Create Java Class dialog, enter AddressBook as the class name. Accept the package name as com.spark.adf.tutorial.service, and the remaining default values, then click OK.

3.In the source editor, add code to create a collection Java class.
Delete all the generated code and replace with the following code:

package com.spark.adf.tutorial.service;


import com.spark.adf.tutorial.Contact;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Pavan Kumar Mantha
 */
public class AddressBook {

    List<Contact> contacts = new ArrayList<Contact>();

    public AddressBook() {
        super();
        contacts.add(new Contact("Steve", "steve@acme.org"));
        contacts.add(new Contact("Charles", "cyoung@acme.org"));
        contacts.add(new Contact("Karl", "kheint@acme.org"));
        contacts.add(new Contact("Mik", "mik_meir@acme.org"));
        contacts.add(new Contact("Yvonne", "yvonne_yvonne@acme.org"));
        contacts.add(new Contact("Sung", "superstar001@acme.org"));
        contacts.add(new Contact("Shailyn", "spatellina@acme.org"));
        contacts.add(new Contact("John", "jjb@acme.org"));
        contacts.add(new Contact("Ricky", "rmartz@acme.org"));
        contacts.add(new Contact("Shaoling", "shaoling@acme.org"));
        contacts.add(new Contact("Olga", "olga077@acme.org"));
        contacts.add(new Contact("Ron", "regert@acme.org"));
        contacts.add(new Contact("Juan", "jperen@acme.org"));
        contacts.add(new Contact("Uday", "udaykum@acme.org"));
        contacts.add(new Contact("Amin", "amin@acme.org"));
        contacts.add(new Contact("Sati", "sparek@acme.org"));
        contacts.add(new Contact("Kal", "kalyane.kushnane@acme.org"));
        contacts.add(new Contact("Prakash", "prakash01@acme.org"));
    }

    public List<Contact> findAllContacts() {
        return contacts;
    }

    public List<Contact> findContactByName(String name) {

        String namePattern = ".*" + (name != null ? name.toUpperCase() : "") + ".*";
        List<Contact> l_contacts = new ArrayList<Contact>();
        for (Contact contact : contacts) {
            if (Pattern.matches(namePattern, contact.getName().toUpperCase())) {
                l_contacts.add(contact);
            }
        }
        return l_contacts;
    }
}

4. Click saveall icon Save All to save your work.

Step 4: Create a Data Control for the Service Class
1. In the Application Navigator, right-click AddressBook.java and choose Create Data Control.

DataControls

2.In the Bean Data Control Interface Chooser dialog, click OK without selecting an option.

JDeveloper adds the data control definition file (DataControls.dcx ) to the project, and opens the file in the overview editor.
dcx_overview

3.In the Application Navigator, expand the Data Controls panel, then expand AddressBook.
DataControls

Step 5: Create a JSF Page

1. From the main menu, choose File > New > General > Projects > Custom Project, then click OK.

new_genproj

2. Enter View as the project name. Then select ADF Faces from the Available list and shuttle icon shuttle it to the Selected list.

3. Click Finish.
You should see the View project in the Application Navigator.

4. In the Application Navigator, right-click the View project and choose New > Web Tier > JSF/Facelets > Page, then click OK

5. In the Create JSF Page dialog, enter ContactList.jsf as the file name. Make sure Facelets is the selected document type.

6. On the Page Layout page, select Blank Page. On the Managed Bean page, select Do Not Automatically Expose UI Components in a Managed Bean.

7. Click OK.
By default JDeveloper displays the new JSF Facelets page in the visual editor.

8. In the Component Palette, ADF Faces page, Layout panel, drag borderlayout icon Panel Stretch Layout and drop it on the blank page in the visual editor.

When you drag the component to the visual editor, you should see a target rectangle with the name Form on the page; this means the component you are dragging will be inserted inside that target component.

9. click save all icon to save the work.

Step 6: Bind an ADF Faces Table Component to the Service Bean
1. In the Data Controls panel, expand AddressBook, then expand findAllContacts().

dcpalette3

2. Click and drag Contact to the center facet on the page in the visual editor. From the Create context menu, choose Table > ADF Read-only Table.

createcontextmenu

3. In the Edit Table Columns dialog, select Enable Sorting.edittablecols

4. Accept the default values and click OK.
The page in the visual editor should look similar to this:

tableineditor

5.In the Application Navigator, right-click ContactList.jsf and choose Run.

If the Create Default Domain dialog displays, enter the default password, for example weblogic1, in the Password and Confirm Password fields, then click OK.

The page in the browser should look similar to this:
tableinbrowser1

I will teach how to bind “Bind to a Parameterized Method and a Parameter” in my next post.
Happy ADF data binding. 🙂

Handling SQLite Database from Android Programatically

Hi guys, first of all let me wish you all “A very Happy New Year”, i was working on a android project from couple of week ends so thought of putting it on my blog so that it can help some one and save his time.Android provides several ways to store user and application data. SQLite is one way of the way to store user data. SQLite is very light weight database which comes with Android OS. In this tutorial I’ll be discussing how to write classes to handle all SQLite operations.

Note: please follow the comments in the code carefully, this article is pretty simple
please find the below is the structure for the table.

AcctNo, Acct Holder Name, Acct Type, Bank Name, Created Date, amount

in order to hold the data between calls we can create the same old POJO classes, below is the OpeningBalance bean

/**
 * 
 */
package com.spark.android.pocketpassbook.model;

/**
 * @author Sony
 * 
 */
public class OpeningBalanceModel {

	private String acctNo;
	private String bankName;
	private String acctHdrName;
	private String acctType;
	private String openingDate;
	private String amount;

	/**
	 * @return the acctNo
	 */
	public String getAcctNo() {
		return acctNo;
	}

	/**
	 * @param acctNo
	 *            the acctNo to set
	 */
	public void setAcctNo(String acctNo) {
		this.acctNo = acctNo;
	}

	/**
	 * @return the bankName
	 */
	public String getBankName() {
		return bankName;
	}

	/**
	 * @param bankName
	 *            the bankName to set
	 */
	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	/**
	 * @return the acctHdrName
	 */
	public String getAcctHdrName() {
		return acctHdrName;
	}

	/**
	 * @param acctHdrName
	 *            the acctHdrName to set
	 */
	public void setAcctHdrName(String acctHdrName) {
		this.acctHdrName = acctHdrName;
	}

	/**
	 * @return the acctType
	 */
	public String getAcctType() {
		return acctType;
	}

	/**
	 * @param acctType
	 *            the acctType to set
	 */
	public void setAcctType(String acctType) {
		this.acctType = acctType;
	}

	/**
	 * @return the openingDate
	 */
	public String getOpeningDate() {
		return openingDate;
	}

	/**
	 * @param openingDate
	 *            the openingDate to set
	 */
	public void setOpeningDate(String openingDate) {
		this.openingDate = openingDate;
	}

	/**
	 * @return the amount
	 */
	public String getAmount() {
		return amount;
	}

	/**
	 * @param amount
	 *            the amount to set
	 */
	public void setAmount(String amount) {
		this.amount = amount;
	}

}

once we are done with the bean class, now its time to write the database class, which can directly handle the SQLite db. now in order to handle all database CRUD(Create, Read, Update and Delete) operations we need to write our own class which will extend from a super class SQLiteOpenHelper

/**
 * 
 */
package com.spark.android.pocketpassbook.dbhandlers;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.spark.android.pocketpassbook.model.OpeningBalanceModel;

/**
 * @author Sony
 * 
 */
public class DatabaseHandler extends SQLiteOpenHelper {

	// All Static variables
	// Database Version
	private static final int DATABASE_VERSION = 1;

	// Database Name
	private static final String DATABASE_NAME = "pocket_passbook";

	// opening_balance table name
	private static final String TABLE_OPENING_BALANCE = "opening_balance";

	// opening_balance table Columns names
	private static final String KEY_ID = "id";
	private static final String BANK_NAME = "bank_name";
	private static final String ACCT_HDR_NAME = "aact_hdr_name";
	private static final String ACCT_NUM = "aact_num";
	private static final String ACCT_TYPE = "aact_type";
	private static final String OPENING_DATE = "opening_date";
	private static final String AMOUNT = "amount";

	public DatabaseHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	//onCreate method will be called for the first time in the application is deployed 
	@Override
	public void onCreate(SQLiteDatabase sqLiteDatabase) {

		String CREATE_OPENING_BAL_TABLE = "CREATE TABLE IF NOT EXISTS "
				+ TABLE_OPENING_BALANCE + "(" + KEY_ID
				+ " INTEGER PRIMARY KEY AUTOINCREMENT," + BANK_NAME + " TEXT,"
				+ ACCT_HDR_NAME + " TEXT," + ACCT_NUM + " TEXT," + ACCT_TYPE
				+ " TEXT," + OPENING_DATE + " TEXT" + ")";

		sqLiteDatabase.execSQL(CREATE_OPENING_BAL_TABLE);
	}

	// onUpgrade is called once there is a change in structure of the table
 	@Override
	public void onUpgrade(SQLiteDatabase sqLiteDatabase, int arg1, int arg2) {

		// Drop older table if existed
		sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_OPENING_BALANCE);

		// Create tables again
		onCreate(sqLiteDatabase);
	}

	public void deleteTable(String param) {

		SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
		if (param.equalsIgnoreCase("delete")) {
			// DELETE DATA FROM table if existed
			sqLiteDatabase.execSQL("DELETE FROM " + TABLE_OPENING_BALANCE);
			// Create tables again
			onCreate(sqLiteDatabase);
		} else if (param.equalsIgnoreCase("drop")) {
			// Drop older table if existed
			sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "
					+ TABLE_OPENING_BALANCE);
			// Create tables again
			onCreate(sqLiteDatabase);
		}

	}

	// Adding new opening balance data
	public boolean addOpeningBalance(OpeningBalanceModel openingBalanceModel) {
		boolean status;
		try {
			SQLiteDatabase db = this.getWritableDatabase();

			ContentValues values = new ContentValues();
			values.put(BANK_NAME, openingBalanceModel.getBankName());
			values.put(ACCT_HDR_NAME, openingBalanceModel.getAcctHdrName());
			values.put(ACCT_NUM, openingBalanceModel.getAcctNo());
			values.put(ACCT_TYPE, openingBalanceModel.getAcctType());
			values.put(OPENING_DATE, openingBalanceModel.getOpeningDate());
			//values.put(AMOUNT, openingBalanceModel.getAmount());

			// Inserting Row
			db.insert(TABLE_OPENING_BALANCE, null, values);
			db.close(); // Closing database connection
			status = true;
		} catch (Exception e) {
			status = false;
			e.printStackTrace();
		}
		return status;
	}

	// Getting All opening balance records
	public List<OpeningBalanceModel> getAllOpeningBalance() {
		List<OpeningBalanceModel> OpeningBalanceModelList = new ArrayList<OpeningBalanceModel>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_OPENING_BALANCE;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				OpeningBalanceModel openingBalanceModel = new OpeningBalanceModel();
				openingBalanceModel.setBankName(cursor.getString(1));
				openingBalanceModel.setAcctHdrName(cursor.getString(2));
				openingBalanceModel.setAcctNo(cursor.getString(3));
				openingBalanceModel.setAcctType(cursor.getString(4));
				openingBalanceModel.setOpeningDate(cursor.getString(5));

				// Adding contact to list
				OpeningBalanceModelList.add(openingBalanceModel);
			} while (cursor.moveToNext());
		}

		// return contact list
		return OpeningBalanceModelList;
	}

	// Getting All opening balance records
	public List<OpeningBalanceModel> getNameAndAcctType(String acctNo) {
		List<OpeningBalanceModel> OpeningBalanceModelList = new ArrayList<OpeningBalanceModel>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_OPENING_BALANCE
				+ " WHERE " + ACCT_NUM + "=" + acctNo;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				OpeningBalanceModel openingBalanceModel = new OpeningBalanceModel();
				openingBalanceModel.setBankName(cursor.getString(1));
				openingBalanceModel.setAcctHdrName(cursor.getString(2));
				openingBalanceModel.setAcctNo(cursor.getString(3));
				openingBalanceModel.setAcctType(cursor.getString(4));
				openingBalanceModel.setOpeningDate(cursor.getString(5));

				// Adding contact to list
				OpeningBalanceModelList.add(openingBalanceModel);
			} while (cursor.moveToNext());
		}

		// return contact list
		return OpeningBalanceModelList;
	}

}

in order to run this we should have a main activity and call the DatabaseHandler object from the main activity.
as shown below.


package com.spark.android.pocketpassbook.testing;

import java.util.List;
 
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
 
public class AndroidSQLiteTutorialActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        DatabaseHandler db = new DatabaseHandler(this);
         
        final OpeningBalanceModel openingBalanceModel = new OpeningBalanceModel();
        // all the values i got it from front end after the form gets filled. 
        // if not we can just hardcode and test it.

        final EditText bankName = (EditText) findViewById(R.id.bankName);
	final EditText acctHdrName = (EditText) findViewById(R.id.acctHdrName);
	final EditText acctNo = (EditText) findViewById(R.id.acctNo);
	final EditText acctType = (EditText) findViewById(R.id.acctType);
	final EditText openingDate = (EditText) findViewById(R.id.openingDate);

        // set the values to model object
        openingBalanceModel.setBankName(bankName.getText()
							.toString().trim());
	openingBalanceModel.setAcctHdrName(acctHdrName.getText()
							.toString().trim());
	openingBalanceModel.setAcctNo(acctNo.getText().toString()
							.trim());
	openingBalanceModel.setAcctType(acctType.getText()
							.toString().trim());
	openingBalanceModel.setOpeningDate(openingDate.getText()
							.toString().trim());
        
        // calling the database handler object by passing the model object to it
        boolean status = openingBalanceDatabaseHandler.addOpeningBalance(openingBalanceModel);
    }
    }
}

Lets meet in my next tutorial (Android Text To Speech)
Happy Coding in Android 🙂