Tutorial #47: Send E-mail automatically using GoldenGate

Hello everyone!

Today’s post is a bit complex but at the same time interesting for all those familiar with Oracle GoldenGate. In this tutorial, you will learn how to send an e-mail once a particular transaction (insert/delete/update) takes place at the source side.

Pre-requisites: Oracle GoldenGate for Windows (64 bit), Oracle database 11gR2 Enterprise Edition with *SQLPlus, Eclipse IDE

1. Java Part

Let’s first write our email code using Java. Create a new Java console application project named SendMail in Eclipse. I will be using the JavaMail API by adding the latest version of the mail.jar file to my project. Let the package name be com.example and class name SendMailTLS.


package com.example;

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendMailTLS 
   public static void main(String[] args) 
     final String username = "yourgmailusername@gmail.com";
     final String password = "yourgmailpassword";
     Properties props = new Properties();
     props.put("mail.smtp.auth", "true");
     props.put("mail.smtp.starttls.enable", "true");
     props.put("mail.smtp.host", "smtp.gmail.com");
     props.put("mail.smtp.port", "587");
     Session session = Session.getInstance(props,
	  new javax.mail.Authenticator() {
	  protected PasswordAuthentication getPasswordAuthentication() {
	  return new PasswordAuthentication(username, password);
	    MimeMessage message = new MimeMessage(session);
	    message.setFrom(new InternetAddress(username));
        message.addRecipient(Message.RecipientType.TO,new InternetAddress("yourrecipient@gmail.com"));
	    message.setSubject("Mail from GoldenGate");
	    //set your message content    
	    BodyPart messageBodyPart1 = new MimeBodyPart();
	    messageBodyPart1.setText("A transaction was successfully completed!!");
	    //set DataHandler object to this object    
	    MimeBodyPart messageBodyPart2 = new MimeBodyPart();

        //change path to filename as per your needs
        //adding attachments to mail
	    String filename = "C:\\programs\\result.txt";
	    DataSource source = new FileDataSource(filename);
	    messageBodyPart2.setDataHandler(new DataHandler(source));
	    //add MimeBodyPart objects to this object    
	    Multipart multipart = new MimeMultipart();

	    //set the multiplart object to the message object
	    message.setContent(multipart );


      catch (MessagingException e) 
	     throw new RuntimeException(e);

Note: Make sure you add the latest version of mail.jar by right clicking your Project –> Properties –> Java Build Path –> Add External Jars.

Export the Project as a Runnable Jar file to a particular directory and click Finish.


2. GoldenGate part

In GoldenGate, I will be performing replication with source and target on the same physical host. Open *SQLPlus and create the following table in both the source and the target schema.

Source schema: SYSTEM
Table name: same_host_src

create table same_host_src(empid int primary key, empname varchar(10), empcity varchar(10));

Do not insert any rows in the source table now since we would be doing the same during the replication process!

Target schema: GGS_OWNER
Table name: same_host_src

create table same_host_src(empid int primary key, empname varchar(10), empcity varchar(10));

Now as per the replication process, we need to create a Extract and the corresponding Replicat process. Open the GGSCI command line interface and write the following commands!

Creating Extract

GGSCI (jatin-PC) 25> dblogin userid ggs_owner, password ggs_owner

GGSCI (jatin-PC) 26> add trandata system.same_host_src

GGSCI (jatin-PC) 27> add extract extlocal tranlog begin now

GGSCI (jatin-PC) 28> add rmttrail ./dirdat/aa extract extlocal

GGSCI (jatin-PC) 29> edit params extlocal

--add the following lines in the notepad file
extract extlocal
userid ggs_owner, password ggs_owner
rmthost, mgrport 7809
rmttrail ./dirdat/aa
table system.same_host_src;

Create Replicat

GGSCI (jatin-PC) 30> add replicat replocal exttrail ./dirdat/aa

GGSCI (jatin-PC) 31> edit params replocal

--add following lines in the notepad file
REPLICAT replocal
USERID ggs_owner, PASSWORD ggs_owner
MAP system.same_host_src, TARGET ggs_owner.same_host_src, FILTER (@STREQ (EMPCITY, "pune" )), EVENTACTIONS ( IGNORE TRANS , SHELL "C:\programs\mailsend.bat");


As you can see above, we have added a FILTER to the replicat file. It is used to specify the event which is to look for the string “pune” in the column name EMPCITY of the table SAME_HOST_SRC.

When this event occurs, the EVENTACTIONS clause specifies now what to do which is:

1. Ignore the transaction and do not replicate that insert into the table SAME_HOST_SRC on the target side.

2. Run the Windows batch file namely mailsend.bat on the target server since replicat process runs on target.

Run Manager, Extract and Replicat process

GGSCI (jatin-PC) 32> start manager

GGSCI (jatin-PC) 32> start extlocal

GGSCI (jatin-PC) 33> start replocal


Now, insert a new record in your source table. For our mail event to occur, I will purposely insert a record with EMPCITY as “pune” so that the batch file is called and the mail is sent to our recipient!


insert into same_host_src values(109,'nitesh','pune');


Check Extract statistics:

GGSCI (jatin-PC) 35> stats extlocal


Wait for some time. Log in to the Gmail account you have specified in the above Java code. You should see a new mail in your Inbox! 🙂 The mail should also contain the attachment file that includes the report of the transaction generated by GoldenGate.


The batch file plays a very important role here. It contains the code for calling the SendMail.jar file which in turn sends the email. More information can be obtained from over here.

This completes the tutorial. Hope it helps. Have a nice day! 🙂

Source: GoldenGate replication on same physical host

Tutorial #46: Configuring Oracle database for using GoldenGate


In my previous tutorial on Oracle GoldenGate, we saw how to install the GoldenGate software on a Windows 7 machine. However, in order to start using GoldenGate we need to first configure or prepare the Oracle database.

Over here I will demonstrate how to set up your Oracle database for getting started with GoldenGate. This would involve configuring both the source and target databases. In this case, we assume that both source and target are Oracle databases.

Pre-requisites: Oracle database 11g Enterprise Edition with *SQLPlus, Windows 7 (64 bit) Operating System

Step 1: Create a new schema for GoldenGate

Open *SQLPlus and Connect to your database instance as sysdba (system database administrator). In case you are not able to log in as sysdba, please refer this link. Once connected, execute the following commands in the given order!

1. create tablespace ggs_data
   datafile 'D:\app\your-path-to-ORADATA\orcl\ggs_data.dbf' size 200m
   autoextend on next 10m maxsize 4g;

2. create user ggs_owner identified by g
   default tablespace ggs_data
   temporary tablespace temp;

3. grant connect, resource to ggs_owner;

4. grant select any dictionary, select any table to ggs_owner;

5. grant create table to ggs_owner;

6. grant flashback any table to ggs_owner;

7. grant execute on dbms_flashback to ggs_owner;

8. grant execute on utl_file to ggs_owner;

9. grant create any table to ggs_owner;

10. grant insert any table to ggs_owner;

11. grant update any table to ggs_owner;

12. grant delete any table to ggs_owner;

13. grant drop any table to ggs_owner;

Step 2: Enable ARCHIVELOG mode for Oracle database

GoldenGate requires the Oracle database to be in ARCHIVELOG mode. When you enable this mode redo logs will be archived instead of overwritten. The archive logs are stored in a separate place usually can backed up regularly by your standard filesystem backup system (NetBackup or whatever).

-- to check it the database is running in archivelog mode:
select log_mode from v$database;

-- to make it running in archivelog mode:
shutdown immediate startup mount
alter database archivelog;

Step 3: Verify database-level supplemental logging

When the supplemental logging is active on a database, the redo logs contain other columns from tables to uniquely identify a row. We need to verify supplemental logging at the source database by writing the following SQL command!

-- it must be YES or IMPLICIT

-- to enable it:

Step 4: Add DDL replication support

Goldengate supports the replication of DDL commands, operating at a schema level, from one database to another. By default the DDL replication is disabled on the source database (extract side) but is enabled on the target Database (replicat side). The commands below are used to activate the DDL replication.

However, it is best suited to carry out DDL replication on both source and target databases as follows!

Create a file named as GLOBALS in the GoldenGate directory, if one does not exist!

C:\gg_src>notepad GLOBALS

Add the following into the GLOBALS file:

GGSCHEMA ggs_owner

Log in to *SQLPlus as sysdba by navigating to the gg_src folder!

C:\ggs_src>sqlplus /nolog

SQL*Plus: Release Production on Mon Jul 29 22:34:15 2013
Copyright (c) 1982, 2010, Oracle.  All rights reserved.

SQL> conn / as sysdba

Run the below SQL scripts

Note: When asked for schema name enter ggs_owner

SQL> @marker_setup.sql

SQL> @ddl_setup.sql

SQL> @role_setup.sql

Grant the created role (default name is GGS_GGSUSER_ROLE) to all Oracle GoldenGate Extract users.


Run the ddl_enable.sql script to enable the DDL trigger.

SQL> @ddl_enable.sql

Finally, make sure you commit all the changes made so far. You have now successfully configured the Oracle database for using GoldenGate. In the upcoming tutorials we will see how to perform initial load, unidirectional replication, bidirectional replication etc using Extract, Replicat processes and data pumps. Till then enjoy! 🙂

Source: Oracle GoldenGate Hands On Tutorial

References: Supplemental Logging, DDL replication

Installing Oracle database 11gR2 on Windows

Hi guys!

Recently, Oracle launched it’s latest database version 12c Release 1. Prior to this version, developers used the Oracle 11gR2 (Release 2) version of the Oracle database. Some of the features that were introduced in Oracle 11g were clustering, business intelligence and data warehousing, content management services, performance, manageability etc.

In this tutorial, we will learn how to download and install the Oracle database 11gR2 version on a Windows machine!

Pre-requisites: Windows 7 (64-bit) Operating system, minimum 3GB RAM, latest version of Java i.e Java 7 64-bit installed for Windows

Step 1: Download Oracle 11gR2 database

Go to the Oracle database software downloads page and download both the files of Oracle 11gR2 for Windows (x64).

Step 2: Run the the Oracle Universal Installer

Once you have downloaded both the files, extract them to obtain the respective Disk1 and Disk2 folders. Copy paste the database folder in Disk2 to Disk1 so that both the database folders get merged. Now, click on the oui (Oracle Universal Installer) present in the install folder in Disk1.



Follow the below screenshots in order to begin with the installation!






The installation will take around 15-20 minutes. Once the installation is over, you will get the Password management option. There you can unlock other user accounts including scott.

Issues faced during installation

Issue #1: Length of PATH Environmental variable

Make sure the length of your PATH environmental variable does not exceed 1023 characters or else installation will not proceed.

Issue #2: Presence of another Oracle database instance

Before you install Oracle 11gR2 on your machine, make sure you don’t have another Oracle instance running. Sometimes, due to the presence of another Oracle instance, the ORACLE_HOME variable path is already set. In that case, you need to either change the existing ORACLE_HOME path to something else or remove the existing Oracle database.

Tutorial #45: Installing GoldenGate on Windows

Hello everyone!

Oracle GoldenGate (GG) is a well known replication software that provides real time, log based change data capture and delivery between heterogeneous systems. It acts as an ETL tool that provides high availability and disaster tolerance due to which business critical applications can operate without any disruption.

The GoldenGate product suite includes the following!

1. Oracle GoldenGate

2. GoldenGate Director is a multi-tiered client-server application that enables the configuration and management of GoldenGate instances from a remote client (web based interface).

3. Oracle GoldenGate Veridata is an online high-speed data comparison solution that identifies and reports data discrepancies between databases and sets of data.

In this tutorial, I will explain how to download and configure GoldenGate on a Windows machine!

Pre-requisites: Windows 7 (64 bit) Operation System

Step 1: Download Microsoft Visual C++ 2005 SP1 and GoldenGate

First, you need to download the Microsoft Visual C++ 2005 SP1 Redistributable for Windows 7 (x64). Download appropriate version of GoldenGate from the Oracle website. If you working on an Oracle 11g database then you need to download the GoldenGate Oracle 11g 64 bit package for Windows. Extract the downloaded rar file to get the GG folder.

Step 2: Create new directory for GG software

Create a new directory called gg_src

C:\mkdir gg_src

Note: Do not install GoldenGate into a folder that contains spaces in its name.

Copy all the files inside the extracted GG folder to gg_src. Now, open a Command Prompt window and navigate to the folder gg_src and type the ggsci command.


GoldenGate should now open up. Write the command CREATE SUBDIRS to create the necessary sub-directories to be used by GoldenGate.


Step 3: Add and install Manager service

Inside the ggsci window, type edit params mgr. It will create a new Notepad file. Add the following lines to it!

port 7809
autostart ER *

Note: You can use port number as 7840 also. The autostart ER parameter indicates all Extract and Replicat processes to start automatically as soon as the Manager is started. PURGEOLDEXTRACTS is used to specify the minimum number of days for storing trail files. You can read about Extract, Replicat processes and trail files by downloading the latest GoldenGate documentation from over here.

Now, open another instance of Command Prompt, navigate to the gg_src folder and type the following command!


The Manager service is now successfully installed. To verify the same try starting the manager from the ggsci window as follows!


So that’s it for this tutorial. In the next tutorial, we will learn how to configure or prepare the Oracle database for using GoldenGate. Have a nice day! 🙂

Access Call logs in Android

Hey guys!

Today we will learn about a new functionality in Android using which one can access data through various built-in Content Providers such as contacts, browser, call logs etc. Basically, Content Providers are the standard interface that connects data in one process with the code running in another process.

One of the most commonly used Content Providers is CallLog.Calls which is used to provide access to call logs data. Call logs contain information about outgoing, incoming and missed calls.

Pre-requisites: Android SDK (tested below code on Android 2.3.3) , Eclipse IDE (preferably latest version)

Let’s begin implementing the Call logs Content Provider in Android! Create a new Activity class named MyCallLogActivity in any of your existing Projects. Let the package name be com.example and select Target Android SDK as Android 2.3.3


package com.example;

import java.util.Date;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.widget.TextView;

public class MyCallLogActivity extends Activity
	private TextView tv;
	private String callType;
	private String phoneNumber;
	private String callDate;
	private String callDuration;
	private Date callDateTime;

	protected void onCreate(Bundle savedInstanceState) 
		tv= (TextView)findViewById(R.id.calllog);
	public void getCallDetails() 

		StringBuffer sb = new StringBuffer();
		Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI,null, null,null, null);
		int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER ); 
		int type = managedCursor.getColumnIndex( CallLog.Calls.TYPE );
		int date = managedCursor.getColumnIndex( CallLog.Calls.DATE);
		int duration = managedCursor.getColumnIndex( CallLog.Calls.DURATION);
		while (managedCursor.moveToNext()) 
			phoneNumber = managedCursor.getString(number);
			callType = managedCursor.getString(type);
			callDate = managedCursor.getString(date);
			callDateTime = new Date(Long.valueOf(callDate));
			callDuration = managedCursor.getString(duration);
			String cType = null;
			int cTypeCode = Integer.parseInt(callType);
						case CallLog.Calls.OUTGOING_TYPE:
						cType = "OUTGOING";
						case CallLog.Calls.INCOMING_TYPE:
						cType= "INCOMING";
						case CallLog.Calls.MISSED_TYPE:
						cType = "MISSED";
			tv.setText("\nPhone Number:--- "+phoneNumber +
			           "\nCall Type:--- "+cType+" " +
				   "\nCall Date:--- "+callDateTime+" " +
				   "\nCall duration in sec :--- "+callDuration);



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"


In order to access the Call Logs information, you would need to add the android.permission.READ_CONTACTS permission in your manifest file as follows!


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.READ_CONTACTS"/>
        android:targetSdkVersion="10" />

                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

Finally, make sure no errors are present. Save and run the Activity and you should get the following output!


Tutorial #44: Implement log based change data capture in ODI

Hello everyone!

Change data capture is mainly used to capture the data inserted, deleted or updated at the source side. The changes thus captured are then replicated to the target side. There are many ways to implement Change Data Capture in Oracle Data Integrator. Two commonly used methods are:

1. Log based change data capture

2. Trigger based change data capture

I had implemented trigger based change data capture in one of my earlier tutorials. In this post, I will implement the log based change data capture method!

Pre-requisites: Oracle database 11gR2 Enterprise edition with *SQLPlus, Oracle data integrator 11g (build version

Must read: Previous version of Oracle data integrator namely ODI 10g included the JKM Oracle 11g Consistent LOGMINER (REALTIME) module for change data capture. However, this knowledge module is not present from ODI 11g onwards. As Oracle is slowly moving towards streams, this KM was then replaced by JKM Oracle 11g Consistent Streams. Hence in order to implement log based CDC we either need to download the older LOGMINER KM or use the current Streams KM. For using streams in Oracle it is mandatory to have the Oracle database Enterprise Edition (EE) to be downloaded and installed. Other versions of Oracle database such as XE (Express edition), SE (Standard edition) do not support streams.

Note: I assume you have the data models, physical and logical schemas already set up for the connection to your Oracle database.

Step 1: Create source and target tables

source table for CDC

create table cdc_src(empid int primary key, empname varchar(20),empcity varchar(20));

target table for CDC

create table cdc_target(empid int, empname varchar(20), empcity varchar(20));

Insert a few dummy records in the source table only.


Next, reverse engineer both source and target tables in a new Model named cdc_model. Add the source data store cdc_src to CDC by right clicking–> Change data capture–>Add to CDC


Step 2: Apply log based method

Open the cdc_model and select the Journalizing option. You now need to select the Journalizing mode. Simple is used for CDC implementation on a single table and Consistent on multiple tables or models. In this tutorial I will be implementing the Consistent Set option even though I have a single source table. You can always try it using multiple source tables described over here

Once you have selected the Consistent option, you need to choose the corresponding Knowledge module. I have selected JKM Oracle 11g Consistent Streams for my Project cdc_test_project.

Make sure you follow the Basic Configuration steps that appear in the description below before you start implementing your Interface!


Basic Configuration Steps

1. Connect SYS as SYSDBA with SQL*Plus and run the following statements
	-- Replace "SAS" with the name of your user
	-- This user is specified in the Data Server definition
	grant dba to SAS;
	grantee	=> 'SAS',
	grant_privileges=> true);

2. Exit from SQL*Plus
3. Select the JKM on the model you want to journalize
4. Add the Datastores to the CDC Set (with this JKM, it is not mandatory to define an order for the datastores in the CDC Set)
5. Make sure that the AUTO_CONFIGURATION and VALIDATE options are set to Yes
6. Start the Journal on the Model
7. Create a Subscriber on the Model

Note: If you are logged in as SUPERVISOR the default subscriber chosen would be SUNOPSIS.

Once again, right click the source data store cdc_src and select Start Journal. You should see a green color icon on the data store. This indicates that the data store is now in journalizing mode ready to capture changes. Check the status of the operation in the Operator tab.




Step 3: Make changes to source table

After you have started the journal successfully, you now need to update or insert any row in the source table cdc_src. In my case, I have added a new row as follows!

SQL> insert into cdc_src values(108,'salman','mumbai');
1 row created.
SQL> commit;
Commit complete.

Step 4: Create an interface

Create a new Interface named cdc_test. Drag and drop the journalized source table and the target table in Mapping. In Mapping, select source data store and tick the option Journalized data only in the Source properties window. Finally, select IKM as Oracle Incremental Update and run the interface.

Ensure that no errors occur. Check the status of the operation. If the operation was successful, right click the source data store –> Change data capture and select Journal data. You should now see the changed data getting reflected! 🙂



Source: Working with Change data capture, ODI Experts blog

Get list of installed applications in Android

Hey everyone!

Android provides the PackageInfo class that contains information about the contents of a package. Sometimes, we need to obtain the list of applications installed on an Android device in order to determine whether our application was installed correctly or not.

In this post, I will demonstrate how to obtain the list of all installed applications on your Android device. Since I would be obtaining information about an application, I would also be using the ApplicationInfo class.

Let’s begin by creating a new Activity named GetListActivity in any of our existing Android projects. Let the Package name be com.example with Target SDK as Android 2.3.3


package com.example;

import java.util.List;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.util.Log;

public class GetListActivity extends Activity
	protected void onCreate(Bundle savedInstanceState) 
	public void getInstalledApps()
	    List<PackageInfo> PackList = getPackageManager().getInstalledPackages(0);
	    for (int i=0; i < PackList.size(); i++)
	         PackageInfo PackInfo = PackList.get(i);
		     if(((PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true)
		          String AppName = PackInfo.applicationInfo.loadLabel(getPackageManager()).toString();
		          Log.e("DeviceApp" + Integer.toString(i), AppName);

Save and run the Activity class. You will see the list of all the applications in the Logcat window!


Tutorial #43: Performing joins in Oracle Data Integrator

Hello everyone!

Sometimes in order to fetch the results of a query we need to perform a join on two or more tables. Oracle data integrator provides a simple way to create joins between source tables.

In this tutorial, I will explain how to perform a simple left outer join using Oracle Data Integrator.

Pre-requisites: Oracle database 10g Express Edition with *SQLPlus, Oracle Data Integrator 11g (build version

Initially we need to create two source tables in our Oracle database as follows!

Create source tables

create table customer(cid int primary key, cname varchar(20), ccity varchar(20));

create table product(pid int primary key, pname varchar(20), pcname varchar(20));

Insert a few dummy records in both these tables.

Create target table

create table join_target(jid int primary key, jname varchar(20), jcity varchar(20), jpid int);


This completes the database part. We now have our tables created along with some sample values.

Open ODI Studio and perform the following steps!

Note: I assume you have a Oracle Physical and Logical schema already set up for the connection to your database.

Step 1: Reverse engineer source and target tables

In order to use the tables in an Interface we need to reverse engineer them. Create a new model named join_src and reverse engineer the customer and product tables. Similarly, reverse engineer the target table in another model named join_target.

Step 2: Create new interface

In any of your existing projects, create a new Interface named test_join_example as follows!



Our join query looks something like this!

select * from customer c left outer join product p on c.cname = p.pcname;



Finally, save and run the interface. Check the status of the operation under the Operator tab. If the operation is successful, you will see the rows fetched using the join query in the target table.



Resolve TNS protocol error in Oracle 11g

Many a times while connecting to the Oracle database, we get the ORA-12560 TNS protocol error. The TNS (Transparent Network Substrate) protocol is used for client interaction with Oracle’s RDBMS. Depending upon the Oracle database version and the Operating system version you need to take the appropriate steps to resolve the error.

Here, I will show you how to resolve the TNS error on a Windows 7 (64 bit OS) machine with Oracle 11g R2 (Release 2) installed.

Step 1: Check listener status

First thing you need to check is whether the listener service is started. Go to Start–>Run and type services.msc. Find the Oracle listener service and start it. In my case the listener service name is OracleServiceORCL where ORCL is my service identifier.


Once the listener is started you can verify the same by opening a command prompt window and typing the below command!

lsnrctl status


Step 2: Set the Oracle SID (Service Identifier)

Next you need to add the Oracle SID as an Environmental variable. You can do it by either setting it using command prompt or by creating a new Environmental variable as follows!


Using command prompt type

set ORACLE_SID = yoursid

Step 3: Use TNS ping utility

A final check is to ensure that your service name is present in the sqlnet.ora file. You can check this by typing the following command in the prompt window.

tnsping yourservicename


By performing these steps you should be able to solve the TNS protocol error. That’s it for this Oracle tip! Feel free to ask any questions! 🙂

Determine type of device in Android

Hello everyone!

Android applications run on multiple devices including smartphones, 7-inch tablets and even 10-inch tablets. As developers, we need to create applications that will support multiple devices. The Android developer’s guide talks about supporting different screen sizes ensuring that the correct layout is applied to the correct screen.

In this post, I will explain how to determine whether the device is a tablet or a phone. There are two ways to implement this as follows!

Pre-requisites: Android SDK (tested below code on Android 4.2.2), Target SDK Android 4.2.2 (API level 17)

1. Using Java code

Create a new Activity class named CheckDeviceActivity in any of your existing Android projects and write the following code!


package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.widget.Toast;

public class CheckDeviceActivity extends Activity
	protected void onCreate(Bundle savedInstanceState) 
		Display d = getWindowManager().getDefaultDisplay();
			Toast.makeText(getApplicationContext(), "Device is a tablet..!", Toast.LENGTH_LONG).show();			
			Toast.makeText(getApplicationContext(), "Device is a phone..!", Toast.LENGTH_LONG).show();	
	//check whether device is a tablet or not
	private static boolean isTablet(Display display)
	    Log.d("Message", "Checking device!");
	    final int width = display.getWidth();
	    final int height = display.getHeight();

	    switch (display.getOrientation()) 
	    case 0: case 2:
	    		if(width > height) 
	    			return true;
	    case 1: case 3:
	        	if(width < height) 
	        		return true;
	    return false;

2. Using XML

Create a new XML file called screen.xml in three folders of your Android project as follows!


<?xml version="1.0" encoding="utf-8"?>
  <string name="screentype">phone</string>


<?xml version="1.0" encoding="utf-8"?>
  <string name="screentype">7-inch-tablet</string>


<?xml version="1.0" encoding="utf-8"?>
  <string name="screentype">10-inch-tablet</string>

Now, from your Activity class you can check the value of screentype using the below code!

String screenType=getResources().getString(R.string.screentype);
    System.out.println("Device is a phone!!!");

Run the project and you should see the following output! Thanks for reading! Have a nice day! 🙂


Reference: Display and WindowManager