Implement Lightbox using jQuery plugin!

Hi guys!

Lightbox is a well-known JavaScript technique used to display images or any web content using modal dialogs. Not too long ago, the lightbox plugin was written in jQuery that allowed developers to modify the code and come up with new plugins that carry out the same task.

Colorbox is one such jQuery plugin that we can use to implement a lightbox. Through this post, I will try to implement a sample HTML page that displays a lightbox using the Colorbox plugin.

test.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="generator"
    content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <title>LightBox Demo</title>
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.4.3/example1/colorbox.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.4.3/jquery.colorbox.js"></script>
  </head>
  <body>
    <div class="container">
      <a href="#ShowLightBox" class="colorbox-element">Show LightBox</a>
    </div>
    <br />
    <div style="display:none">
      <div id="ShowLightBox" style="margin:0 auto;padding:10px; background:#fff;">
        <!--sample form -->
        <div class="panel panel-info">
          <div class="panel-heading">
            <div class="row">
              <div class="col-md-10">
                <h3 class="panel-title">My Form</h3>
              </div>
            </div>
          </div>
        </div>
        <div class="form-group">
        <label>Name:</label> 
        <input type="text" placeholder="Name of the customer" class="form-control" /></div>
        <div class="form-group">
        <label>Phone:</label> 
        <input type="text" placeholder="Phone of the customer" class="form-control" /></div>
        <a href="#" class="btn btn-default">Submit</a>
      </div>
    </div>
    <script>
      $(document).ready(function($) {
            $(".colorbox-element").colorbox({inline:true, width:"70%", height:"95%"});
      });   
        
</script>
  </body>
</html>

Save and open the above web page in any browser and you should see the following output!

lightbox_demo

Tutorial #65: Implement barcode scanner using ZXing in Android

Hello everyone!

ZXing is a popular open-source barcode image processing library implemented in Java. It is capable of porting to many other programming languages as well. The library is divided into several components but for the purpose of this tutorial we would be using two components namely core and android.

core: The core image decoding library, and test code.

android: Android client, called Barcode Scanner.

In this tutorial, we will learn how to implement a barcode scanner application using ZXing on the Android platform.

Pre-requisites: Android SDK, ZXing library and Eclipse IDE

Step 1: Download ZXing library

Developers can download the latest version of the library from over here. The downloaded .zip file needs to be extracted. After extracting the ZXing source, you should see the following contents!

zxing_folder_structure

Step 2: Import ZXing Android project

You need to import the ZXing Android project in Eclipse. Once imported right click the Project –> Properties –> Android and tick mark the Is Library checkbox. Also, create a new folder called libs within the project and add the core.jar file. The core.jar can be downloaded from over here.

zxing_library_project

Step 3: Create new Android application project

Next, you need to create a new Android application project named BarCodeScanner with package name com.example and target SDK Android 4.2.2. Once again add the core.jar file inside the libs folder of your project. Right click the Project –> Properties –> Android and add the above ZXing project as a library.

adding_zxing_library_project

Now, add the following code in the MainActivity.java and AndroidManifest.xml files.

MainActivity.java

package com.example;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

	private Button scan;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		scan= (Button)findViewById(R.id.btnScan);
		
		scan.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub	
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
				startActivityForResult(intent, 0);
			}
		});
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		   if (requestCode == 0) {
		      if (resultCode == RESULT_OK) {
		         
		    	 String contents = intent.getStringExtra("SCAN_RESULT");
		         String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
	         
		         // Handle successful scan
		         		                  
		      } else if (resultCode == RESULT_CANCELED) {
		         // Handle cancel
		    	 Log.i("App","Scan unsuccessful");
		      }
		 }
	  }
	
	@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;
	}
}

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="10"
        android:targetSdkVersion="18" />

    <uses-permission android:name="android.permission.CAMERA"/>
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity
               android:name="com.google.zxing.client.android.CaptureActivity"
			   android:screenOrientation="landscape"
			   android:configChanges="orientation|keyboardHidden"
			   android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
			   android:windowSoftInputMode="stateAlwaysHidden">
			   <intent-filter>
			      <action android:name="android.intent.action.MAIN"/>
			      <category android:name="android.intent.category.DEFAULT"/>
			   </intent-filter>
			   <intent-filter>
			      <action android:name="com.google.zxing.client.android.SCAN"/>
			      <category android:name="android.intent.category.DEFAULT"/>
			   </intent-filter>
		</activity>
    </application>
</manifest>

Finally, run the project on an Android device. Try scanning any QR code and you should see the desired result!

barcode_scanner

UPDATE:

In case you experience an application force close error then make sure you have added the ZXing library project as mentioned in this link.

Displaying Toast message in an IntentService!

Hi everyone!

In one of my projects, I am trying to display a Toast message in a Service class. I am using an IntentService, which is a base class for Services and is used to handle requests on demand. In this class all requests are handled on a single worker thread that processes only one request at a time.

Initially, I wrote the code for displaying the Toast message in the following manner:

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class TestService extends IntentService {
	
	public TestService(String name) {
	          // TODO Auto-generated constructor stub
	          super(name);
	}
	
	public TestService () {
	      super("TestService");
	}
	
	@Override
	protected void onHandleIntent(Intent intent) {
	   
	      Toast.makeText(getApplicationContext(), "Handling Intent...", Toast.LENGTH_LONG).show();
	     //Handle intent over here	
	 	
	}	
}

In this case, although the onHandleIntent method was called, my Toast message would never get displayed. It is due to the fact that the IntentService would spawn only a single thread. Hence, in order to display the Toast message I needed to create another different thread using a Handler.

Here is what my working code now looks like. Finally, I get to see the Toast notification! ๐Ÿ™‚

package com.example;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;


public class TestService extends IntentService {

	
	private Handler handler;  
	       
	public TestService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}
	
	public TestService () {
		  super("TestService");	
    }

			  
	@Override  
	public int onStartCommand(Intent intent, int flags, int startId) {  
	   handler = new Handler();  
	   return super.onStartCommand(intent, flags, startId);  
	}  
	
	@Override
	protected void onHandleIntent(Intent intent) {
          // TODO Auto-generated method stub
	     handler.post(new Runnable() {  
		        @Override  
		        public void run() {  	   
                            Toast.makeText(getApplicationContext(), "Handling Intent..", Toast.LENGTH_LONG).show(); 
	            }  
	      });   
     } 
}

Hope this helps you in some way. I will be sharing many more such useful tips in future as well. ๐Ÿ™‚

Implement notification alerts using PhoneGap!

Hey everyone!

In my previous post, I spoke about the PhoneGap framework and how one can start using it for Android. In this post I will implement a basic Notification alert using the PhoneGap API.

Step 1: Create config.xml

You need to create a config.xml file under the assets/www folder and include the following content!

<?xml version="1.0" encoding="UTF-8"?>

<feature name="Notification">
  <param name="wp-package" value="Notification"/>
</feature>

Step 2: Make changes to existing HTML page

Now, let’s modify our previous HTML page to include a button and the PhoneGap notification alert.

<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>

<script>

function showAlert(){

navigator.notification.alert("This is a test alert!", test , "New Alert" , "OK")

}


function test(){
   //do something
}

</script>
</head>
<body>
<h1>Test PhoneGap</h1>

<input type="button" onclick="showAlert();" id="btn" value="Click me to display alert"/>

</body>
</html>

Syntax for notification.alert method

navigator.notification.alert(message, alertCallback, [title], [buttonName]) 

where,

message: Dialog message (String)
alertCallback: Callback to invoke when alert dialog is dismissed. (Function)
title: Dialog title (String) (Optional, Default: “Alert”)
buttonName: Button name (String) (Optional, Default: “OK”)

When you click the button, you should see the following output!

phonegap_navigation_alert

Reference: PhoneGap Notification

Tutorial #64: Setting up Sony Add-on SDK for Android

Hey everyone!

Electronic devices are getting smaller day by day. Earlier what could be done using a smartphone can now also be done using a smartwatch. Sony recently announced SmartWatch 2 and has provided API’s for developers to build Android applications specifically for the device. It is important to note that the SmartWatch is not an Android device and hence doesn’t run the Android operating system. It is mainly capable of pairing with any Android device supporting the Bluetooth functionality.

In this tutorial, we will learn how to install and setup the Sony Add-on SDK for Android.

Pre-requisites: Eclipse IDE, Android SDK, Sony Smartwatch (version 1)

Step 1: Download Sony Add-on SDK

First, you need to download and install the SDK. Please follow these steps mentioned on the developer’s website.

Step 2: Import project in Eclipse

Once you have downloaded the Sony Add-on SDK, you should see a new folder created under path-to-android-sdk/add-ons directory. Browse through and import any one of the projects in Eclipse. For this tutorial, I will go for the SampleWidgetExtension project.

sony_sdk_folder

Note: Sony Smartwatch API’s can be used only with devices running Android 4.0 and higher.

Step 3: Installing SmartConnect application

Before you run the Android application, you need to download the Sony SmartConnect application (also known as LiveWare manager) from the play store. In addition, you also need to download and install the official Sony SmartWatch app.

Step 4: Pair the Smartwatch with the device

Using Bluetooth, pair the Smartwatch with your Android device. Once paired the SmartConnect application should open. At this point, you could also install third party applications like Twitter, Facebook, messaging, call handling etc.

Finally, run the application on an Android device using the USB debugging feature. If no errors are present and the installation was successful, then you would see a new time widget displayed on the smartwatch.

sony_sdk_1

sony_sdk_2

That’s it for now. Next we will start playing around with the Sony API’s ๐Ÿ™‚

jQuery mobile: Page loading widget

Hey everyone!

jQuery mobile provides a navigation system that can display pages with a set of animated transitions. Now, developers can add various transitions including fade, pop, flip, turn etc to their web pages. However, when you carry out a background task that consumes a lot of time, it is advisable to display a Page Loading widget. This widget handles the task of displaying the loading dialog.

Here is a short demo of the Page loading widget!

test.html


<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>

<script type="text/javascript">

function showIndicator(){
$.mobile.loading( 'show', {
	text: 'Loading...',
	textVisible: true,
	theme: 'b',
	html: ""
   });
}

function hideIndicator(){
$.mobile.loading( 'hide');
}

</script>

</head>
<body>

<input type="button" value="Click me" onclick="showIndicator();"/>
<input type="button" value="Hide me" onclick="hideIndicator();"/>

</body>
</head>

</html>

The result looks something like this,

output

Note: The page loading dialog was previously configured globally with three settings $.mobile.loadingMessage, $.mobile.loadingMessageTextVisible, and $.mobile.loadingMessageTheme which are now deprecated. In addition to the methods for showing and hiding, $.mobile.showPageLoadingMsg and $.mobile.hidePageLoadingMsg are also deprecated.

Source: jQuery mobile website

Getting started with PhoneGap!

Hello guys,

In recent times, the number of cross platform mobile applications is gradually increasing with more and more developers trying to run their applications on the various mobile platforms. In these situations, PhoneGap is one of the popular solutions out there allowing developers to create applications using web technologies like HTML, CSS and JavaScript. It is free and open source and can be installed from over here.

Through this post, we will learn how to start using PhoneGap for Android!

Pre-requisites: Eclipse IDE, PhoneGap version 2.7.0

Step 1: Create a new Android Project

Open Eclipse IDE and create a new Android Application project named TestPhoneGap with package name com.example

Step 2: Add PhoneGap files

Create a new folder called www under the assets folder and add the cordova javascript file (cordova-2.7.0.js) inside it. Also, add the cordova-2.7.0 jar file inside the libs folder of your Android project.

Step 3: Create HTML page

Create a new HTML page named index.html under assets/www folder with a simple test message!

Step 4: Modify Activity class and AndroidManifest files

Finally, you need to make changes to your MainActivity class and the AndroidManifest.xml as follows!

MainActivity.java

package com.example;

import org.apache.cordova.Config;
import org.apache.cordova.DroidGap;
import android.os.Bundle;

public class MainActivity extends DroidGap {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		super.loadUrl(Config.getStartUrl());

	}	
}

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">
   
    <supports-screens android:largeScreens="true"
	android:normalScreens="true"
	android:smallScreens="true"
	android:resizeable="true"
	android:anyDensity="true"/>
      
    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="17"/>

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

Save all files and make sure no errors are present. When you run the application, you should see the following output!

test_phonegap