Posts Tagged ‘Markup Languages’

العربية: 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 »

ListView in simplest form with plain text only. This exercise describe how to add a icon in ListView.

ListView, with icon

create a new file in /res/layout/row.xml, to setup our layout on each row.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"/>
<TextView
android:id="@+id/weekofday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>

AndroidList.java

package com.exercise.AndroidList;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class AndroidList extends ListActivity {

String[] DayOfWeek = {"Sunday", "Monday", "Tuesday",
  "Wednesday", "Thursday", "Friday", "Saturday"
};

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       //setContentView(R.layout.main);
       setListAdapter(new ArrayAdapter<String>(this,
         R.layout.row, R.id.weekofday, DayOfWeek));
   }
}
Enhanced by Zemanta

It’s a simple way to load ImageView with a bitmap from internet, via http connection.

Load ImageView with bitmap from internet

In order to load something from internet, the AndroidManifest.xml have to be modified to grand permission for internet access.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.exercise.AndroidWebImage"
     android:versionCode="1"
     android:versionName="1.0">
   <application android:icon="@drawable/icon" android:label="@string/app_name">
       <activity android:name=".AndroidWebImage"
                 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-sdk android:minSdkVersion="4" />
 <uses-permission android:name="android.permission.INTERNET" />
</manifest>

Modify main.xml to include a ImageView

<?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="@string/hello"
   />
<ImageView
   android:id="@+id/image"
   android:scaleType="center"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
/>
</LinearLayout>

java code:

package com.exercise.AndroidWebImage;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidWebImage extends Activity {

String image_URL=
 "http://4.bp.blogspot.com/_C5a2qH8Y_jk/StYXDpZ9-WI/AAAAAAAAAJQ/sCgPx6jfWPU/S1600-R/android.png";

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

       ImageView bmImage = (ImageView)findViewById(R.id.image);
    BitmapFactory.Options bmOptions;
    bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    Bitmap bm = LoadImage(image_URL, bmOptions);
    bmImage.setImageBitmap(bm);
   }

   private Bitmap LoadImage(String URL, BitmapFactory.Options options)
   {       
    Bitmap bitmap = null;
    InputStream in = null;       
       try {
           in = OpenHttpConnection(URL);
           bitmap = BitmapFactory.decodeStream(in, null, options);
           in.close();
       } catch (IOException e1) {
       }
       return bitmap;               
   }

private InputStream OpenHttpConnection(String strURL) throws IOException{
 InputStream inputStream = null;
 URL url = new URL(strURL);
 URLConnection conn = url.openConnection();

 try{
  HttpURLConnection httpConn = (HttpURLConnection)conn;
  httpConn.setRequestMethod("GET");
  httpConn.connect();

  if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
   inputStream = httpConn.getInputStream();
  }
 }
 catch (Exception ex)
 {
 }
 return inputStream;
}

}
Enhanced by Zemanta

by Paul Beusterien, Mobile Developer Solutions, Carl Stehle, Appception Inc. and Tomaz Kregar, Bucka IT

Image representing PayPal as depicted in Crunc...

Adding the Plugin to your project

Using this plugin requires Android Cordova (PhoneGap) and the PayPal Mobile Payments Library. The PayPal Mobile Payments Library can be downloaded here.

  1. Create an Android Cordova project. Details at http://docs.phonegap.com/en/2.0.0/guide_getting-started_android_index.md.html
  2. Put PayPal_MPL.jar into your project’s libs directory and add it to the build path. In Eclipse, right click on PayPal_MPL.jar and select Add to Build Path.
  3. Copy assets/www/ files into your project’s assets/www/ directory
  4. Copy src/com/phonegap/plugin/ files into your project’s src/com/phonegap/plugin/ directory
  5. Make sure your AndroidManifest.xml includes a superset of the permissions shown in the reference AndroidManifest.xml
  6. Add the com.paypal.android.MEP.PayPalActivity as shown in the reference AndroidManifest.xml
  7. Include the plugin registration in /res/xml/config.xml as shown in the reference config.xml
  8. Make sure the cordova.{version}.js filename in index.html matches the filename in your www directory.
  9. Deploy and test the app. The default environment is ENV_NONE.

Using the PayPal Sandbox

  1. Set up a PayPal buyer and seller sandbox account from https://developer.paypal.com/
  2. Update demo.js to use ENV_SANDBOX instead of ENV_NONE. See comments near bottom of demo.js
  3. In index.html, update the pmt_recipient field to your sandbox seller account

 

Helping URl: https://github.com/phonegap/phonegap-plugins/tree/master/Android/PayPalPlugin

 

Enhanced by Zemanta

Recently I had a requirement where using Spring MVC we had to take inputs multiple rows of data from user. The form had many rows which user can edit and submit. Spring MVC provides very simple yet elegant way of collecting data from multiple rows from HTML form and store them in List of Beans in Java.

18% Price Drop: Samsung 51" Black Plasma 720P HDTV – PN51E450

Lets look at the requirement first. We have a screen where data for multiple Contacts is displayed. The Contact data is displayed in an HTML table. Each row in the table represents a single contact. Contact details consist of attributes such as Firstname, Lastname, Email and Phone number.

Related: Spring 3 MVC Tutorial Series (Must Read)

The Add Contact form would look like following:
spring-mvc-multi-row-form

Lets see the code behind this example.

Tools and Technologies used:

  1. Java 5 or above
  2. Eclipse 3.3 or above
  3. Spring MVC 3.0

Step 1: Create Project Structure

Open Eclipse and create a Dynamic Web Project.
eclipse-dynamic-web-project

Enter project name as SpringMVC_Multi_Row and press Finish.

Step 2: Copy Required JAR files

Once the Dynamic Web Project is created in Eclipse, copy the required JAR files under WEB-INF/lib folder. Following are the list of JAR files:
spring-mvc-multi-row-jar-files

 

Step 3: Adding Spring MVC support

Once the basic project setup is done, we will add Spring 3 MVC support. For that first modify default web.xml and add springs DispatcherServlet.

File: /WebContent/WEB-INF/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>Spring3MVC-Multi-Row</display-name>
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

Related: Tutorial: Learn Spring MVC Lifecycle

Now add spring-servlet.xml file under WEB-INF folder.

File: /WebContent/WEB-INF/spring-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        
    <context:annotation-config />
    <context:component-scan base-package="net.viralpatel.spring3.controller" />  
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Note that in above spring-servlet file, line 10, 11 defines context:annotation-config and component-scan tags. These tags let Spring MVC knows that the spring mvc annotations are used to map controllers and also the path from where the controller files needs to be loaded. All the files below package net.viralpatel.spring3.controller will be picked up and loaded by spring mvc.

Step 4: Add Spring Controller and Form classes

File: /src/net/viralpatel/spring3/form/Contact.java

package net.viralpatel.spring3.form;
public class Contact {
    private String firstname;
    private String lastname;
    private String email;
    private String phone;
    public Contact() {
    }
    public Contact(String firstname, String lastname, String email, String phone) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
        this.phone = phone;
    }
    
    // Getter and Setter methods
}

File: /src/net/viralpatel/spring3/form/ContactForm.java

package net.viralpatel.spring3.form;
import java.util.List;
public class ContactForm {
    private List<Contact> contacts;
    public List<Contact> getContacts() {
        return contacts;
    }
    public void setContacts(List<Contact> contacts) {
        this.contacts = contacts;
    }
}

Note line 7 in above code how we have defined a List of bean Contact which will hold the multi-row data for each Contact.

File: /src/net/viralpatel/spring3/controller/ContactController.java

package net.viralpatel.spring3.controller;
import java.util.ArrayList;
import java.util.List;
import net.viralpatel.spring3.form.Contact;
import net.viralpatel.spring3.form.ContactForm;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ContactController {
    
    private static List<Contact> contacts = new ArrayList<Contact>();
    static {
        contacts.add(new Contact("Barack", "Obama", "barack.o@whitehouse.com", "147-852-965"));
        contacts.add(new Contact("George", "Bush", "george.b@whitehouse.com", "785-985-652"));
        contacts.add(new Contact("Bill", "Clinton", "bill.c@whitehouse.com", "236-587-412"));
        contacts.add(new Contact("Ronald", "Reagan", "ronald.r@whitehouse.com", "369-852-452"));
    }
    
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public ModelAndView get() {
        
        ContactForm contactForm = new ContactForm();
        contactForm.setContacts(contacts);
        
        return new ModelAndView("add_contact" , "contactForm", contactForm);
    }
    
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("contactForm") ContactForm contactForm) {
        System.out.println(contactForm);
        System.out.println(contactForm.getContacts());
        List<Contact> contacts = contactForm.getContacts();
        
        if(null != contacts && contacts.size() > 0) {
            ContactController.contacts = contacts;
            for (Contact contact : contacts) {
                System.out.printf("%s t %s n", contact.getFirstname(), contact.getLastname());
            }
        }
        
        return new ModelAndView("show_contact", "contactForm", contactForm);
    }
}

In above ContactController class, we have defile two methods: get() and save().

get() method: This method is used to display Contact form with pre-populated values. Note we added a list of contacts (Contacts are initialize in static block) in ContactForm bean object and set this inside a ModelAndView object. The add_contact.jsp is displayed which in turns display all contacts in tabular form to edit.

save() method: This method is used to fetch contact data from the form submitted and save it in the static array. Also it renders show_contact.jsp file to display contacts in tabular form.

Step 5: Add JSP View files

Add following files under WebContent/WEB-INF/jsp/ directory.

File: /WebContent/WEB-INF/jsp/add_contact.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring 3 MVC Multipe Row Submit - viralpatel.net</title>
</head>
<body>
<h2>Spring MVC Multiple Row Form Submit example</h2>
<form:form method="post" action="save.html" modelAttribute="contactForm">
    <table>
    <tr>
        <th>No.</th>
        <th>Name</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Phone</th>
    </tr>
    <c:forEach items="${contactForm.contacts}" var="contact" varStatus="status">
        <tr>
            <td align="center">${status.count}</td>
            <td><input name="contacts[${status.index}].firstname" value="${contact.firstname}"/></td>
            <td><input name="contacts[${status.index}].lastname" value="${contact.lastname}"/></td>
            <td><input name="contacts[${status.index}].email" value="${contact.email}"/></td>
            <td><input name="contacts[${status.index}].phone" value="${contact.phone}"/></td>
        </tr>
    </c:forEach>
</table
<br/>
<input type="submit" value="Save" />
    
</form:form>
</body>
</html>

In above JSP file, we display contact details in a table. Also each attribute is displayed in a textbox. Note that modelAttribute=”contactForm” is defined in <form:form /> tag. This tag defines the modelAttribute name for Spring mapping. On form submission, Spring will parse the values from request and fill the ContactForm bean and pass it to the controller.

Also note how we defined textboxes name. It is in form contacts[i].a. Thus Spring knows that we want to display the List item with index i and its attribute a.

contacts[${status.index}].firstname will generate each rows as follows:

contacts[0].firstname // mapped to first item in contacts list
contacts[1].firstname // mapped to second item in contacts list
contacts[2].firstname // mapped to third item in contacts list

Spring 3 MVC and path attribute and square bracket

One thing here is worth noting that we haven’t used Spring’s
tag to render textboxes. This is because Spring MVC 3 has a unique way of handling path attribute for
tag. If we define the textbox as follows:

<form:input path="contacts[${status.index}].firstname" />

Then instead of converting it to following HTML code:

<input name="contacts[0].firstname" />
<input name="contacts[1].firstname" />
<input name="contacts[2].firstname" />

It converts it into following:

<input name="contacts0.firstname" />
<input name="contacts1.firstname" />
<input name="contacts2.firstname" />

Note how it removed square brackets [ ] from name attribute. In previous versions of Spring (before 2.5) the square bracket were allowed in name attribute.

It seems w3c has later changed the HTML specification and removed [ ] from html input name.
Read the specification http://www.w3.org/TR/html4/types.html#type-name. It clearly says that:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (“-”), underscores (“_”), colons (“:”), and periods (“.”).

Thus, square brackets aren’t allowed in name attribute! And thus Spring 3 onwards this was implemented.

So far I haven’t got any workaround to use springs <form:input /> tag instead of plain html <input /> to render and fetch data from multiple rows.

File: /WebContent/WEB-INF/jsp/show_contact.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Spring 3 MVC Multipe Row Submit - viralpatel.net</title>
</head>
<body>
<h2>Show Contacts</h2>
<table width="50%">
    <tr>
        <th>Name</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Phone</th>
    </tr>
    <c:forEach items="${contactForm.contacts}" var="contact" varStatus="status">
        <tr>
            <td>${contact.firstname}</td>
            <td>${contact.lastname}</td>
            <td>${contact.email}</td>
            <td>${contact.phone}</td>
        </tr>
    </c:forEach>
</table
<br/>
<input type="button" value="Back" onclick="javascript:history.back()"/>
</body>
</html>

File: /WebContent/index.jsp

<jsp:forward page="get.html"></jsp:forward>

 

Final Project Structure

Once we have added all relevant source files and jar files, the project structure should look like following:
spring-multi-row-project-structure

 

Step 6: Execute it

Execute the web application Right click on project > Run As > Run on Server.

Add Contact page

Show Contact page
spring-multiple-row-list-show-page

Download Source Code

Spring-MVC-Multiple-Row-List-example.zip (2.9 MB)

Enhanced by Zemanta

In this tutorial, we show you how to integrate JSF 2.0 with Spring.

Directory structure of this example

jsf2-spring-example-folder

1. Project Dependencies

Use Maven to grab all the JSF 2.0 and Spring library dependencies.

File : pom.xml


  4.0.0
  com.mkyong.common
  JavaServerFaces
  war
  1.0-SNAPSHOT
  JavaServerFaces Maven Webapp
  http://maven.apache.org

       java.net.m2
       java.net m2 repo
       http://download.java.net/maven/2

  	 

		org.springframework
		spring
		2.5.6

		org.springframework
		spring-web
		2.5.6

    <!-- For Java EE Application Server, uncomment this library 
  	and comment the rest of the libraries
    
      javax.faces
      jsf-api
      2.0
      provided
    
     -->

  	
  	

	  com.sun.faces
	  jsf-api
	  2.1.0-b03

	  com.sun.faces
	  jsf-impl
	  2.1.0-b03

	

	  org.glassfish.web
	  el-impl
	  2.2

        

	  javax.servlet
	  jstl
	  1.2

	  javax.servlet
	  servlet-api
	  2.5

	  javax.servlet.jsp
	  jsp-api
	  2.1

    JavaServerFaces

           org.apache.maven.plugins
           maven-compiler-plugin
           2.3.1

               1.6
               1.6

2. Spring Bean

A Spring bean declaration, later uses Spring to DI this “userBo” into JSF 2.0 managed bean property.

File : UserBo.java

package com.mkyong.user.bo;

public interface UserBo{

	public String getMessage();

}

File : UserBoImpl.java

package com.mkyong.user.bo.impl;

import com.mkyong.user.bo.UserBo;

public class UserBoImpl implements UserBo{

	String name;

	public void setName(String name) {
		this.name = name;
	}

	public String getMessage() {

		return "JSF 2 + Spring Integration saying : " + name;

	}

}

File : applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="userBo" class="com.mkyong.user.bo.impl.UserBoImpl">
		<property name="name" value="mkyong.com" />
	</bean>

</beans>

3. JSF 2.0

A simple JSF 2.0 web application.

File : UserBean.java

package com.mkyong;

import java.io.Serializable;

import com.mkyong.user.bo.UserBo;

//DI via JSF managed bean
public class UserBean implements Serializable{

	//DI via Spring
	UserBo userBo;

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public String printMsgFromSpring() {

		return userBo.getMessage();

	}

}

File : default.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      >

    <h:body>

    	<h1>JSF 2.0 + Spring Example</h1>

 		#{user.printMsgFromSpring()}

    </h:body>

</html>

JSF 2.0 + Spring Integration

The main concern is how to inject Spring “UserBo” bean into JSF managed bean “UserBean“.

File : UserBean.java

//DI via JSF managed bean
public class UserBean implements Serializable{

	//DI via Spring
	UserBo userBo;

1. Spring Listeners

Add following two Spring’s listeners into web.xml.

  <listener>
	<listener-class>
		org.springframework.web.context.ContextLoaderListener
	</listener-class>
  </listener>
  <listener>
	<listener-class>
		org.springframework.web.context.request.RequestContextListener
	</listener-class>
  </listener>

See full example of web.xml.

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>JavaServerFaces</display-name>

  <!-- Add Support for Spring -->
  <listener>
	<listener-class>
		org.springframework.web.context.ContextLoaderListener
	</listener-class>
  </listener>
  <listener>
	<listener-class>
		org.springframework.web.context.request.RequestContextListener
	</listener-class>
  </listener>

  <!-- Change to "Production" when you are ready to deploy -->
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>

  <!-- Welcome page -->
  <welcome-file-list>
    <welcome-file>faces/default.xhtml</welcome-file>
  </welcome-file-list>

  <!-- JSF mapping -->
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- Map these files with JSF -->
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>

</web-app>

2. SpringBeanFacesELResolver

Add SpringBeanFacesELResolver as el-resolver in faces-config.xml, and declare JSF managed bean like normal. Now, whenever JSF sees a bean name, it try JSF rules first, then Spring rules next. In this case, when JSF see #{userBo}, it will match it with Spring’s “userBo” bean.

File : faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

	<application>
    	        <el-resolver>
    		    org.springframework.web.jsf.el.SpringBeanFacesELResolver
    	        </el-resolver>
  	</application>

	<managed-bean>
		<managed-bean-name>user</managed-bean-name>
		<managed-bean-class>com.mkyong.UserBean</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
		<managed-property>
			<property-name>userBo</property-name>
			<value>#{userBo}</value>
		</managed-property>
	</managed-bean>

</faces-config>
Note
Alternatively, you can add DelegatingVariableResolver in variable-resolver, but API variable-resolver is deprecated after JSF 1.1. You should use el-resolverinstead.

<application>
	<variable-resolver>
		org.springframework.web.jsf.DelegatingVariableResolver
	</variable-resolver>
</application>

3. Demo

Done, run it and see output below : http://localhost:8080/JavaServerFaces/faces/

jsf2-spring-example-output

Download Source Code

This example gives you an idea on how to Initialize bean in the program and also explains the lifecycle of bean in spring. Run the given bean example to retrieves the values of the bean using java file. Here in the file given below i.e. (context.xml) we have declare the bean definition.

Mybean” class=”Bean”>
<property name=”company” value=”Name”/>
</bean>

Here “Bean” is the name of the bean class which would be further referred in the xml file with the id “MyBean”.

<property name=”company” value=”Name”/>:-Declares  the property name of the bean and its value.

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="Mybean" class="Bean">
  <property name="company" value="Name"/>
  <property name="value" value="Roseindia.net"/> 
  </bean>
</beans>

Here is the file named Main.java through which we are retrieving the properties of the bean which we have defined in the above file i.e. context.xml

 XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(“context.xml”)):-Here we are creating an instance of the XmlBeanFactory which is used to read bean definition from an XML document

new ClassPathResource(“context.xml”):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded.

class BeanSupport implements InitializingBean :-Here the InitializingBean  interface is implemented by bean class. The use of this interface here is  to do some post processing actions when all the properties have been set by the Bean Factory..

 @Override
public String toString() {   return String.format(“%s : \”%s\””, this.company, getValue());
}

Here the method toString() is overridden which is returning the the company name and value that has been defined in the context.xml file.

Main.java

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Main {

  public static void main(String[] argsthrows Exception {
 XmlBeanFactory factory = new XmlBeanFactory(new 
    ClassPathResource("context.xml"));  System.out.println(factory.getBean("Mybean"));
  }
}
class Bean extends BeanSupport {

  private String company;
  
  public void setCompany(String company) {
  this.company = company;
  }
  @Override
  public String toString() {
  return String.format("%s : \"%s\""this.company, getValue());
  }
}
class BeanSupport implements InitializingBean {

  private String value;

  public final void afterPropertiesSet() throws Exception {
  }

  public final void setValue(String value) {
  this.value = value;
  }

  protected final String getValue() {
  return this.value;
  }
}

Output of the program

Nov 25, 2008 5:25:41 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [context.xml]
Name : “Roseindia.net”
BUILD SUCCESSFUL (total time: 1 second)

Download Source code

Calling Bean using init() method in Spring, this section describes  the way to initialize a bean through its lifecycle events using the init() method .Here we have defined the property and values of  the bean using the init method as shown below:-

<bean id=”mybean” class=”Bean” init-method=”init”>:-Here “Bean” is the name of the bean class which would be referred in the xml file with the id “mybean”.

init-method=”init”:-Specify the init method named “init” in the configuration file.

name=”name”> Roseindia.net:-Here the <property> element is used to declare the attributes and to pass the desired value to the property element, the <value> element is used. Here the property name is “name”and its value is “Roseindia.net”.

 

 

mybean” class=”Bean” init-method=”init”>
<property name=”name”>
<value>Roseindia.net</value>
</property>
<property name=”address”>
<value>Rohini</value>
</property>
<property name=”type”>   <value>Software Development Company</value>
</property>
</bean>

initMethod.xml

beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd"
>
<beans>
  <bean id="mybean" class="Bean" init-method="init">
  <property name="name">
  <value>Roseindia.net</value>
  </property>
  <property name="address">
  <value>Rohini</value>
  </property>
  <property name="type">
  <value>Software Development Company</value>
  </property>
 </bean>
</beans>

Here is the file named SimpleBean.java through which we are retrieving the properties of the bean which we have defined in the above file i.e. initMethod.xml.

BeanFactory factory = new XmlBeanFactory(new FileSystemResource(“initMethod.xml”)):-Creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document.

SimpleBean.java

import org.springframework.beans.factory.BeanCreationException;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.FileSystemResource;



public class Bean {



  private static final String DEFAULT_NAME = "Girish";

  private String name = null;

  private String address = null;

  private String type = null;

  



  public void setName(String name) {

  this.name = name;

  }

  public void setAddress(String address) {

  this.address = address;

  }



  public void setType(String type) {

  this.type = type;

  }



  public void init() {

  System.out.println("Initializing bean");



  if (name == null) {

  System.out.println("Using default name");

  name = DEFAULT_NAME;

  }

  if (address == null) {

  System.out.println("Using default name");

  address = DEFAULT_NAME;

  }

  if (type == null) {

  System.out.println("Using default name");

  type = DEFAULT_NAME;

  }

 

  }

  public String toString() {

  return "Name: " + name + "\nAddress: " + address + "\nType: " + type ;

  }



  public static void main(String[] args) {

  BeanFactory factory = new XmlBeanFactory(new FileSystemResource(

  "initMethod.xml"));



  Bean Bean1 = getBean("mybean", factory);

  }

  private static Bean getBean(String beanName, BeanFactory factory) {

  try {

  Bean bean = (Bean) factory.getBean(beanName);

  System.out.println(bean);

  return bean;

  } catch (BeanCreationException ex) {

  System.out.println("An error occured 



in bean configuration: " + ex.getMessage());

  return null;

  }

  }

}  

Output of the program

Initializing beanName: Roseindia.net

Address: Rohini

Type: Software Development Company

Download Source code

Sir Timothy John Berners-Lee, painted portrait...

Sir Timothy John Berners-Lee, painted portrait _DDC7898 (Photo credit: Abode of Chaos)

Sir Timothy John Berners-Lee, painted portrait...

Sir Timothy John Berners-Lee, painted portrait DSC_0163 (Photo credit: Abode of Chaos)

This is the eight part of the “Android Full Application Tutorial” series. The complete application aims to provide an easy way of performing movies/actors searching over the internet. In the first part of the series (“Main Activity UI”), we created the Eclipse project and set up a basic interface for the main activity of the application. In the second part (“Using the HTTP API”), we used the Apache HTTP client library in order to consume an external HTTP API and integrate the API’s searching capabilities into our application. In the third part (“Parsing the XML response”) we saw how to parse the XML response using Android’s built-in XML parsing capabilities. In the fourth part (“Performing the API request asynchronously from the main activity”), we tied together the HTTP retriever and XML parser services in order to perform the API search request from our application’s main activity. The request was executed asynchronously in a background thread in order to avoid blocking the main UI thread. In the fifth part (“Launching new activities with intents”), we saw how to launch a new Activity and how to transfer data from one Activity to another. In the sixth part, (“Customized list view for data presentation”) we created a custom list view in order to provide a better data visual presentation. In the seventh (“Using options menus and customized dialogs for user interaction”), we created options menus and custom dialogs in order to facilitate better user interaction. In this part, we are going to create an AppWidget for the user home screen and provide application related updates via it.

Since version 1.5, the Android SDK includes the AppWidget framework, a framework that allows developers to write “widgets” that people can drop onto their home screen and interact with. The use of widgets is very handy since it allows the user to add their favorite applications into their home screen and interact with them quickly and without having to launch the whole application. Before continuing, I suggest taking a look at the article “Introducing home screen widgets and the AppWidget framework” posted at the official Android developers blog. An example of a widget is shown in the next image. It is the one built for the purposes of the article and it gives updates on the “Word of the day”. The source code for that can be found here.

For our application, we are going to create a widget which periodically provides updates on the latest movie created in the TMDb database. As I have mentioned in the past, we have been using the very cool TMDb API for movie/actors search and various other related functions.

The first step to creating the app widget is to provide a declaration for it as well as some XML metadata that describe it. This is done by adding a special XML file in the “res/xml” folder of our project. Through that file, we provide information regarding the widget’s dimensions, its update interval etc. The corresponding class is named AppWidgetProviderInfo and its fields correspond to the fields in the XML tag we are going to see below. For the height and width of the widget, Google recommends using a specific formula:

Minimum size in dip = (Number of cells * 74dip) – 2dip

Since we wish our widget to occupy 2 cells in width and 1 cell in height, the sizes in dip are going to be 146 and 72 respectively. The update interval is defined in milliseconds and for demonstration purposes we are using only 10 seconds (10000 millis). However, please note that short interval are discouraged. More specifically, updating more frequently than every hour can quickly eat up battery and bandwidth.

UPDATE: For this very reason of avoiding battery exhaustion, Google has changed its API after version 1.6 so that the refresh rate can not be less than 30 minutes. If you wish to achieve more frequent updates, the alarm mechanism has to be used in order to send intent broadcast to your widget receiver. You can find an example of this approach in the post “App Widget using Alarm Manager“.

Last but not least, a layout has to be used so that we can handle how the widget will be rendered. This will be done by referencing an other XML file, named “widget_layout.xml”.

The XML widget declaration file is named “movie_search_widget.xml” and it is the following:

1 <?xml version="1.0" encoding="utf-8"?>
2
3 <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
4     android:minWidth="146dip"
5     android:minHeight="72dip"
6     android:updatePeriodMillis="10000"
7     android:initialLayout="@layout/widget_layout"
8 />

Let’s see now what its layout description (“/res/layout/widget_layout.xml”) looks like:

01 <?xml version="1.0" encoding="utf-8"?>
02
03 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
04     android:id="@+id/widget"
05     android:layout_width="fill_parent"
06     android:layout_height="wrap_content"
07     android:focusable="true"
08     style="@style/WidgetBackground">
09     
10     <TextView
11         android:id="@+id/app_name"
12         android:layout_width="wrap_content"
13         android:layout_height="wrap_content"
14         android:layout_marginTop="14dip"
15         android:layout_marginBottom="1dip"
16         android:includeFontPadding="false"
17         android:singleLine="true"
18         android:ellipsize="end"
19         style="@style/Text.WordTitle" />
20     
21     <TextView
22         android:id="@+id/movie_name"
23         android:layout_width="fill_parent"
24         android:layout_height="wrap_content"
25         android:layout_below="@id/app_name"
26         android:paddingRight="5dip"
27         android:paddingBottom="4dip"
28         android:includeFontPadding="false"
29         android:lineSpacingMultiplier="0.9"
30         android:maxLines="4"
31         android:fadingEdge="vertical"
32         style="@style/Text.Movie" />
33     
34 </RelativeLayout>

The layout is pretty simple. We are using RelativeLayout, where the positions of the children can be described in relation to each other or to the parent, and a couple of TextViews. Note that the style used is actually defined in a different file (“res/values/styles.xml”) in order to gather all style related attributes in one place. The style declarations are the following:

01 <?xml version="1.0" encoding="utf-8"?>
02
03 <resources>
04
05     <style name="WidgetBackground">
06         <item name="android:background">@drawable/widget_bg</item>
07     </style>
08     
09     <style name="Text">
10     </style>
11     
12     <style name="Text.Title">
13         <item name="android:textSize">16sp</item>
14         <item name="android:textStyle">bold</item>
15         <item name="android:textColor">@android:color/black</item>
16     </style>
17     
18     <style name="Text.Movie">
19         <item name="android:textSize">13sp</item>
20         <item name="android:textColor">@android:color/black</item>
21     </style>
22      
23 </resources>

The next step is to register a special BroadcastReceiver in the AndroidManifest.xml file. This receiver will process any app widget updates that will be triggered by the system when the time comes. Let’s see the corresponding manifest file snippet:

01 <application android:icon="@drawable/icon" android:label="@string/app_name">
02 ...    
03         <!-- Broadcast Receiver that will process AppWidget updates -->
04         <receiver android:name=".widget.MovieSearchWidget" android:label="@string/widget_name">
05             <intent-filter>
06                 <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
07             </intent-filter>
08             <meta-data android:name="android.appwidget.provider" android:resource="@xml/movie_search_widget" />
09         </receiver>
10         
11         <!-- Service to perform web API queries -->
12         <service android:name=".widget.MovieSearchWidget$UpdateService" />       
13
14 ...
15 </application>

The receiver class is the “com.javacodegeeks.android.apps.moviesearchapp.widget.MovieSearchWidget” which will actually use an inner service class (“UpdateService”) in order to perform the updates. Note that the actions handled by that receiver are of kind APPWIDGET_UPDATE, which is sent when it is time for the AppWidget update. In the metadata section, the widget declaration XML file location is defined.

Now let’s write the class that will receive the AppWidget requests and provide the application updates. To do so, we extend the AppWidgetProvider class, which in its turn extends the BroadcastReceiver class. Actually, the AppWidgetProvider is just a convenience class to aid in implementing an AppWidget provider and its whole functionality could be achieved by a regular BroadcastReceiver.

There are five basic methods that can be overriden in order to handle the various action requests:

  • onEnabled: Called when the first App Widget is created. Global initialization should take place here, if any.
  • onDisabled: Called when the last App Widget handled by this definition is deleted. Global cleanup should take place here, if any.
  • onUpdate: Called when the App Widget needs to update its View, which could be when the user first creates the widget. This is the most commonly used method.
  • onDeleted: Called when one or more instances of this App Widget are deleted. Cleanup for the specific instances should occur here.
  • onReceive: Handles the BroadcastReceiver actions and dispatches the requests to the methods above.

Here is our implementation:

01 package com.javacodegeeks.android.apps.moviesearchapp.widget;
02
03 import android.app.PendingIntent;
04 import android.app.Service;
05 import android.appwidget.AppWidgetManager;
06 import android.appwidget.AppWidgetProvider;
07 import android.content.ComponentName;
08 import android.content.Context;
09 import android.content.Intent;
10 import android.net.Uri;
11 import android.os.IBinder;
12 import android.widget.RemoteViews;
13
14 import com.javacodegeeks.android.apps.moviesearchapp.R;
15 import com.javacodegeeks.android.apps.moviesearchapp.model.Movie;
16 import com.javacodegeeks.android.apps.moviesearchapp.services.MovieSeeker;
17
18 public class MovieSearchWidget extends AppWidgetProvider {
19    
20    private static final String IMDB_BASE_URL = "http://m.imdb.com/title/";
21    
22    @Override
23     public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
24         // To prevent any ANR timeouts, we perform the update in a service
25         context.startService(new Intent(context, UpdateService.class));
26     }
27
28     public static class UpdateService extends Service {
29        
30        private MovieSeeker movieSeeker = new MovieSeeker();
31        
32         @Override
33         public void onStart(Intent intent, int startId) {
34             // Build the widget update for today
35             RemoteViews updateViews = buildUpdate(this);
36
37             // Push update for this widget to the home screen
38             ComponentName thisWidget = new ComponentName(this, MovieSearchWidget.class);
39             AppWidgetManager manager = AppWidgetManager.getInstance(this);
40             manager.updateAppWidget(thisWidget, updateViews);
41         }
42         
43       public RemoteViews buildUpdate(Context context) {
44            
45          Movie movie = movieSeeker.findLatest();              
46          
47          String imdbUrl = IMDB_BASE_URL + movie.imdbId;
48
49          // Build an update that holds the updated widget contents
50          RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
51
52          updateViews.setTextViewText(R.id.app_name, getString(R.string.app_name));
53          updateViews.setTextViewText(R.id.movie_name, movie.name);
54          
55          Intent intent = new Intent();
56          intent.setAction("android.intent.action.VIEW");
57          intent.addCategory("android.intent.category.BROWSABLE");
58          intent.setData(Uri.parse(imdbUrl));
59          
60          PendingIntent pendingIntent =
61             PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
62            
63          updateViews.setOnClickPendingIntent(R.id.movie_name, pendingIntent);
64          
65          return updateViews;
66
67       }
68
69         @Override
70         public IBinder onBind(Intent intent) {
71             // We don't need to bind to this service
72             return null;
73         }
74         
75     }
76
77 }

As mentioned, we override the onUpdate method and inside that, we just start a new Service that will actually provide the updates. This is done in order to perform the time consuming actions (open network connections, downloading data etc.) in an other thread, thus avoiding any ANR timeouts. In our service, we implement the onStart method. Note that this method is now deprecated and the onStartCommand should be used. Since I am using the Android 1.5 SDK, I am going to stick with the onStart method.

For our application, I use a new method from the MovieSeeker class, which has been enhanced in order to also provide the latest movie (we will see that later). Next, we construct a RemoteViews object which will describe the view that will be displayed in another process (i.e. by the home screen). In its constructor, we provide the package name (taken by the relevant Context) and the ID of the layout that the view uses (in our case “widget_layout”). Note that we cannot directly manipulate any child views of the layout, for example by setting the view’s text or registering listeners. For that reason, we are going to use the setTextViewText method in order to provide the TextView‘s text and the setOnClickPendingIntent method in order to provide a handler for the click events.

We want to launch the browser and point to the movie’s IMDB page every time the user clicks on the widget. In order to achieve this, we first create an Intent of action ACTION_VIEW and the page’s URL as data. That intent is then encapsulated inside a PendingIntent and it is the pending intent that is used as the click handler.

When the RemoteViews object is ready, we create a ComponentName object which functions as an identifier of our BroadcastReceiver. Then, we take reference of the AppWidgetManager and use it to push updates to our home screen app widget via the updateAppWidget method.

Before launching the application, let’s see how the latest movie is retrieved. Recall that the MovieSeeker class is used for movies search. We have added a method named “findLatest” to that class which uses the Movie.getLatest API call of the TMDb API. Since the response from that call does not match the format of the existing movie search responses, we have to create an additional XML handler, called “SingleMovieHandler”. You can find the full changes in the project available for downloading at the end of this article.

Now launch the corresponding Eclipse project configuration. The emulator will probably take you straight to the application itself. Rather, hit the back button in order to return to the home screen. Check the article on how to add and remove app widgets. For the emulator, you basically have to click on an empty area and not release the mouse button. Then, the following dialog will pop-up:

Choose “Widgets” and then select the “MovieSearchAppWidget”:

When the widget gets inserted in the home screen, the relevant update method will be executed and the latest movie will be fetched. This is how the home screen will look like:

Finally, if you double click on the movie’s name, the pending intent will be fired and the Android browser will launch directed to the movies IMDB page (note that some movies will not have an associated IMDB ID and page. In that case the browser will take you to a broken IMDB page).

That’s it. AppWidget for your application. You can download here the Eclipse project created so far