Convert text file to PDF document in Java

Hi everyone!

iText is a popular open source library that helps to create and manipulate PDF documents. Developers can use this library to convert their existing files to PDF documents. iText is currently available for Java, .NET and Android platforms. To use iText commercially, one needs to obtain a license where as the open-source version can be downloaded from over here.

The iText classes are very useful for those who need to generate read-only, platform independent documents containing text, lists, tables and images. The library is especially useful in combination with Servlets. Through this post, we will learn how to convert a text file to a PDF document using iText.

Pre-requisites: Eclipse IDE, Java (JDK 1.6 or above)

Open Eclipse IDE and create a new Java project called JavaTextToPDFDemo with package name com.example

Add a new Java class within this package called TextToPDFConverter containing the following code!

TextToPDFConverter.java

package com.example;

import java.io.BufferedReader;  
import java.io.DataInputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.InputStreamReader;  
import com.itextpdf.text.Document;  
import com.itextpdf.text.Element;  
import com.itextpdf.text.Font;  
import com.itextpdf.text.Paragraph;  
import com.itextpdf.text.pdf.PdfWriter;

public class TextToPDFConverter {  


	public static void main(String[] args) throws Exception {  

		// TODO Auto-generated method stub  
		File file = new File("C:\\programs\\java_text_to_pdf\\sample.txt");

		if(file.getName().endsWith(".txt")){

			if(convertTextToPDF(file)){
				System.out.println("Text file successfully converted to PDF");
			}
		}

	}  

	public static boolean convertTextToPDF(File file) throws Exception  
	{  

		FileInputStream fis=null;  
		DataInputStream in=null;  
		InputStreamReader isr=null;  
		BufferedReader br=null;  

		try {  

			Document pdfDoc = new Document();  
			String output_file =file.getParent()+"\\"+"sample.pdf";  
			PdfWriter writer=PdfWriter.getInstance(pdfDoc,new FileOutputStream(output_file));  
			pdfDoc.open();  
			pdfDoc.setMarginMirroring(true);  
			pdfDoc.setMargins(36, 72, 108,180);  
			pdfDoc.topMargin();  
			Font myfont = new Font();  
			Font bold_font = new Font();  
			bold_font.setStyle(Font.BOLD);  
			bold_font.setSize(10);  
			myfont.setStyle(Font.NORMAL);  
			myfont.setSize(10);  
			pdfDoc.add(new Paragraph("\n"));  

			if(file.exists()){  

				fis = new FileInputStream(file);  
				in = new DataInputStream(fis);  
				isr=new InputStreamReader(in);  
				br = new BufferedReader(isr);  
				String strLine;  

				while ((strLine = br.readLine()) != null)  {  

					Paragraph para =new Paragraph(strLine+"\n",myfont);  
					para.setAlignment(Element.ALIGN_JUSTIFIED);  
					pdfDoc.add(para);  
				}  
			}     
			else {  

				System.out.println("no such file exists!");  
				return false;  
			}  
			pdfDoc.close();   
		}  

		catch(Exception e) {  
			System.out.println("Exception: " + e.getMessage());  
		}  
		finally {  

			if(br!=null)  
			{  
				br.close();  
			}  
			if(fis!=null)  
			{  
				fis.close();  
			}  
			if(in!=null)  
			{  
				in.close();  
			}  
			if(isr!=null)  
			{  
				isr.close();  
			}  

		}  

		return true;  
	}  
}  

Note: You need to add the following iText .jar files to the Class Path in order to resolve the import statement specific errors in the above class.

itextpdf-5.4.5.jar
itext-pdfa-5.4.5
itext-xtra-5.4.5

Finally, make sure no errors are present. Save and run the application and you should see a message being displayed inside the console.

console_output

Tutorial #72: Implement accelerometer in PhoneGap

Like Android and other existing mobile operating systems, Phonegap too provides the Accelerometer API to capture device motion in the x, y and z directions. An accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation. The accelerometer can detect 3D movement along the co-ordinate axes.

In this tutorial, we will learn how to implement an accelerometer sensor using the PhoneGap framework. In this case, our target platform would be Android. You can download the latest version of PhoneGap from over here.

Pre-requisites: Eclipse IDE

Create new Android application project called PhoneGapAccelerometerDemo with package name com.example and add the following code within the MainActivity class!

MainActivity.java

package com.example;

import android.os.Bundle;
import android.util.Log;
import org.apache.cordova.*;

public class MainActivity extends DroidGap {
	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("PhoneGapAccelerometerApp", "onCreate: Entered method.");
		super.loadUrl("file:///android_asset/www/index.html");
	}
}

Next, let’s create an index.html file for PhoneGap to load. It will be used to display the accelerometer values on screen.

assets/www/index.html

<html>
<head> 

<script src="scripts/cordova.js" type="text/javascript"></script>
<script src="scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="scripts/jquery.mobile-1.0.1.min.js" type="text/javascript"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="css/jquery.mobile-1.0.1.min.css" />
<script type="text/javascript">
 
    var sensorAcc = null;
 
    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {
        var options = { frequency: 80 };

        sensorAcc = navigator.accelerometer.watchAcceleration(accelerometerSuccess, accelerometerError, options);
    }
	
	function accelerometerError() {
        alert('Failed to load accelerometer!');
    }
	
	function accelerometerSuccess(acceleration) {        
        var str = 'Acceleration X: ' + acceleration.x + '<br />' +
                  'Acceleration Y: ' + acceleration.y + '<br />' +
                  'Acceleration Z: ' + acceleration.z + '<br />';
        $('div.result').html(str); 
    }
	
</script>
</head>
<body>

<div class='result'> </div>

</body>
</html>

res/xml/config.xml

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

    <access origin="http://127.0.0.1*"/> <!-- allow local pages -->

    <content src="index.html" />

    <log level="DEBUG"/>
    <preference name="useBrowserHistory" value="true" />
    <preference name="exit-on-suspend" value="false" />
    
  <plugins>
    <plugin name="App" value="org.apache.cordova.App"/>
    <plugin name="Geolocation" value="org.apache.cordova.GeoBroker"/>
    <plugin name="Device" value="org.apache.cordova.Device"/>
    <plugin name="Accelerometer" value="org.apache.cordova.AccelListener"/>
    <plugin name="Compass" value="org.apache.cordova.CompassListener"/>
    <plugin name="Media" value="org.apache.cordova.AudioHandler"/>
    <plugin name="Camera" value="org.apache.cordova.CameraLauncher"/>
    <plugin name="Contacts" value="org.apache.cordova.ContactManager"/>
    <plugin name="File" value="org.apache.cordova.FileUtils"/>
    <plugin name="Notification" value="org.apache.cordova.Notification"/>
    <plugin name="Storage" value="org.apache.cordova.Storage"/>
    <plugin name="FileTransfer" value="org.apache.cordova.FileTransfer"/>
    <plugin name="Capture" value="org.apache.cordova.Capture"/>
    <plugin name="Battery" value="org.apache.cordova.BatteryListener"/>
    <plugin name="SplashScreen" value="org.apache.cordova.SplashScreen"/>
    <plugin name="Echo" value="org.apache.cordova.Echo" />
    <plugin name="Globalization" value="org.apache.cordova.Globalization"/>
    <plugin name="InAppBrowser" value="org.apache.cordova.InAppBrowser"/>
	<plugin name="SpeechRecognizer" value="com.example.SpeechRecognizer"/>   
  </plugins>

</cordova>


Do not forget to add the cordova.js and cordova.jar files to your project. As seen from the above code, the accelerometer.watchAcceleration gets the device’s current acceleration at a regular interval. Each time the Acceleration is retrieved, the accelerometerSuccess callback function is executed. You need to specify the interval in milliseconds via the frequency parameter in the acceleratorOptions object.

Finally, save and run the application on an Android device and you should see the following output!

phonegap_accelerometer

Source code for this tutorial can be found over here

Display ProgressBar in Android

Hey everyone!

A ProgressBar is basically a visual indicator of progress in some operation. Implementing a ProgressBar helps in the understanding of processes running on threads separate from the main User Interface (UI) and the communication between threads. As mentioned on the Android developer’s page, a progress bar can also be made indeterminate. In indeterminate mode, the progress bar shows a cyclic animation without an indication of progress. This mode is used by applications when the length of the task is unknown.

By default the progress bar is a spinning wheel (an indeterminate indicator). We can always change to a horizontal progress bar using the Widget.ProgressBar.Horizontal style as follows,

<ProgressBar
     style="@android:style/Widget.ProgressBar.Horizontal"
     ... />

More such styles can be found over here. Through this post, we will learn how to display a ProgressBar in Android.

Pre-requisites: Eclipse IDE, Android SDK

Create a new Activity class called MyProgressBarActivity in any of your existing Android projects and add the following code!

MyProgressBarActivity.java

package com.example;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MyProgressBarActivity extends Activity {

	private ProgressBar progBar;
	private Handler mHandler = new Handler();;
	private int mProgressStatus = 0;
	private Button showProgressBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		progBar= (ProgressBar)findViewById(R.id.progBar1);
		showProgressBar= (Button)findViewById(R.id.btn1);
		showProgressBar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				doSomeWork();
			}
		});

	}

	public void doSomeWork(){

		// Start lengthy operation in a background thread
		new Thread(new Runnable() {
			public void run() {
				while (mProgressStatus < 100) {
					mProgressStatus += 1;
					// Update the progress bar
					mHandler.post(new Runnable() {
						public void run() {
							progBar.setProgress(mProgressStatus);
						}
					});
					try {
						//Display progress slowly
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}

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:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/btn1"
        android:layout_below="@+id/txt1"
        android:text="@string/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    
       <ProgressBar
         android:id="@+id/progBar1"
         android:layout_below="@+id/btn1"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         style="@android:style/Widget.ProgressBar.Horizontal"
         android:layout_marginRight="15dp" />
        
</RelativeLayout>

Run the Android application by specifying the above Activity as the default launcher Activity and you should see the ProgressBar in action! 🙂

android_progressbar_1

android_progressbar_2

Hope this helps someone. Thanks for visiting! 🙂

Tutorial #71: Implement lock screen in Android

In general, there are several ways to lock a screen. One can use the PowerManager class along with the WAKE_LOCK permission and provide a certain amount of time for the device to go to sleep. Reducing the screen brightness to zero can also help to automatically turn off the screen. Both these approaches may prove useful at times but what if you want to develop your own lock screen application? One can’t just keep reducing the screen brightness. To solve this, we could make our application run as an Administrator by providing device administration features at the system level.

Android provides the Device Administration API enabling developers to use the device management services and applications. In this tutorial, we will learn how to implement the lock screen functionality in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create Android project

Launch Eclipse IDE and create a new Android application project called AndroidLockScreenDemo with package name com.example

Step 2: Create Activity class

Create a new Activity class called MyLockScreenActivity within the above package and add the following code!

MyLockScreenActivity.java

package com.example;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MyLockScreenActivity extends Activity implements OnClickListener {

	private static final int ADMIN_INTENT = 15;
	private static final String description = "Sample Administrator description";
	private DevicePolicyManager mDevicePolicyManager; 
	private ComponentName mComponentName;  

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lock);
		mDevicePolicyManager = (DevicePolicyManager)getSystemService(  
				Context.DEVICE_POLICY_SERVICE);  
		mComponentName = new ComponentName(this, MyAdminReceiver.class);  
		Button btnEnableAdmin = (Button) findViewById(R.id.btnEnable);
		Button btnDisableAdmin = (Button) findViewById(R.id.btnDisable);
		Button btnLock = (Button) findViewById(R.id.btnLock);
		btnEnableAdmin.setOnClickListener(this);
		btnDisableAdmin.setOnClickListener(this);
		btnLock.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnEnable:
			Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
			intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
			intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,description);
			startActivityForResult(intent, ADMIN_INTENT);
			break;

		case R.id.btnDisable:
			mDevicePolicyManager.removeActiveAdmin(mComponentName);  
			Toast.makeText(getApplicationContext(), "Admin registration removed", Toast.LENGTH_SHORT).show();
			break;

		case R.id.btnLock:
			boolean isAdmin = mDevicePolicyManager.isAdminActive(mComponentName);  
			if (isAdmin) {  
				mDevicePolicyManager.lockNow();  
			}else{
				Toast.makeText(getApplicationContext(), "Not Registered as admin", Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ADMIN_INTENT) {
			if (resultCode == RESULT_OK) {
				Toast.makeText(getApplicationContext(), "Registered As Admin", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(getApplicationContext(), "Failed to register as Admin", Toast.LENGTH_SHORT).show();
			}
		}
	}

}

activity_lock.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=".MyLockScreenActivity">

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

    <Button
        android:id="@+id/btnEnable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Enable"
        android:layout_below="@+id/txt1"/>

    <Button
        android:id="@+id/btnDisable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Disable"
        android:layout_below="@+id/btnEnable"/>

    <Button
        android:id="@+id/btnLock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Lock"
        android:layout_below="@+id/btnDisable"/>

</RelativeLayout>

Step 3: Add lock policy and create receiver

Create a new folder called xml inside the project and add an XML file for exercising admin rights called admin.xml containing the following code!

<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
    <uses-policies>
        <force-lock />
    </uses-policies>
</device-admin>

You also need to create an empty Receiver class that will extend the DeviceAdminReceiver. I am going to name my class as MyAdminReceiver.

MyAdminReceiver.java

package com.example;

import android.app.admin.DeviceAdminReceiver;

public class MyAdminReceiver extends DeviceAdminReceiver{

}

In this case, one needs to update the AndroidManifest.xml file and add the Receiver entry as follows!

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MyLockScreenActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="MyAdminReceiver"
            android:permission="android.permission.BIND_DEVICE_ADMIN">
            <meta-data
                android:name="android.app.device_admin"
                android:resource="@xml/admin"/>

            <intent-filter>
                <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
            </intent-filter>
        </receiver>
        
    </application>

</manifest>

Save all changes and make sure no errors are present. Finally, run the application on an Android device and you should now be able to lock your screen through code! 🙂

lock_screen_1

lock_screen_2

Source code for this tutorial can be found over here

Detect and use light and gyroscope sensors in Android

Hello everyone!

Sensors play a vital role in any electronic device and more importantly help in detecting or measuring a physical property. Nowadays, Android phones come equipped with a range of sensors including light, pressure, temperature, gyroscope, proximity etc. Developers need to build applications using the functionality of these sensors. For that purpose, one needs to learn how to detect and implement the corresponding sensor functionality.

Through this post, we will understand how to detect and use the Light and Gyroscope sensors in Android.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Create a new Android application project called AndroidSensorsDemo with package name com.example

Step 2: Create Activity class

We will first create an Activity class called MySensorActivity in our existing package and add the following code!

MySensorActivity.java

package com.example;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;

public class MySensorActivity extends Activity implements SensorEventListener {

	private TextView tv;
	private SensorManager mSensorManager;
	private Sensor mGyroSensor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		tv= (TextView)findViewById(R.id.txt2);
		// Get an instance of the sensor service
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mGyroSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
		
		PackageManager PM= this.getPackageManager();
		boolean gyro = PM.hasSystemFeature(PackageManager.FEATURE_SENSOR_GYROSCOPE);
		boolean light = PM.hasSystemFeature(PackageManager.FEATURE_SENSOR_LIGHT);
		
		if(gyro){
			
			if(light){
				Toast.makeText(getApplicationContext(),"Both light and gyroscope sensors are present", Toast.LENGTH_LONG).show();
			}
			else
				Toast.makeText(getApplicationContext(),"Only gyroscope sensor is present", Toast.LENGTH_LONG).show();
			
		}
	}

	@Override
	public final void onAccuracyChanged(Sensor sensor, int accuracy) {
		// Do something if sensor accuracy changes.
	}

	@Override
	public final void onSensorChanged(SensorEvent event) {

		float angularXSpeed = event.values[0];
		tv.setText("Angular X speed level is: " + "" +angularXSpeed); 
	}

	@Override
	protected void onResume() {
		// Register a listener for the sensor.
		super.onResume();
		mSensorManager.registerListener(this, mGyroSensor, SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	protected void onPause() {
		// important to unregister the sensor when the activity pauses.
		super.onPause();
		mSensorManager.unregisterListener(this);
	}

}

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=".MySensorActivity">

    <TextView
        android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"/>
    
	<TextView
        android:id="@+id/txt2"
        android:layout_below="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>    

</RelativeLayout>

Note: The above code displays values for a Gyroscope sensor. For using the light sensor, you just need to register the Light sensor instead of the Gyroscope sensor. The availability of sensors varies from device to device. Try and find out the sensors present in your device.

Finally, no changes are to be made to the AndroidManifest.xml file. Save and run the application on an Android device and you should the following output!

sensors_demo_1

sensors_demo_2

Reference: Android Sensors

Using TextSwitcher and ImageSwitcher in Android

Hello everyone!

Sometimes, we need to apply different animations to our mobile content in order to make the transitions across pages look more visually appealing. Android provides developers two classes namely TextSwitcher and ImageSwitcher in order to have a transition animation in an Android View.

As mentioned on the developer’s page, a TextSwitcher is a specialized ViewSwitcher that contains only children of type TextView. It is used to animate a label on screen. Whenever the setText(CharSequence) method is called, TextSwitcher animates the current text out and animates the new text in. TextView and TextSwitcher work in a similar way. Similarly, an ImageSwitcher replaces an ImageView.

Through this post, we will learn how to implement TextSwitcher and ImageSwitcher in Android.

Pre-requisites: Eclipse IDE, Android SDK

Create a new Android application project called AndroidSwitcherDemo with package name com.example

Now, let’s create an Activity class called MyTextSwitcherActivity for implementing TextSwitcher as follows!

MyTextSwitcherActivity.java

package com.example;

import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
import android.app.Activity;
import android.graphics.Color;

public class MyTextSwitcherActivity extends Activity {

	private TextSwitcher textSwitcher;
	private Button b;

	String myContent[]={"A","B","C","D"};

	//used to keep track of text index
	int currentIndex=-1; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_text_switcher);

		textSwitcher = (TextSwitcher)findViewById(R.id.textSwitcher);
		b= (Button)findViewById(R.id.btn1);

		//set ViewFactory of TextSwitcher to dynamically create TextView
		textSwitcher.setFactory(new ViewFactory() {

			public View makeView() {
				// TODO Auto-generated method stub
				// create new textView 
				TextView myText = new TextView(MyTextSwitcherActivity.this);
				myText.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
				myText.setTextSize(42);
				myText.setTextColor(Color.RED);
				return myText;
			}
		});

		// Declare the in and out animations
		Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
		Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right);

		// set the animation of textSwitcher
		textSwitcher.setInAnimation(in);
		textSwitcher.setOutAnimation(out);

		//button click
		b.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				currentIndex++;
				// If index reaches maximum reset it
				if(currentIndex==myContent.length)
					currentIndex=0;
				textSwitcher.setText(myContent[currentIndex]);
			}
		});

	}
}

activity_text_switcher.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=".MyTextSwitcherActivity" >

    <TextView
        android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text_switcher" />

    <TextSwitcher
        android:id="@+id/textSwitcher"
        android:layout_below="@+id/txt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp" />

    <Button
        android:id="@+id/btn1"
        android:layout_below="@+id/textSwitcher"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:text="Next" />

</RelativeLayout>

Similarly, create another Activity class within the same package called MyImageSwitcherActivity for implementing ImageSwitcher as follows!

MyImageSwitcherActivity.java

package com.example;

import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
import android.app.Activity;
import android.view.ViewGroup.LayoutParams;

public class MyImageSwitcherActivity extends Activity {

	private ImageSwitcher imageSwitcher;
	private Button b;

	int myContent[]={R.drawable.android_pic1,R.drawable.android_pic2,R.drawable.android_pic3,R.drawable.android_pic4};

	//used to keep track of image index
	int currentIndex=-1; 

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_switcher);

		imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher);
		b= (Button)findViewById(R.id.btn1);

		//set ViewFactory of imageSwitcher to dynamically create imageView
		imageSwitcher.setFactory(new ViewFactory() {

			public View makeView() {
				// TODO Auto-generated method stub
				// create new imageView 
				ImageView myImage = new ImageView(MyImageSwitcherActivity.this);
				myImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
				LayoutParams params = new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
				myImage.setLayoutParams(params);
				return myImage;
			}
		});

		// Declare the in and out animations
		Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
		Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right);

		// set the animation of imageSwitcher
		imageSwitcher.setInAnimation(in);
		imageSwitcher.setOutAnimation(out);

		//button click
		b.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (currentIndex == myContent.length - 1) {
					currentIndex = 0;
					imageSwitcher.setImageResource(myContent[currentIndex]);
				} else {
					imageSwitcher.setImageResource(myContent[++currentIndex]);
				}
			}
		});
	}
}

activity_image_switcher.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=".MyTextSwitcherActivity" >

    <TextView
        android:id="@+id/txt1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/image_switcher" />

    <ImageSwitcher
        android:id="@+id/imageSwitcher"
        android:layout_below="@+id/txt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dp" />

    <Button
        android:id="@+id/btn1"
        android:layout_below="@+id/imageSwitcher"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:text="Next" />

</RelativeLayout>

Finally, save all changes. Make sure no errors are present. Run each of the above Activity classes as the default launcher Activity and you should see the following output!

textswitcher

image_switcher

That’s it for this Android development tip. Stay tuned for more! 🙂

Autostart application at bootup in Android

In Android, we may sometimes come across a situation where in we want our application to run as soon as the mobile device starts or boots up. For this to happen, we need to listen to the BOOT_COMPLETED action. This action is broadcasted once, after the system has finished booting. It can be used to perform application-specific initialization, such as installing alarms.

Through this post, we will learn how to autostart an application at bootup.

Pre-requisites: Eclipse IDE, Android SDK

Create an Activity class named MyAutoStartActivity with package name com.example in any of your existing Android projects.

Next, we need to add a BroadcastReceiver that will listen to the boot event and respond accordingly. In this case, our AndroidManifest.xml file will look something like this,

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MyAutoStartActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".MyBootReceiver"
            android:enabled="true"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

    </application>
</manifest>

We also need to add the corresponding Receiver class as follows!

package com.example;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyBootReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Intent i = new Intent(context, MyAutoStartActivity.class);  
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(i);  
	}

}

Do not forget to add the android.permission.RECEIVE_BOOT_COMPLETED to your manifest file. Save all changes and make sure no errors are present. This will help make your Android application start when the device is booted! 🙂

Reference: Boot Action, Android Intent

.

Tutorial #70: Testing Android code using Robotium test automation framework

Hi everyone!

Robotium is one of the popular test automation frameworks used for writing black-box tests for Android applications. The advantage of using Robotium is that it can used both for testing applications where the source code is available and applications where only the APK file is available. It is pretty similar to Selenium but supports Android features such as Activities, menus etc.

In this tutorial, we will learn how to get started with Robotium for Android by creating a sample Test project to test our existing Android source code.

Pre-requisites: Eclipse IDE, Android SDK

Step 1: Download Robotium

In order to setup Robotium for Android, you need to obtain the latest version of the Robotium framework from over here. We will add the downloaded .jar file to our Android Test project later.

Step 2: Create new Test project

Open Eclipse IDE and create a new Android Test project called AndroidRobotiumDemo. Select an existing workspace project to be tested and click OK. Add the Robotium .jar to your Test project.

Step 3: Create new Test class

Robotium extends the Android test framework to make it simpler to write tests. The main class for testing with Robotium is Solo. Solo is initialized with the instrumentation of the testcase and the first activity to test. Let’s create our own Test class as follows,

MyTestClass.java

package com.example;


import com.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.EditText;
import android.widget.TextView;

public class MyTestClass extends ActivityInstrumentationTestCase2<TestActivity>{


	private Solo solo;

	public MyTestClass() {
		super(TestActivity.class);
	}

	public void setUp() throws Exception {
		solo = new Solo(getInstrumentation(), getActivity());
	}

	public void testCase() throws Exception {

		String vResult="TestExample";
		EditText vEditText = (EditText) solo.getView(R.id.edit1);
		solo.clearEditText(vEditText);
		solo.enterText(vEditText,"TestExample");
		solo.clickOnButton("Submit");

		assertTrue(solo.searchText(vResult));
		TextView textField = (TextView) solo.getView(R.id.txt1);
		//Assert to verify result with visible value
		assertEquals(vResult, textField.getText().toString());
	}

	@Override
	public void tearDown() throws Exception {
		solo.finishOpenedActivities();
	}

}

Save all changes. Make sure no errors are present. Now, run the test case. If the test case is successful, you should see the following output!

test_case_output

snapshot_device

You can download the source code for this tutorial from over here.

Reference: Getting Started with Robotium

Compress files in ZIP format using Java

Hello everyone!

In general, zipping files is a process by which multiple files can be bundled together as a single file. It is possible to compress and decompress data using tools such as WinZip, gzip, and Java ARchive (or jar). These tools are themselves used as standalone applications. However, Java provides developers the java.util.zip package in order to compress and decompress data on the fly.

Through this example, we will learn how to implement a Java class to perform data file compression in ZIP format.

Create a new Java class called TestZipExample in any of your existing Java console application projects and add the following code!

package com.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class TestZipExample
{	
	public static void main( String[] args )
	{

		File file1= new File("C:\\programs\\java_zip_example\\sample.html");
		File file2= new File("C:\\programs\\java_zip_example\\test_slide.html");
		
		List<File> myFiles= new ArrayList<File>();
		
		myFiles.add(file1);
		myFiles.add(file2);
		
		createZip(myFiles, "C:\\programs\\java_zip_example\\test.zip");
		
		System.out.println("Done zipping the files..!");
	}

	public static File createZip(List<File> files, String filename) {
		File zipfile = new File(filename);
		// buffer for reading the files
		byte[] buf = new byte[1024];
		try {
			// create ZIP file
			ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
			// begin compressing the files
			for(int i=0; i<files.size(); i++) {
				
				FileInputStream in = new FileInputStream("C:\\programs\\java_zip_example\\" + files.get(i).getName());
				// add ZIP entry to output stream
				out.putNextEntry(new ZipEntry(files.get(i).getName()));
				int len;
				while((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				in.close();
			}
			//don't forget to close the output stream
			out.close();
			return zipfile;
		} catch (IOException ex) {
			System.err.println(ex.getMessage());
		}
		return null;
	}
}

Finally, make sure no errors are present. Save and run the application. You should see the ZIP file created in your target directory.

console_output

Reference: Java ZipFile

Connect to MySQL database using JDBC

Java DataBase Connectivity (JDBC) is basically a data access technology that provides an API to help define how a client may access a database. In addition, the API helps in loading appropriate Java packages with the JDBC Driver Manager. The DriverManager class is used as a connection factory for creating JDBC connections.

It mainly provides three types of statements:

1. Statement

It can be used for general-purpose access to the database. It is useful when you are using static SQL statements at runtime.

2. PreparedStatement

It can be used when you plan to use the same SQL statement many times. The PreparedStatement interface accepts input parameters at runtime.

3. CallableStatement

CallableStatement can be used when you want to access database stored procedures.

Pre-requisites: Eclipse IDE, Windows 7 OS (64 bit)

Through this post, we will learn how to create a connection to an existing MySQL database using JDBC. You need to first download and setup an instance of the latest version of the MySQL database. For that purpose, you need to install and configure MySQL on Windows.

Next, you need to obtain the MySQL Java connector for the appropriate database version and operating system from over here. Now, let’s create a new Java console application project named TestMySqlExample.

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

TestMySqlConnection.java

package com.example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TestMySqlConnection {

	public static void main(String[] argv) {

		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return;
		}

		Connection connection = null;

		try {
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database_name","mysql_user", "mysql_password");

		} catch (SQLException e) {
			System.out.println("Connection Failed!");
			e.printStackTrace();
			return;
		}

		if (connection != null) {
			System.out.println("Connected to database!");
		} else {
			System.out.println("Connection Failed!");
		}
	}
}

Finally, save and run the application. If the connection is successful, you should get a message in the Console window in Eclipse.

mysql_jdbc_demo