Displaying SVG images in Android

Hello everyone!

Scalable Vector Graphics (SVG) is a W3C recommendation basically used for describing two dimensional vector graphics in XML. One of the key advantages in using SVG graphics is that they do not lose quality if they are zoomed or resized. SVG images can be created, modified using any text editor.

In this post, we will learn how to display SVG images in Android. For this purpose, we will be using an open source library called svg-android. The library allows developers to parse SVG files and render them in an Android canvas. One just needs to place the SVG files in the res/raw folder of the Android Project and load them within their Activity.

Pre-requisites: Android SDK (Target SDK Android 2.3.3)

Step 1: Create a new Android application project named AndroidSVGDemo with package name com.example and target SDK as Android 2.3.3

Step 2: Download svg-android library

Download the latest version of the svg-android library from over here. Add the downloaded .jar file inside the libs folder of your Android project.

Step 3: Load SVG images in Activity class

For this demo, I have added a sample svg image in my project’s res/raw folder. Now, we need to load the image on the Android canvas for displaying it.

Write the following code in the MainActivity class!

package com.example;

import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;
import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
		
	    ImageView imageView = (ImageView)findViewById(R.id.img1);
	    //Parse the SVG file from the resource
	    SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.sample_svg);
	    //Get a drawable from the parsed SVG and apply to ImageView
	    imageView.setImageDrawable(svg.createPictureDrawable());
	}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_title"/>

    <ImageView 
        android:id="@+id/img1"
        android:layout_width="wrap_content"
       	android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>"
    
</RelativeLayout>

Finally, save all your work. Make sure no errors are present. Run the project on an emulator/actual device and you should see the SVG image being displayed on your screen.

snapshot

Image Courtesy: WikiMedia

Determine initial load processes in Oracle GoldenGate!

Hi everyone!

One of the interesting features of Oracle GoldenGate is obtaining the information of any Extract or Replicat process used during the initial load. An initial load process involves extracting the records of a table from a source database to a table in the target database. After the data is synchronized, one can configure processes to capture changes, pump the data to target and finally replicate the data.

In scenarios where GoldenGate is already configured for data replication, we need to obtain the information about the extract and the replicat process used for initial data load. Through this post, we will learn how to obtain the same using a few GGSCI commands.

Pre-requisites: Oracle GoldenGate 11g for Windows (64 bit)

Step 1: Open the GGSCI interface

ggsci_interface

Step 2: Create an extract named ext1 as follows!

EXTRACT ext1
SOURCEISTABLE
USERID ggs_owner, PASSWORD ggs_owner
RMTHOST 192.169.0.3, MGRPORT 7809
TABLE ggs_owner.TEST1;

As seen above, we have used the parameter SOURCEISTABLE that extracts all column data specified within TABLE statement. This parameter is applied to initial load methods such as loading data from file to Replicat and loading data from file to database utility. When used, SOURCEISTABLE must be the first parameter in the Extract file.

Alternatively, one can specify the same as an argument to the ADD EXTRACT command.

Step 3: Create a replicat named rep6 as follows!

REPLICAT rep6
SPECIALRUN
ASSUMETARGETDEFS
HANDLECOLLISIONS
USERID ggs_owner, PASSWORD ggs_owner
MAP ggs_owner.*, TARGET ggs_target.*;
END RUNTIME

As seen above, we have added the SPECIALRUN parameter in the replicat file. It is used for certain initial loads and ensures that the replicat is started automatically instead of manually using the START REPLICAT command.

add_extract_replicat

Step 4: Start the manager process

manager_running

Step 5: View information about processes

Now, one can view the information about the processes used for initial load using the following command!

info all tasks

view_task_info

Credits: This post wouldn’t have been possible without the support and help of Mr. Pankaj Singh (Oracle DBA)

Tutorial #61: Implement CheckBox and RadioButton in Android

Hello everyone!

One of the most common and widely used UI components in Android include CheckBox and RadioButton. A RadioButton has basically two states namely checked or unchecked. A user can press or click it to check it. Similarly, a checkbox is a specific type of two-states button that can be either checked or unchecked.

In this tutorial, we will learn how to implement CheckBox and RadioButton in Android.

Pre-requisites: Android SDK, Eclipse Helios

Step 1: Create new Android project

Open Eclipse IDE and create a new Android Application Project named AndroidCheckBoxRadioButtonExample with Target SDK Android 4.2.2

Step 2: Create Activity classes for RadioButton and CheckBox

Create a new Activity class called MainRadioActivity with package name com.example and add the following code!

package com.example;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.app.Activity;

public class MainRadioActivity extends Activity {
	
	
    private RadioGroup selectRole;
    private RadioButton btn;
    private Button display;
	
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_radio);
		
		selectRole = (RadioGroup) findViewById(R.id.selectRole);
		display = (Button) findViewById(R.id.display);
	 
		display.setOnClickListener(new OnClickListener() {
	 
			@Override
			public void onClick(View v) {
	 
				int selectedId = selectRole.getCheckedRadioButtonId();
	
				btn = (RadioButton) findViewById(selectedId);
	 
				Toast.makeText(MainRadioActivity.this,btn.getText(), Toast.LENGTH_LONG).show();
	 
			}
	 
		});
	}	

}

activity_radio.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainRadioActivity">

    <TextView
        android:id="@+id/txtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"/>
    
     <RadioGroup  
        android:id="@+id/selectRole"
        android:layout_below="@+id/txtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
 
        <RadioButton
            android:id="@+id/roleUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/role_user" 
            android:checked="true"/>
 
        <RadioButton
            android:id="@+id/roleAdmin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/role_administrator"/>
 
    </RadioGroup>
 
    <Button
        android:id="@+id/display"
        android:layout_below="@+id/selectRole"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/result_display"/>

</RelativeLayout>

Similarly, create another Activity class called MainCheckBoxActivity with the same package name and add the following code!

package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainCheckBoxActivity extends Activity{

	
	private CheckBox countryIndia, countryChina, countryUS;
	private Button btnResult;
	  
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_checkbox);
		
		countryIndia = (CheckBox) findViewById(R.id.country_india);
		countryChina = (CheckBox) findViewById(R.id.country_china);
		countryUS = (CheckBox) findViewById(R.id.country_us);
		btnResult = (Button) findViewById(R.id.btnResult);
	 
		btnResult.setOnClickListener(new OnClickListener() {		 
	 	  
		  @Override
		  public void onClick(View v) {
	 
				if (countryIndia.isChecked()) {
					Toast.makeText(MainCheckBoxActivity.this, "You selected India..!", Toast.LENGTH_LONG).show();
				}
				else
					Toast.makeText(MainCheckBoxActivity.this, "Try selecting India..!", Toast.LENGTH_LONG).show();
				
	 
		  }
		
		});
		
	}
}

activity_checkbox.xml

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

    <CheckBox
        android:id="@+id/country_india"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/india" />
 
    <CheckBox
        android:id="@+id/country_china"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/china"/>
 
    <CheckBox
        android:id="@+id/country_us"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/us" />
    
    <Button
        android:id="@+id/btnResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_result"/>

</LinearLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AndroidCheckBoxRadioButtonExample</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">RadioButton and CheckBox Demo</string>
    <string name="role_user">User</string>
    <string name="role_administrator">Administrator</string>
    <string name="result_display">Submit</string>	
    <string name="india">India</string>
    <string name="china">China</string>
    <string name="us">United States</string>
    <string name="btn_result">Submit</string>
	
</resources>

Finally, save all files and run the project. If no errors occur, you should see the following output!

snapshot_radio_button

snapshot_checkbox_1

snapshot_checkbox_2

Source code for this tutorial can be found over here.

It’s time for Nitrodroid!

It’s that time of the year again when some of the best speakers come together on a common platform to promote the development of Android. Nitrodroid is back with it’s 2nd edition that promises to be much better, bigger giving you a chance to meet experienced Android developers across India.

If Android is what that drives you and you are passionate about technology, then Nitrodroid is the place to be. The event will take place at Hotel Fidalgo, Goa on 26th October 2013. To know more about the event please visit the official page or the Facebook page.

Hurry and book your tickets for Nitrodroid 2013. Hope to see you there! πŸ™‚

nitrodroid_2013

Tutorial #60: Load data from Oracle table to XML using OdiSqlUnload

Hi everyone!

It’s time for yet another ODI tutorial. Through this post, we will learn how to export the data from an Oracle table to an XML file. To implement this task we would be using the built in tool called OdiSqlUnload that comes shipped with Oracle Data Integrator.

Pre-requisites: Oracle Data Integrator 11g (build version 11.1.1.7.0)

Step 1: Create table in Oracle

Create a new table called Department in your work repository and insert a few dummy values!

create table Department (DeptId int primary key, DeptName varchar(20));

insert into Department values(201, 'Computers');
insert into Department values(202,'Electronics');
insert into Department values(203,'Mech');

Step 2: Create XML file

Make a new blank XML file called sample.xml. Do not add any contents to it as it would be done using a built in tool. πŸ™‚

Step 3: Create Package and use OdiSqlUnload

Open ODI Studio and connect to your work repository. Create a new package named table_to_xml in any of your existing projects!

Now, drag and drop the OdiSqlUnload tool under the Files section.

create_package_drag_tool

Add the required details and finally save and run the package. Check the status of the operation under the Operator tab. If the operation is successful you should see the XML file now populated with data from your Oracle table.

add_required_fields

output

Output

<?xml version="1.0" encoding="ISO-8859-1"?>

<!-- File generated at 16/10/13 8:03 PM -->

<table>
    <row>
      <DEPTID><![CDATA[201]]></DEPTID>
      <DEPTNAME><![CDATA[Computers]]></DEPTNAME>
    </row>
    <row>
      <DEPTID><![CDATA[202]]></DEPTID>
      <DEPTNAME><![CDATA[Electronics]]></DEPTNAME>
    </row>
    <row>
      <DEPTID><![CDATA[203]]></DEPTID>
      <DEPTNAME><![CDATA[Mech]]></DEPTNAME>
    </row>
</table>

Tutorial #59: Implement Accelerometer using Processing for Android

Hey everyone!

Processing is slowly becoming a popular platform for creating Android applications. Although still in beta, it can be used to carry out tasks that we would normally do using an Android device.

In this tutorial, we will learn how to implement an accelerometer using Processing for Android.

Pre-requisites: Processing for Windows (64 bit), Android SDK

Launch the Processing application (.exe) and create a new Sketch named test_accelerometer_android.

Step 1: Installing Android mode

In case you don’t have the Android mode installed, you can do so by clicking on the Add mode option under Mode Manager.

installing_android_mode

Step 2: Write Processing Android

Switch to Android mode and include the following code in your Sketch!


import android.content.Context;                
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

SensorManager sensorManager;       
SensorListener sensorListener;    
Sensor accelerometer;              
float[] accelData;                 

// basic setup
void setup() 
{
  orientation(PORTRAIT);            
  smooth();
  noStroke();
};

void draw() 
{
  background(0);
  
  //get sensor data
  if (accelData != null) {

    fill(255);
    textSize(70);
    textAlign(CENTER, CENTER);
    text("x: " + nf(accelData[0], 1, 2) + "\n" + 
         "y: " + nf(accelData[1], 1, 2) + "\n" + 
         "z: " + nf(accelData[2], 1, 2), 0, 0, width, height);

  }
  else
  {
    text("[ no accelerometer data ]", width/2, height/2);
  }
};

void onResume() 
{
  super.onResume();
  sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
  sensorListener = new SensorListener();
  accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  sensorManager.registerListener(sensorListener, accelerometer, SensorManager.SENSOR_DELAY_GAME);  
};

void onPause() 
{
  sensorManager.unregisterListener(sensorListener);
  super.onPause();
};


class SensorListener implements SensorEventListener 
{
  void onSensorChanged(SensorEvent event) 
  {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) 
    {
      accelData = event.values;
    }
  }
  void onAccuracyChanged(Sensor sensor, int accuracy) 
  {
       //todo 
  }
}

output

Run the Sketch on an Android device by connecting the phone via USB cable to your machine. You should see the accelerometer data being displayed. Alternatively, developers can also use the Ketai library for implementing the same functionality.

Reference: Processing for Android

Source code for this tutorial can be found over here.

Getting started with MongoDB on Windows!

MongoDB is a popular open-source, cross platform document oriented database system. It is one of those NoSQL databases out there used for handling random, unstructured data as opposed to the traditional relational database management system (RDBMS) structure.

Through this post, we will learn how to install and setup MongoDB in Windows followed by a simple example!

Pre-requisites: Windows 7 (64 bit) OS

Step 1: Download MongoDB

Go to the downloads page on the MongoDB website and obtain the latest version of the database depending upon your operating system bit version (32 or 64 bit). Extract all the contents to a folder mongodb, for example C:\mongodb

Step 2: Create Configuration file

You first need to create a MongoDB config file inside the MongoDB folder for example, mine exists at C:\mongodb\mongo.config. Create the file using any text editor like Notepad.

mongo.config

##store data here
dbpath=C:\mongodb\data
 
##all output go here
logpath=C:\mongodb\log\mongo.log
 
##log read and write operations
diaglog=3

Note: You need to manually create two folders namely data and log inside the MongoDB directory!

mongo_db_folder_structure

Step 3: Run MongoDB server

Open a command prompt window. Navigate up to the bin (C:\mongodb\bin) folder and execute the following command!

mongod.exe --config d:\mongodb\mongo.config

run_mongo_db_server

Step 4: Connect to MongoDB

Finally, connect to your MongoDB database by typing the mongo command in the prompt.

connect_to_mongo_db

Short Example

At present, we don’t really have a database. We need to create one to insert records. Copy the below commands in your MongoDB shell.

>db.test.insert( {name:'karan', city: 'mumbai' } );
>db.test.insert( {name:'vaibhav', city: 'bangalore' } );
>db.test.insert( {name:'ashish', city: 'pune' } );

create_database_insert_records

The above example inserts a document in the collection named test. You can find more information over here.

Also, one can search for all records or for a particular record as follows!

>db.test.find()

finding_all_records

>db.test.find(city:'mumbai');

finding_particular_record

That completes the setup of MongoDB. Stay tuned for more! πŸ™‚

Scheduling tasks in Oracle database

Hello everyone!

Today, we will learn how to schedule a particular task in Oracle. Starting from Oracle 10g, the SCHEDULER package provides a collection of scheduling functions and procedures that are callable from any PL/SQL program. The package also provides the ability to execute jobs with user-specific privileges/roles.

Pre-requisites: Oracle database 10g Express Edition

Let’s create a simple PL/SQL procedure that we are going to schedule!

Login to either SYS or SYSTEM (or any user that has the right privileges for scheduling) and execute the following commands.

create or replace procedure greeting
as
begin
dbms_output.put_line('Hello world');
end;
/

In order to schedule the above procedure, we first need to create a new schedule for the same using the DBMS_SCHEDULER package.

BEGIN
  DBMS_SCHEDULER.create_job (
    job_name        => 'TASK1',
    job_type        => 'STORED_PROCEDURE',
    job_action      => 'greeting',
    start_date      => SYSTIMESTAMP,
    repeat_interval => 'freq=minutely; byminute=1',
    end_date        => NULL,
    enabled         => TRUE,
    comments        => 'my first PL/SQL task');
END;
/

Now, run the execute command to start the job!

execute dbms_scheduler.run_job('task1');

In order to view the job description including status, name etc we run the following SQL command.

SQL> select log_date, job_name, status, run_duration
  2  from dba_scheduler_job_run_details where job_name='TASK1';

You will observe that the job has been executed successfully. In this way, you can schedule PL/SQL functions, triggers etc to run at a specific time as well. Hope this helps! πŸ™‚

view_scheduled_job

Tutorial #58: Implement ActionBar in Android

Hi everyone!

The ActionBar was first introduced in Android 3.0 (Honeycomb). Using this user interface component developers can display titles, icons as well as associate actions. It is basically a window feature used for user navigation and identifying user location.

Key features of the ActionBar as mentioned on the Android developer’s page are as follows:

1. Provides a dedicated space for giving your app an identity and indicating the user’s location in the app.

2. Makes important actions prominent and accessible in a predictable way (such as Search).

3. Supports consistent navigation and view switching within apps (with tabs or drop-down lists).

In this tutorial we will learn how to implement an ActionBar in Android. In case you are targeting an Android version earlier than 3.0 you can use the Open Source project ActionBar Sherlock which allows you to use the ActionBar on earlier Android versions.

Pre-requisites: Eclipse Indigo, Android SDK (Target SDK 4.2.2)

Open Eclipse IDE and create a new Android application project named AndroidActionBarExample. Let the Activity name be MainActivity with Target SDK as Android 4.2.2. Let the package name be com.example

Add the following code in the Activity class!

MainActivity.java

package com.example;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends Activity 
{
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
			super.onOptionsItemSelected(item);
			switch(item.getItemId())
			{

			case R.id.itemOne:
			Toast.makeText(getBaseContext(), "Share an item", Toast.LENGTH_SHORT).show();
			break;

			case R.id.itemTwo:
			Toast.makeText(getBaseContext(), "Send an item", Toast.LENGTH_SHORT).show();
			break;
			
			}
	       return true;
	}
	
}

The actions for the action bar are typically defined in an XML resource file. The showAsAction attribute allows you to define how the action is displayed.

res/menu/main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>
  
    <item
	    android:id="@+id/itemOne"
	    android:icon="@drawable/ic_launcher"
	    android:title="@string/textItemOne"/>
    
    <item
	    android:id="@+id/itemTwo"
	    android:title="@string/textItemTwo"
	    android:icon="@drawable/ic_launcher"/>

</menu>

res/values/strings.xml

<resources>
<string name="app_name">AndroidActionBarExample</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="textItemOne">Share</string>
<string name="textItemTwo">Send</string>
</resources>

res/layout/activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"/>

</RelativeLayout>

Save all the files. Make sure no errors are present. Run the project on an Android device/emulator and you should see the following output!

android_action_bar_1

android_action_bar_2

Source code for this tutorial can be found over here.

Reference: Android ActionBar