Get Contact Details Android

العربية: Android logo
Get Contact Details (ID, Name, Phone, Photo)

res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent" >
    <Button android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Select a Contact"
            android:onClick="onClickSelectContact" />
    <ImageView android:id="@+id/img_contact"
               android:layout_height="wrap_content"
               android:layout_width="match_parent"
               android:adjustViewBounds="true"
               android:contentDescription="Contacts Image"
                />
</LinearLayout>

Read More »

Microsoft and Client Remote Desktop for Android

Before establish connection between host PC and remote client app, you have to setup in both PC side and client side.

Set up your Remote Desktop in host PC. (This example running Windows 8.1 Pro)

– Enter “Remote Desktop” in Search, select “Select users who can use remote desktop“.

– Under Remote tab, enable “Allow remote connections to this computer” under Remote Desktop. Click the “Select Users” button.

Read More »

Creating a Mobile Event Calendar

Mobile-Calendar_Preview
This tutorial describes how to build an HTML5-based mobile calendar to track conferences and events that run on iOS and Android phones using a mobile version of dhtmlxScheduler (open source, GPL). At the end, users will be able to add and edit events, select the conference location on Google Maps, and see the events in day, month, or list views….

Read More »

 

Create a RESTful Services API in PHP.

Are you working with multiple devices like iPhone, Android and Web then take a look at this post that explains you how to develop a RESTful API in PHP.  Representational state transfer (REST) is a software system for distributing the data to different kind of applications. The web service system produce status code response in JSON or XML format.
Create a RESTful Services API in PHP.


Download Script

Database
Sample database users table columns user_id, user_fullname, user_email, user_password and user_status.

CREATE TABLE IF NOT EXISTS `users`
(
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_fullname` varchar(25) NOT NULL,
`user_email` varchar(50) NOT NULL,
`user_password` varchar(50) NOT NULL,
`user_status` tinyint(1) NOT NULL DEFAULT ‘0’,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Rest API Class: api.php
Contains simple PHP code, here you have to modify database configuration details like database name, username and password.

<?php
require_once(“Rest.inc.php”);class API extends REST
{
public $data = “”;
const DB_SERVER = “localhost”;
const DB_USER = “Database_Username”;
const DB_PASSWORD = “Database_Password”;
const DB = “Database_Name”;private $db = NULL;

public function __construct()
{
parent::__construct();// Init parent contructor
$this->dbConnect();// Initiate Database connection
}

//Database connection
private function dbConnect()
{
$this->db = mysql_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD);
if($this->db)
mysql_select_db(self::DB,$this->db);
}

//Public method for access api.
//This method dynmically call the method based on the query string
public function processApi()
{
$func = strtolower(trim(str_replace(“/”,””,$_REQUEST[‘rquest’])));
if((int)method_exists($this,$func) > 0)
$this->$func();
else
$this->response(”,404);
// If the method not exist with in this class, response would be “Page not found”.
}

private function login()
{
…………..
}

private function users()
{
…………..
}

private function deleteUser()
{
………….
}

//Encode array into JSON
private function json($data)
{
if(is_array($data)){
return json_encode($data);
}
}
}

// Initiiate Library
$api = new API;
$api->processApi();
?>

Login POST
Displaying users records from the users table Rest API URL http://localhost/rest/login/. This Restful API login status works with status codes if status code 200 login success else status code 204 shows fail message. For more status code information check Rest.inc.php in download script.

private function login()
{
// Cross validation if the request method is POST else it will return “Not Acceptable” status
if($this->get_request_method() != “POST”)
{
$this->response(”,406);
}$email = $this->_request[’email’];
$password = $this->_request[‘pwd’];// Input validations
if(!empty($email) and !empty($password))
{
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$sql = mysql_query(“SELECT user_id, user_fullname, user_email FROM users WHERE user_email = ‘$email’ AND user_password = ‘”.md5($password).”‘ LIMIT 1″, $this->db);
if(mysql_num_rows($sql) > 0){
$result = mysql_fetch_array($sql,MYSQL_ASSOC);

// If success everythig is good send header as “OK” and user details
$this->response($this->json($result), 200);
}
$this->response(”, 204); // If no records “No Content” status
}
}

// If invalid inputs “Bad Request” status message and reason
$error = array(‘status’ => “Failed”, “msg” => “Invalid Email address or Password”);
$this->response($this->json($error), 400);
}

Users GET
Displaying users records from the users table Rest API URL http://localhost/rest/users/

private function users()
{
// Cross validation if the request method is GET else it will return “Not Acceptable” status
if($this->get_request_method() != “GET”)
{
$this->response(”,406);
}
$sql = mysql_query(“SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1”, $this->db);
if(mysql_num_rows($sql) > 0)
{
$result = array();
while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC))
{
$result[] = $rlt;
}
// If success everythig is good send header as “OK” and return list of users in JSON format
$this->response($this->json($result), 200);
}
$this->response(”,204); // If no records “No Content” status
}

DeleteUser
Delete user function based on the user_id value deleting the particular record from the users table Rest API URL http://localhost/rest/deleteUser/

private function deleteUser()
{if($this->get_request_method() != “DELETE”){
$this->response(”,406);
}
$id = (int)$this->_request[‘id’];
if($id > 0)
{
mysql_query(“DELETE FROM users WHERE user_id = $id”);
$success = array(‘status’ => “Success”, “msg” => “Successfully one record deleted.”);
$this->response($this->json($success),200);
}
else
{
$this->response(”,204); // If no records “No Content” status
}
}

Chrome Extention
A Extention for testing PHP restful API response download here Advanced REST client Application

.htaccess code
Rewriting code for friendly URLs. In the download code you just modify htaccess.txt to .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ api.php [QSA,NC,L]RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>

 

How to open wifi settings in android?

In today’s tutorial I will show you how to open the wifisettings in android programatically.
This code comes handy when the user have not enabled the wifi and you want the user to enable it for your application to work.

Here is the code for that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.coderzheaven;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class OpenWifiSettingsDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button open = (Button)findViewById(R.id.open);
        open.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openWifiSettings();
            }
        });
    }
    public void openWifiSettings(){
        final Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings");
        intent.setComponent(cn);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity( intent);
    }
}

Here is the layout xml– main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="How to open Wifi Settings Demo"
    />
  <Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Open Wifi settings"
    android:id="@+id/open"
    />
</LinearLayout>

Wifi settings in android

Enhanced by Zemanta

How To Create QR Codes in Java & Servlet

Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store,

automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of users of smart phones day by day, the QR codes usage is going up exponentially.

Let us see a quick overview of Quick Response (QR) codes and also how to generate these codes in Java.

Introduction to QR Codes

A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (“modes”) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.

Created by Toyota subsidiary Denso Wave in 1994 to track vehicles during the manufacturing process, the QR code is one of the most popular types of two-dimensional barcodes. It was designed to allow its contents to be decoded at high speed.

Hello World QR Code in Java

Zebra Crossing (ZXing) is an awesome open source library that one can use to generate / parse QR Codes in almost all the platforms (Android, JavaSE, IPhone, RIM, Symbian etc). But if you have to generate simple QR Codes, I found it a bit clumsy to implement.

However QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake. It has a dependency on ZXing, so you would need ZXing jar files along with QRGen to create QR Codes in Java.

On the download page of ZXing, you will not find the JAR files. Instead we have to create JAR files using the source code. I have already generated these JAR files. Here are the links:

zxing-core-1.7.jar (346 KB)
zxing-javase-1.7.jar (21 KB)

Also download the QRGen JAR File from their download page.

Include these JAR files in your Classpath and execute following Java code to generate QR Code.

package net.viralpatel.qrcode;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
public class Main {
    public static void main(String[] args) {
        ByteArrayOutputStream out = QRCode.from("Hello World")
                                        .to(ImageType.PNG).stream();
        try {
            FileOutputStream fout = new FileOutputStream(new File(
                    "C:QR_Code.JPG"));
            fout.write(out.toByteArray());
            fout.flush();
            fout.close();
        } catch (FileNotFoundException e) {
            // Do Logging
        } catch (IOException e) {
            // Do Logging
        }
    }
}

The code is pretty straight forward. We used QRCode class to generate QR Code Stream and write the byte stream to a file C:QR_Code.JPG.

Download Source Code

QR_Code_Java.zip (339 KB)

If you open this JPEG file and scan using your iPhone or Android QR scanner, you’ll find a cool “Hello World” in it :)

Apart from generating Sterams of data using QRGen API, we can also use below APIs to create QR Codes:

// get QR file from text using defaults
File file = QRCode.from("Hello World").file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from("Hello World").stream();
 
// override the image type to be JPG
QRCode.from("Hello World").to(ImageType.JPG).file();
QRCode.from("Hello World").to(ImageType.JPG).stream();
 
// override image size to be 250x250
QRCode.from("Hello World").withSize(250, 250).file();
QRCode.from("Hello World").withSize(250, 250).stream();
 
// override size and image type
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).file();
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).stream();

Website Link (URLs) QR Code in Java

One of the most common use of a QR Code is to bring traffic to a particular webpage or download page of website. Thus QR Code encodes a URL or website address which a user can scan using phone camera and open in their browser. URLs can be straight forward included in QR Codes. In above Java Hello World example, just replace “Hello World” string with the URL you want to encode in QR Code. Below is the code snippet:

ByteArrayOutputStream out = QRCode.from("http://viralpatel.net")
                .to(ImageType.PNG).stream();

QR Code in Servlet

Most of the time you would need to generate QR Codes dynamically in some website. We already saw how easy it is to generate QR code in Java. Now we will see how to integrate this QR Code generation in a Java Servlet.

Following is a simple Http Servlet that creates QR Code using QRGen and ZXing library. User provides the text for which QR Code is generated.

The index jsp file contains a simple html form with a textbox and submit button. User can enter the text that she wishes to generate QR code of and presses submit.

File: index.jsp

<html>
<head>
<title>QR Code in Java Servlet - viralpatel.net</title>
</head>
<body>
    
    <form action="qrservlet" method="get">
        <p>Enter Text to create QR Code</p>
        <input type="text" name="qrtext" />
        <input type="submit" value="Generate QR Code" />
    </form>
</body>
</html>

The magic happens in QRCodeServlet.java. Here we uses QRGen library along with ZXing and generates QR Code for given text (Text we get from request.getParameter). Once the QR Stream is generated, we write this to response and set appropriate content type.

File: QRCodeServlet.java

package net.viralpatel.qrcodes;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
public class QRCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String qrtext = request.getParameter("qrtext");
        ByteArrayOutputStream out = QRCode.from(qrtext).to(
                ImageType.PNG).stream();
        
        response.setContentType("image/png");
        response.setContentLength(out.size());
        
        OutputStream outStream = response.getOutputStream();
        outStream.write(out.toByteArray());
        outStream.flush();
        outStream.close();
    }
}

The below web.xml simply maps QRCodeServlet.java with /qrservlet URL.

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">
        
  <display-name>QR_Code_Servlet</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
        <servlet-name>QRCodeServlet</servlet-name>
        <servlet-class>net.viralpatel.qrcodes.QRCodeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>QRCodeServlet</servlet-name>
        <url-pattern>/qrservlet</url-pattern>
    </servlet-mapping>
    
</web-app>

Download Source Code

QR_Code_Servlet.zip (340 KB)

Output

qr-code-java-servlet-index

qr-code-java-servlet-image

 

Conclusion

Generating QR Codes in Java is not only easy, but quite straight forward. Integrating this functionality with any existing Java based app is just a piece of cake! In this tutorial we saw how to generate these QR codes in Java and also with Servlet.

Hope you’ll like this :)

Enhanced by Zemanta

30 jQuery Calendar Date Picker Plugins

Today we will be featuring calendar date pickers to let you output planners, calendars even more easier, most of these date pickers are built on jQuery and jQuery UI (User Interface).

I would consider these date pickers as frameworks with great functionality, but most of them require modifying and some styling, but I think it’s really acceptable since each project needs it’s own design and you should change style of calendar plugin too. These plugins will help you and your visitors keep track what’s happening in specific project and help to organize time!

1. Create astonishing iCal-like calendars with jQuery

This is tutorial how to make kind a like iPhone calendar application.

%tutke

Download NowView Example

1.1. Timeline calendar

Timeline is simple JavaScript driven calendar, which is written on top of jQuery JavaScript framework. Timeline is a horizontal representation of days in month. It can be used to display unlimited number of events with their descriptions.

%tutke

View Demo

2.1. MagiCalender

 

View Demo

2. BlueShoes JS DatePicker Component

The DatePicker lets users easily select valid dates from a dropdown calendar. No need to worry about date formats, by picking dates it’s always correct.

Download Now | View Examples

3. Calendar – A Javascript class for Mootools

Calendar is a Javascript class that adds accessible and unobtrusive date-pickers to your form elements. This class is a compilation of many date-pickers I have implemented over the years and has been completely re-written for Mootools. I have tried to include all the features that have been most useful while streamlining the class itself to keep it as small as possible. Use the links below to see what features are available in Calendar and how it might enhance the accessibility, usability and validation of form elements on your website.

Download Now | View Example

4. jQuery Calendar Widget Plugin

jQuery Calendar Widget Plugin is a simple jQuery Calendar Widget Plugin with a month view. You can specify which month you would like to display or have it display the current month. With just 100 lines of Javascript code, this plugin is light-weight and perfect for its purpose.

Download Now | View Example

5. JavaScript Calendar Component

Calendar Component that is very customizable and extendable.

Features:

  • Create any numbers of months per calendar.
  • Set the weekend, days off, holidays (dates off), start day of the week.
  • Start and end date.
  • Multi selection with limits or without.
  • Skinnable (using CSS).
  • Can have any number of calendars in any page.
  • Optimized for best performance.

View Example

6. Simple Calendar Widget

This flexible, simple pop-up calendar is written to work across browsers. It’s fully commented and customisable for language, colours and date format. The pop-up displays a month at a time from a specified range of years.

The optional input date determines the initial month displayed. The year can be in two or four digits while the month can be digits or a month name abbreviation that can easily be set up for any language. Any date or day of the week can be disabled (and re-enabled) using JavaScript on the calling page.

This is ideal for combination with server-side technologies to produce a professional application.

Download Now | View Example

7. DatePicker

Date Picker component with a lot of options and easy to fit in your web application.

Features:

  • Flat mode – as element in page
  • Multiple calendars in the component
  • Allows single, multiple or range selection
  • Mark dates as special, weekends, special days
  • Easy to customize the look by changing CSS
  • Localiation for months’ and days’ names
  • Custom day to start the week
  • Fits into the viewport

Download Now | View Example

8. Calendar System

Calendar System – the basic calendar.

Download Now | View Example

9. Tigra JavaScript Calendar

Tigra Calendar is a free cross-browser JavaScript Calendar control, it improves the user experience by enabling a drop-down calendar for date fields in HTML forms.

Download Now | View Example

10. Plans

One installation of plans can support many calendars. Calendars can share information with each other. Each calendar is managed independently (unique password, custom options, custom look & feel).

Multiple calendars running on the same installation of plans can be “embedded” in completely different websites. Plans uses a powerful and flexible recurring event model.

Plans supports multiple languages. Weeks can start on days other than Sunday. Plans supports arbitrary date formats (mm/dd/yy, dd/mm/yy, etc.) Plans can store data in flat files or an SQL database.

11. jQuery UI Datepicker

The jQuery UI Datepicker is a highly configurable plugin that adds datepicker functionality to your pages. You can customize the date format and language, restrict the selectable date ranges and add in buttons and other navigation options easily.

By default, the datepicker calendar opens in a small overlay onFocus and closes automatically onBlur or when a date is selected. For an inline calendar, simply attach the datepicker to a div or span.

You can use keyboard shortcuts to drive the datepicker:

  • page up/down – previous/next month
  • ctrl+page up/down – previous/next year
  • ctrl+home – current month or open when closed
  • ctrl+left/right – previous/next day
  • ctrl+up/down – previous/next week
  • enter – accept the selected date
  • ctrl+end – close and erase the date
  • escape – close the datepicker without selection

Download Now | View Example

12. The sliding date-picker

This element enables you to pick dates with a simple slider bar. By dragging the bar over the time-line, the dates change instantly. Besides this, when the user decides to manually change the dates, the bar is automatically adjusted to the corresponding dates.

Download Now | View Example

13. FullCalendar

FullCalendar is a jQuery plugin that provides a full-sized, drag & drop calendar like the one below. It uses AJAX to fetch events on-the-fly for each month and is easily configured to use your own feed format (an extension is provided for Google Calendar).

It is visually customizable and exposes hooks for user-triggered events (like clicking or dragging an event).

Download Now | View Example

14. Unobtrusive Date-Picker Widget

  • Fully keyboard accessible
  • Multiple date formats and date dividers supported
  • Unobtrusive and nameSpace friendly
  • Fully skinnable with CSS
  • Both upper and lower date limits can be set
  • Certain days of the week can be disabled
  • Certain, dates can be disabled/enabled (and wildcards used to stipulate the dates in question)
  • Includes “smart” localisation (16 languages currently available)
  • Bespoke days of the week can be highlighted
  • Works with single text inputs, split text inputs or select lists
  • It’s free to use, even commercially (Released under a CC share-alike license)

Download Now | View Example

15. Simple jQuery date-picker plugin

Features:

  • works on one or more text input elements (<input type="text" ... />)
  • highlights a preset date (first looking for a value in the input, then a passed option / default, then just selects today)
  • closes when either a date is picked, the “today” button is hit, or the “close” button is hit
  • allows fast navigation using a <select> field for months and years
  • advances and reverses months with a hit of the « or » buttons
  • automatically hides the « or » buttons when either the start or end of the date range is reached
  • and much more…

View Example

16. jQuery CalendarPicker

This component is a light-weight calendar/date-picker.

Features:

  • supports internationalization (supports do not necessary means it is implemented:-) )
  • supports changing current date
  • supports mouse wheel scrolling
  • supporting (deferred) callback on date selection
  • supports variable number of years, months and days
  • supports next/prev arrows

Download Now | View Example

17. Timeframe

Timeframe is open source, tested, and available for forking, pushing, and pulling at Github. It can select dates “from – to”.

Download Now | View Example

18. Date / Time Picker

Date / Time Picker is a easy date picker control. To open the calendar, click the icon at the right side of the input box.

Download Now | View Example

19. YUI Library: Calendar Control

This is another example of easy date picker. Calendar has three required dependencies: the YAHOO Global object, the Event Utility, and the DOM Collection.

Download Now | View Example

19.1. PHP Event Calendar

PHP Event Calendar is a MySQL Database driven script that displays events on your website quickly and easily through a traditional calendar UI. It can be integrated into any existing PHP page within minutes using a simple file include.

It features a simple yet advanced Administration Panel with secure login sessions, from within this you have full control over your calendar events and gives the ability to Add Events, Search & Edit Events, Delete Events from your calendar and so forth.

View Demo

20. Date Range Picker using jQuery UI 1.7 and jQuery UI CSS Framework

This plugin wraps the jQuery UI datepicker into an interactive component specifically designed for choosing date ranges. It is an update from a former version.

Download NowView Example

21. The New Coolest DHTML Calendar

Download Now | View Example

22. jMonthCalendar

jMonthCalendar is a full month calendar that supports events. You simply initialize the calendar with options and an events array and it can handle the rest. The plugin does have extension points that allow the developer to interact with the calendar when the display is about to change months, after the display has changed months and when the event bubbles are clicked on. jMonthCalendar now supports hover extension points, hover over an event and trigger an event like an alert(); By default the events would each have a URL supplied that would link to a details page.

Download Now | View Example

23. VCalendar

VCalendar (Virtual Web Calendar) is an open source Web calendar application for posting and maintaining events and schedules online, in calendar format. This is an excellent and free solution for use by online Web communities and any commercial and non-commercial organizations. Unlike any other online calendars, VCalendar comes with source code in multiple programming languages: PHP, ASP and ASP.NET (C#); with potential for adding more technologies in the future.

Download Now | View Example

24. PHP Calendar

All day and month names are automatically generated specific to your locale. Allows you to choose what day your weeks start on.

Download Now | View Example

25. Multiday Calendar Datepicker JQuery Plugin

Multiday Calendar Datepicker JQuery Plugin is a nicely animated calendar datepicker for multi-day selection with multi-month display. Allows for a sequence of months to reside side by side and for the user to select a number of consecutive days. This is great for lodging reservation systems, ticket purchasing systems, etc.

Download Now: JS file and CSS file | View Example

26. Easy PHP Calendar

The Easy PHP Calendar is a powerful PHP calendar script that is easily integrated into web sites and is simple to customize. This attractive, full-featured calendar is suitable for display on a calendar of events page, home page, or any other page that needs a calendar.

Download Now | View Example

27. jQuery Date Input

Date Input is a no frills date picker plugin for jQuery. It is lightweight, fast and pretty by default.

Download Now | View Example

28. jQuery DatePicker

jQuery DatePicker is an clean, unobtrusive plugin for jQuery which allows you to easily add date inputing functionality to your web forms and pages. Designed from the ground up to be flexible and extensible, the date picker can be used in unlimited ways to allow you to add calendar widgets to your pages.

Download Now | View Example

29. dynDateTime

This jQuery plugin makes it easy to add date and time selection to textfield inputs. This supports date and time, and renders the value to a single field in a configurable format.

Download Now | View Example

30. Week Calendar

The jquery-week-calendar plugin provides a simple and flexible way of including a weekly calendar in your application. It is built on top of jquery and jquery ui and is inspired by other online weekly calendars such as google calendar.

Download Now | View Example

Enhanced by Zemanta

SMS Messaging in Android

It would be safe to say that nearly every mobile phone sold in the past decade has SMS messaging capabilities. In fact, SMS messaging is one great killer application for the mobile phone and it has created a steady revenue stream for mobile operators. Understanding how to use SMS messaging in your application can provide you with many ideas to create the next killer application.

 

In this article, we take a look at how you can programmatically send and receive SMS messages in your Android applications

 

English: SMS message received on a Motorola RA...

 

. The good news for Android developers is that you don’t need a real device to test out SMS messaging – the free Android emulator provides the capability to do so.

 

Sending SMS Messages

 

To get started, first launch Eclipse and create a new Android project. Name the project as shown in Figure 1.

 


Figure 1 Creating a new Android project using Eclipse

 

Android uses a permission-based policy where all the permissions needed by an application need to be specified in the AndroidManifest.xml file. By doing so, when the application is installed it will be clear to the user what specific access permissions are required by the application. For example, as sending SMS messages will potentially incur additional cost on the user’s end, indicating the SMS permissions in the AndroidManifest.xml file will let the user decide whether to allow the application to install or not.

 

In the AndroidManifest.xml file, add the two permissions – SEND_SMS and RECEIVE_SMS:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  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>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

 

In the main.xml file located in the res/layout folder, add the following code so that the user can enter a phone number as well as a message to send:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Enter the phone number of recipient"
        />     
    <EditText 
        android:id="@+id/txtPhoneNo"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"        
        />
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"         
        android:text="Message"
        />     
    <EditText 
        android:id="@+id/txtMessage"  
        android:layout_width="fill_parent" 
        android:layout_height="150px"
        android:gravity="top"         
        />          
    <Button 
        android:id="@+id/btnSendSMS"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />    
</LinearLayout>

 

The above code creates the UI shown in Figure 2.

 


Figure 2 Creating the UI for sending SMS messages

 

Next, in the SMS activity, we wire up the Button view so that when the user clicks on it, we will check to see that the phone number of the recipient and the message is entered before we send the message using the sendSMS() function, which we will define shortly:

 

package net.learn2develop.SMSMessaging;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMS extends Activity 
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        

        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);

        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {                
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();                 
                if (phoneNo.length()>0 && message.length()>0)                
                    sendSMS(phoneNo, message);                
                else
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });        
    }    
}

 

The sendSMS() function is defined as follows:

 

public class SMS extends Activity 
{
    //...

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        //...
    }

    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMS.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);        
    }    
}

 

To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly instantiate this class; instead you will call the getDefault() static method to obtain an SmsManager object. The sendTextMessage() method sends the SMS message with a PendingIntent. The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending the message, you can use a PendingIntent object to display another activity. In this case, the PendingIntent object (pi) is simply pointing to the same activity (SMS.java), so when the SMS is sent, nothing will happen.

 

If you need to monitor the status of the SMS message sending process, you can actually use two PendingIntent objects together with two BroadcastReceiver objects, like this:

 

    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
    }

 

The above code uses a PendingIntent object (sentPI) to monitor the sending process. When an SMS message is sent, the first BroadcastReceiver‘s onReceive event will fire. This is where you check the status of the sending process. The second PendingIntent object (deliveredPI) monitors the delivery process. The second BroadcastReceiver‘s onReceive event will fire when an SMS is successfully delivered.

 

You can now test the application by pressing F11 in Eclipse. To send an SMS message from one emulator instance to another, simply launch another instance of the Android emulator by going to the Tools folder of the SDK and running Emulator.exe.

 


Figure 3 Sending an SMS message

 

Figure 3 shows how you can send an SMS message from one emulator to another; simply use the target emulator’s port number (shown in the top left corner of the window) as its phone number. When an SMS is sent successfully, it will display a “SMS sent” message. When it is successfully delivered, it will display a “SMS delivered” message. Note that for testing using the emulator, when an SMS is successfully delivered, the “SMS delivered” message does not appear; this only works for real devices.

 

Figure 4 shows the SMS message received on the recipient emulator. The message first appeared in the notification bar (top of the screen). Dragging down the notification bar reveals the message received. To view the entire message, click on the message.

 


Figure 4 The SMS message received by the Android emulator

 

If you do not want to go through all the trouble of sending the SMS message yourself, you can use an Intent object to help you send an SMS message. The following code shows how you can invoke the built-in SMS application to help you send an SMS message:

 

        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.putExtra("sms_body", "Content of the SMS goes here..."); 
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivity(sendIntent);

 

Figure 5 shows the built-in SMS application invoked to send the SMS message.

 


Figure 5 Invoking the built-in SMS application

 

Receiving SMS Messages

 

Besides programmatically sending SMS messages, you can also intercept incoming SMS messages using a BroadcastReceiver object.

 

To see how to receive SMS messages from within your Android application, in the AndroidManifest.xml file add the <receiver> element so that incoming SMS messages can be intercepted by the SmsReceiver class:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  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=".SmsReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>

    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

 

Add a new class file to your project and name it as SmsReceiver.java (see Figure 6).

 


Figure 6Adding the SmsReceiver.java file to the project

 

In the SmsReceiver class, extend the BroadcastReceiver class and override the onReceive() method:

 

package net.learn2develop.SMSMessaging;

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

public class SmsReceiver extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent) 
       {	
	}
}

 

When SMS messages are received, the onCreate() method will be invoked. The SMS message is contained and attached to the Intent object (intent – the second parameter in the onReceive() method) via a Bundle object. The messages are stored in an Object array in the PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class:

 

package net.learn2develop.SMSMessaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
                str += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }
}

 

That’s it! To test the application, press F11 in Eclipse. Deploy the application to each Android emulator. Figure 7 shows Eclipse showing the emulators currently running. All you need to do is to select each emulator and deploy the application onto each one.

 


Figure 7 Selecting an emulator/device to deploy the application onto

 

Figure 8 shows that when you send an SMS message to another emulator instance (port number 5556), the message is received by the target emulator and displayed via the Toast class.

 


Figure 8 Sending and receiving SMS messages using the Android emulators

 

Summary

 

In this article, you have seen how you can send and receive SMS messages programmatically from within your Android application. The capability to send and receive SMS messages is very useful as you can build very compelling applications. As an example, you can build a location tracker application where you can send a secret-coded SMS message to a device and when the device receives the secret SMS message it will reply with another SMS message containing its current geographical location using its built-in GPS receiver. How cool is that?!

 

Click the link below to download project source code

 

Attachment Size
SMSMessaging.zip 35.43 KB

 

Windows 95 on iPhone 3G!!

 

windows-95-iphone
In this new world of smart phones, 3gs, web 2(3).0, twitter, facebook etc we hardly remember the old legacy softwares that we used in early days of technological evolution of computer world. But people come up with some strange, weird or you can say innovative idea. Like this one; the Developers of iSoft team ran windows 95 on iPhone, its done with help of Bochs emulator and original win 95 image.

Few screen shots below :)

Image Source: Goodiphone

 

How To Create QR Codes in Java

OF + ZXing

Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store, automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of users of smart phones day by day, the QR codes usage is going up exponentially.

Let us see a quick overview of Quick Response (QR) codes and also how to generate these codes in Java.

Introduction to QR Codes

A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (“modes”) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.

Created by Toyota subsidiary Denso Wave in 1994 to track vehicles during the manufacturing process, the QR code is one of the most popular types of two-dimensional barcodes. It was designed to allow its contents to be decoded at high speed.

Hello World QR Code in Java

Zebra Crossing (ZXing) is an awesome open source library that one can use to generate / parse QR Codes in almost all the platforms (Android, JavaSE, IPhone, RIM, Symbian etc). But if you have to generate simple QR Codes, I found it a bit clumsy to implement.

However QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake. It has a dependency on ZXing, so you would need ZXing jar files along with QRGen to create QR Codes in Java.

On the download page of ZXing, you will not find the JAR files. Instead we have to create JAR files using the source code. I have already generated these JAR files. Here are the links:

zxing-core-1.7.jar (346 KB)
zxing-javase-1.7.jar (21 KB)

Also download the QRGen JAR File from their download page.

Include these JAR files in your Classpath and execute following Java code to generate QR Code.

package net.viralpatel.qrcode;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
public class Main {
    public static void main(String[] args) {
        ByteArrayOutputStream out = QRCode.from("Hello World")
                                        .to(ImageType.PNG).stream();
        try {
            FileOutputStream fout = new FileOutputStream(new File(
                    "C:\\QR_Code.JPG"));
            fout.write(out.toByteArray());
            fout.flush();
            fout.close();
        } catch (FileNotFoundException e) {
            // Do Logging
        } catch (IOException e) {
            // Do Logging
        }
    }
}

The code is pretty straight forward. We used QRCode class to generate QR Code Stream and write the byte stream to a file C:\QR_Code.JPG.

Download Source Code

QR_Code_Java.zip (339 KB)

If you open this JPEG file and scan using your iPhone or Android QR scanner, you’ll find a cool “Hello World” in it :)

Apart from generating Sterams of data using QRGen API, we can also use below APIs to create QR Codes:

// get QR file from text using defaults
File file = QRCode.from("Hello World").file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from("Hello World").stream();
 
// override the image type to be JPG
QRCode.from("Hello World").to(ImageType.JPG).file();
QRCode.from("Hello World").to(ImageType.JPG).stream();
 
// override image size to be 250x250
QRCode.from("Hello World").withSize(250, 250).file();
QRCode.from("Hello World").withSize(250, 250).stream();
 
// override size and image type
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).file();
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).stream();

Website Link (URLs) QR Code in Java

One of the most common use of a QR Code is to bring traffic to a particular webpage or download page of website. Thus QR Code encodes a URL or website address which a user can scan using phone camera and open in their browser. URLs can be straight forward included in QR Codes. In above Java Hello World example, just replace “Hello World” string with the URL you want to encode in QR Code. Below is the code snippet:

ByteArrayOutputStream out = QRCode.from("http://viralpatel.net")
                .to(ImageType.PNG).stream();

QR Code in Servlet

Most of the time you would need to generate QR Codes dynamically in some website. We already saw how easy it is to generate QR code in Java. Now we will see how to integrate this QR Code generation in a Java Servlet.

Following is a simple Http Servlet that creates QR Code using QRGen and ZXing library. User provides the text for which QR Code is generated.

The index jsp file contains a simple html form with a textbox and submit button. User can enter the text that she wishes to generate QR code of and presses submit.

File: index.jsp

<html>
<head>
<title>QR Code in Java Servlet - viralpatel.net</title>
</head>
<body>
    
    <form action="qrservlet" method="get">
        <p>Enter Text to create QR Code</p>
        <input type="text" name="qrtext" />
        <input type="submit" value="Generate QR Code" />
    </form>
</body>
</html>

The magic happens in QRCodeServlet.java. Here we uses QRGen library along with ZXing and generates QR Code for given text (Text we get from request.getParameter). Once the QR Stream is generated, we write this to response and set appropriate content type.

File: QRCodeServlet.java

package net.viralpatel.qrcodes;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
public class QRCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String qrtext = request.getParameter("qrtext");
        ByteArrayOutputStream out = QRCode.from(qrtext).to(
                ImageType.PNG).stream();
        
        response.setContentType("image/png");
        response.setContentLength(out.size());
        
        OutputStream outStream = response.getOutputStream();
        outStream.write(out.toByteArray());
        outStream.flush();
        outStream.close();
    }
}

The below web.xml simply maps QRCodeServlet.java with /qrservlet URL.

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">
        
  <display-name>QR_Code_Servlet</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
        <servlet-name>QRCodeServlet</servlet-name>
        <servlet-class>net.viralpatel.qrcodes.QRCodeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>QRCodeServlet</servlet-name>
        <url-pattern>/qrservlet</url-pattern>
    </servlet-mapping>
    
</web-app>

Download Source Code

QR_Code_Servlet.zip (340 KB)

Output

qr-code-java-servlet-index

qr-code-java-servlet-image

 

Conclusion

Generating QR Codes in Java is not only easy, but quite straight forward. Integrating this functionality with any existing Java based app is just a piece of cake! In this tutorial we saw how to generate these QR codes in Java and also with Servlet.

Hope you’ll like this :)