avr

23

Posted by : admin | On : 23 avril 2012

Source

http://www.careerride.com/Spring-bean-lifecycle-in-spring-framework.aspx

Question/response  JAVA

Spring

What is Spring?

Spring is a framework that resolves common problems in JEE architecture. (JDBC ,integration later, presentation layer …)
Spring is managing business objects and encouraging practices POJO model (vs programming model)
It’s highly recommended to use a architectural tiers  (presentation,business,dao Layer) ; the inejection of the different beans is realized by utilizing IoC.
Spring is both comprehensive and modular. Spring has a layered architecture, meaning that you can choose to use just about any part of it in isolation. Spring is also an ideal framework for test driven projects.

  • The most common modules are :
  1. Most use module : Spring core, Spring test, Spring jdbc
  2. Advanced module :  Spring AOP ,Spring integration , Spring batch

Bean lifecycle in Spring framework.

The bean’s definition is found by the spring container from the XML file and instantiates the bean.

All the properties specified in the bean definition are populated by spring using dependency injection.

 

The bean’s Id is passed to setBeanName() method by the factory, and the factory calls setBeanFactory() is passed to itself, incase the bean implements the BeanFactoryAware interface.

The init() method is invoked if specified. If any BeanPostProcessors are associated with the bean, the methods postProcessAfterInitialization() are invoked.

Thread in JAVA

http://www.careerride.com/Interview-Questions-Java-Threading.aspx

2 type of process are being execute in a PC

les multitache  par processus + long pour le CPU de réaliser le swap entre les différents applicatif .

Le multitache par thread

class MonThread implements Runnable {
	Thread t ;
	MonThread("Mon thread "){
		t = new Thread("Mon thread");
		t.start();
	}
	public void run(){
		System.out.println("Thread enfant démarré");
	}

	public static void main(String args[]){
		new MonThread();
		System.out.println("Thread principale démarré ");
		System.out.println("Thread principale terminé ");
	}
}

l’instruction join() permet d’attendre le thread enfant se termine et qu’il rejoinne le thread principale . (exemple le thread du main)

permettre à deux thread de ne pas accéder à la même ressource en même temps on utilise pour cela le mot clé synchronized dans le prototype de la méthode.Souvent cela arrive lorsque 1 thread => appel 1 methode d’une autre classe Exemple :

class  MonThread implements Runnable (){
	String s1 ;
	Parenthese p1;
	Thread t ;
	public MonThread(Parenthese p2 , String s2){
		p1 = p2 ;
		s1 = s2 ;
		t = new Thread(this);
		t.start();
	}
	public void run(){
		p1.afficher(); // La méthode affficher doit être nécessairement en synchronized
	}
}

Une méthode peut etre appellé à l’intérieur d’un bloc synchronizé ( les objets et les methodes sont synchronisés ) Les appels aux méthodes contenues dans le bloc synchronisé n’ont lieu qu’après que le threade a activé le moniteur sur objet L’instruction synchronized

 

public void run(){
	synchronized(p1){
		p1.afficher();
	}
}

 

Communication entre les threads wait() demande à un thread de libérer un moniteur et de se placer en suspens .notify() demande au thread suspendu de se remettre en marche et de reprendre le contrôle du moniteur

 

class MonThread implements Runnable {
	Thread t;

	MonThread(String threadName) {
		// t = new Thread(threadName);
		// t.start();
	}

	public void run() {
		System.out.println("RUN Child thread :" + Thread.currentThread());
	}

	public static void main(String args[]) throws InterruptedException {
		Thread thread1 = new Thread(new MonThread("thread1"), "thread1");
		Thread thread2 = new Thread(new MonThread("thread2"), "thread2");
		thread1.start();
		thread2.start();

		thread1.join();
		if (!thread1.isAlive()) {
			System.out.println("Thread T1 is not alive.");
		}
		thread2.join();
		if (!thread2.isAlive())
			System.out.println("Thread T2 is not alive.");

		Thread.currentThread().sleep(2000);
		System.out.println(Thread.currentThread());

	}
}

RUN Child thread :Thread[thread1,5,main]

RUN Child thread :Thread[thread2,5,main]

Thread T1 is not alive.Thread T2 is not alive.

Thread[main,5,main]

package coordination;

public class AutoBus extends Thread {
	int total = 0;

	public void run() {
		synchronized (this) {
			System.out.println("wait ...");
			for (int i = 0; i < 100; i++)
				total = +i;
			System.out.println("passenger is given notification call ");
			notify();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		AutoBus bus = new AutoBus();
		bus.start();
		synchronized (bus) {
			System.out.println(" passenger is waiting for the bus");
			bus.wait();
			System.out.println("passenger go notification");
		}
		System.out.println(" total=" + bus.total);
	}
}

passenger is waiting for the buswait …

passenger is given notification call passenger go notification total=99

Example questions :

how to create a thread and start it running
Example 1 : Extending Thread Class

Example 2 : implentation Runnable

Explain how do we allow one thread to wait while other to finish.

When a thread is created and started, what is its initial state?
Ready for execution (Create + started )
A thread is in “Ready” state after it has been created and started.
This state signifies that the thread is ready for execution. From here, it can be in the running state.

explain monitor in java

mot clé synchronization

What is serializable Interface?

If we want to transfer data over a network then it needs to be serialized. Objects cannot be transferred as they are. Hence, we need to declare that a class implements serializable so that a compiler knows that the data needs to be serialized.

 

 

EJB

EJB is a standard for developing server side in JAVA. It specifies agreement between components and application servers that allows components to run on server. They are mainly for complex serer side operations like executing complex algorithm or high volume business. EJB provides the application layer logic, also called as middle tier. It provides a standard specifications-based way to develop and deploy enterprise-class system.

What are the kinds of EJB’s?

There are 3 kinds of EJB’s -

  1. Session beans,
  2. Entity Beans
  3. Message-driven beans

 

  • Session beans

Sessions beans represent business logic of an application. Session beans can be of 2 types namely stateless and stateful beans

  • Entity Beans

Entity beans represent persistent data in an EJB application.

  • Message-driven beans

This type of beans is used implement asynchronous communication in the system.

Stateful

The state of the conversation can be maintained using a stateful session bean.
It implements ‘javax.ejb.SessionBean’ interface and is deployed with the declarative attribute ‘stateful’.
The instance variables contain a state only during the invocation by a client method.
The bean can use the conversational states as its business process methods.

Main cons: Resources that is needed to be substain to maintain connection between server and client
Other discussion pro/cons :

http://blog.xebia.fr/2007/07/24/service-stateful-vs-service-stateless/

Stateless

We dont maintain conversational state specific to client session.
It is an EJB component that implements ‘javax.ejb.SessionBean’ interface.
The stateless session bens carry equal value for all the instances due to which a container can assign a bean to any client making it very scalable.
There is no instance state. The business methods on a stateless session bean are like procedural applications or static methods, so all the data needed to execute the method is provided by the method arguments.
Stateless session beans are very lightweight and fast.Typically an application requires less number of stateless beans compared to stateful beans.

What is lazy loading?

Heavy weight application consume a lot of time while loading the plug-ins. In lazy loading approach, the plug-ins that are needed at that particular time are loaded and instantiated. This boosts up the performance as only the plug-ins that are used are loaded. This also ensures the efficiency and speeds up the initial load time of the applications. Applications like Eclipse use this approach. In other words, the goal of lazy loading is to dedicate memory only when it is absolutely necessary.

Difference between a Server, a Container, and a Connector?

-A server is an application that responds to the requests made by client(s) and manages system resources like network connections, threads, processes, memory, database connections, etc
E.g.: Websphere,Jonas,BEA WebLogic …
-A server can contain N number of containers. An EJB container runs inside an EJB server. The Container shields the EJB server through an API between the bean and its container.
-A connector is used to resolve the issue with the legacy systems. A connector is an architecture defined by Sun. Since the applications running on the legacy systems cannot be discarded due to the business logic and other reasons, the connectors were used to serve the purpose.
(exemple connector : Oracle, Mysql,Postgre …)

 

Packaging :

What is the difference between EAR, JAR and WAR file?

Modules are packaged based on their functionality as EAR, JAR and WAR files.

• JAR files (.jar):Modules which contain EJB class files and EJB deployment descriptor are packed as JAR files.
WAR Files (.war):Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as JAR file.
EAR Files (.ear):‘.jar’ & ‘.war’ files are packaged as JAR files. ‘Ear’ stands for enterprise archive. These files are deployed in the application server.

 

Révision Java

Variables en Java

  • Variable instance ont pour durée de vie celle de l’objet
  • Variable de classe sont mis en place quand les classes sont dites chargées .
  • Variable locales celle d’une fonction

 

Flux

Java.io

Flux entrée System.in .

Remarque : Depuis Java 5 la classe Scanner permet de lire les entrées clavier facilement

Scanner scanner = new Scanner(System.in);

String choix = scanner.next();

Flux de sortie : System.out

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

nom = br.readLine();

 

mot clé static

on peut appeler la méthode d’un objet sans avoir à instancier celui ci

On l’utilise le plus souvent lorsque l’objet n’a pas de rapport à proprement dit avec la classe

disposer d’information collectives (exemple : comptage instance de classe )

ou bien disposer de fonction indépendante

 

bloc static

n’ont accès qu’au champs static de la classe

utilise surtout pour initialiser des champs static

=> Conseil mieux vaut avoir un private static methode pour avoir la main sur nos variables facilement

 

Clonage

recopie les références de l’objet mais ne provoquue pas la recopie des valeur des objets .

 

compare

== et !=

ne compare les objets que sur les reférences , peut être utilisé pour comparer des références null , 2 énum values …

a.compareTo(b) compare les values des champs a et b et retourne un int issu de la comparaison

=> penser aussi au pattern Iterator et à la classe Comparator<T>

 

La rammasse miette en java

Lors un objet ne possède plus de référence sur cet objet on dit qu’il est candidat au gargage collector

finalize() est appellé par le garbage collector quand la condition précédente est vérifié

 

Classe anonymes

permet de définir une classe sans lui donner de nom

pas de référence possible

classe anonyme peut dériver d’une autre classe (exemple de la classe JpaTemplate )

classe anonyme implémentant une interface

 

Héritage

le constructeur dérivée (fille) doit prendre en charge l’intégralité de la contruction du père.

ou bien utiliser le mot clé super() pour ne pas avoir à redéfinir les fonctionnalités et disposé de celle défini dans la classe mère.

 

Polymorphisme

complète l’héritage , peut prendre plusieurs formes ou comportement suivant les situations .

différentes formes de polymorphisme

méthode

classe

polymorphisme via heritage (on spécialise un comportement )

String … elements <=> String [] elements

 

final

interdit la modification de la valeur (variable )

méthode final ne peuvent être redéfini par une classe dérivée

classe final idem

 

classe abstraites

pas instancation objet possible

contient les méthodes et champs dont héritera toutes les classes dérivées

 

Exception

des erreur peuvent se produire on les gère… gestion des exceptions

Java.lang.Throwable

|

exception                                  java.lang.error

Runtime      SQLException/IOException

NPE

SeccurityException

 

Manipulation des chaines de caractères

StringBuffer

StringTokenizer

matcher

Java 5

  • prommation générique
  • annotation
  • autoboxing /unboxing (conversion auto des types )
  • énumération
  • nouvelles classes (scanner , formatter …)
  • Java concurrency

 

 

Collection en Java

  • Vecteur : ensemble objet pouvant être retrouvé par leur référence
  • Liste : ensemble objet classé par leur position
  • Ensembles : ensemble objet classé par leur type
  • Table de hashage :  ensemble objet classé à l’aide d’une clé
  • Pile : ensemble objet classé pouvant être simplement posé ou retiré

List

doublon autorisé

récupération via index

LinkedList (liste doublement chainée )

ArrayList (tableau redimensionnable)

Vector ( la différence avec ArrayList est qu’elle est synchronisé durant l’appel de la méthode de cette classe par un thread autre et ne peut être modifier )

 

Map

clé /valeur

unicité de la clé

HashTable va recherche ses éléments avec hashCode

HashTable est ThreadSafe et n’accepte pas null

 

HashMap n’est poas ThreadSafe

 

Set

n’accepte pas les doublons

HahsSet permet de stocker des objets sans doublons , n’accepte pas d’objet null (sinon NPE) => Iterator

 

TreeSet utilise un arbre de recherche

SortedSet

 

Pile

pop/push

 

Iterator

List<String> maListe = new ArrayList<String>();

maListe.add(« Bonkour »);

Iterator<String> it= maListe.iterator();

while(it.hasNext()){

sysout(it.next());

}

parcours HashMap

for(Key key : map.keySet()){}

 

SQL

inner join

relation 1-1 entre 2 tables

exemple :

Select * from Employee inner join departement on employee.DepartementID=departement.DepartementID

natural join : jointure faites sur les tables de même nom

Left / right join (favoriser une ou autre des tables)

Toutes les valeur de  A et les valeurs de B qui matche avec A

cela se traduit en clair quelquesoit ….. who is in

 

avr

19

Posted by : admin | On : 19 avril 2012

image

image

image

image

image

avr

19

Posted by : admin | On : 19 avril 2012

image

image

image

avr

19

Posted by : admin | On : 19 avril 2012

image

image

image

image

image

image

image

image

avr

19

Posted by : admin | On : 19 avril 2012

image

image

avr

19

Posted by : admin | On : 19 avril 2012

 

week end Ski 2012 Sungard

image

image

image

image

image

avr

04

Posted by : admin | On : 4 avril 2012

http://www.marmiton.org/recettes/recette_cookies-tout-chocolat_56794.aspx

mar

11

Posted by : admin | On : 11 mars 2012

http://www.marmiton.org/recettes/recette_blanquette-de-veau-de-la-baronne_25395.aspx

jan

10

Posted by : admin | On : 10 janvier 2012

Rss Reader

Bellow a Simple code about how to make a simple Rss Reader handle by SAX handler.



package mapping.rss;

public class Item {
	private String title ;
	private String description;
	private String link;
	private String pubDate;
	private String source;
	private String mediaContent;
	private String mediaText;
	/**
	 * @return the title
	 */
	public String getTitle() {
		return title;
	}
	/**
	 * @param title the title to set
	 */
	public void setTitle(String title) {
		this.title = title;
	}
	/**
	 * @return the description
	 */
	public String getDescription() {
		return description;
	}
	/**
	 * @param description the description to set
	 */
	public void setDescription(String description) {
		this.description = description;
	}
	/**
	 * @return the link
	 */
	public String getLink() {
		return link;
	}
	/**
	 * @param link the link to set
	 */
	public void setLink(String link) {
		this.link = link;
	}
	/**
	 * @return the pubDate
	 */
	public String getPubDate() {
		return pubDate;
	}
	/**
	 * @param pubDate the pubDate to set
	 */
	public void setPubDate(String pubDate) {
		this.pubDate = pubDate;
	}
	/**
	 * @return the source
	 */
	public String getSource() {
		return source;
	}
	/**
	 * @param source the source to set
	 */
	public void setSource(String source) {
		this.source = source;
	}
	/**
	 * @return the mediaContent
	 */
	public String getMediaContent() {
		return mediaContent;
	}
	/**
	 * @param mediaContent the mediaContent to set
	 */
	public void setMediaContent(String mediaContent) {
		this.mediaContent = mediaContent;
	}
	/**
	 * @return the mediaText
	 */
	public String getMediaText() {
		return mediaText;
	}
	/**
	 * @param mediaText the mediaText to set
	 */
	public void setMediaText(String mediaText) {
		this.mediaText = mediaText;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Item [title=");
		builder.append(title);
		builder.append(", description=");
		builder.append(description);
		builder.append(", link=");
		builder.append(link);
		builder.append(", pubDate=");
		builder.append(pubDate);
		builder.append(", source=");
		builder.append(source);
		builder.append(", mediaContent=");
		builder.append(mediaContent);
		builder.append(", mediaText=");
		builder.append(mediaText);
		builder.append("]");
		return builder.toString();
	}

}

package xml;

import java.util.ArrayList;
import java.util.List;

import mapping.rss.Item;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SearchItemRssHandler extends DefaultHandler {
	private final static String CHANNEL="channel";
	private final static String ITEM="item";
	private final static String TITLE="title";
	private final static String LINK="link";
	private final static String DESCRIPTION="description";
	private final static String SOURCE="source";
	private final static String PUBDATE="PUBDATE";

	private boolean bfChannel = false;
	private boolean bfItem = false;
	private boolean bfTitle = false;
	private boolean bflink = false ;
	private boolean bfDescription = false ;
	private boolean bfSource = false ;
	private boolean bfPubdate = false; 

	private Item item ;
	private List<Item> items ;
	public void startElement(String uri, String localName,String qName,
			Attributes attributes) throws SAXException {
		if(qName.equalsIgnoreCase(CHANNEL)){
			items = new ArrayList<Item>();
			bfChannel = true;
		}
		if(qName.equalsIgnoreCase(ITEM)){
			item = new Item();
			bfItem = true ;
		}
		if(qName.equalsIgnoreCase(TITLE)){
			bfTitle = true ;
		}
		if(qName.equalsIgnoreCase(LINK)){
			bflink = true ;
		}
		if(qName.equalsIgnoreCase(PUBDATE)){
			bfPubdate = true ;
		}
		if(qName.equalsIgnoreCase(SOURCE)){
			bfSource = true ;
		}
		if(qName.equalsIgnoreCase(DESCRIPTION)){
			bfDescription = true ;
		}

	}
	public void endElement(String uri, String localName,
			String qName) throws SAXException {
		if(qName.equalsIgnoreCase(ITEM)){
			items.add(item);
			bfItem = false;
		}
		if(qName.equalsIgnoreCase(CHANNEL)){
			setItems(items);
			bfChannel = false ;
		}
	}
	public void characters(char ch[], int start, int length) throws SAXException {
		String resu= new String(ch, start, length);
		if(bfItem){
			bfItem = false;
		}
		if(bfDescription){
			if(item!=null)
			item.setDescription(resu);
			bfDescription = false;
		}
		if(bfTitle){
			if(item!=null)
			item.setTitle(resu);
			bfTitle = false;
		}
		if(bflink){
			if(item!=null)
			item.setLink(resu);
			bflink = false ;
		}
		if(bfPubdate){
			if(item!=null)
			item.setPubDate(resu);
			bfPubdate = false;
		}
		if(bfSource){
			if(item!=null)
			item.setSource(resu);
		}
	}
	/**
	 * @return the items
	 */
	public List<Item> getItems() {
		return items;
	}
	/**
	 * @param items the items to set
	 */
	public void setItems(List<Item> items) {
		this.items = items;
	}
}

///TEST Main 

package xml.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import mapping.rss.Item;

import org.xml.sax.InputSource;

import xml.SearchItemRssHandler;

public class ReadRssXmlFile {
	public static void main(String argv[]) {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();

			File file = new File("C:\\workspace\src\\rss-test-fr.xml");
			InputStream inputStream= new FileInputStream(file);
			Reader reader = new InputStreamReader(inputStream,"UTF-8");

			InputSource is = new InputSource(reader);
			is.setEncoding("UTF-8");

			SearchItemRssHandler handler = new SearchItemRssHandler();
			saxParser.parse(is, handler);
			List<Item> items  = handler.getItems();
			for (Item item : items) {
				System.out.println(item);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

jan

09

Posted by : admin | On : 9 janvier 2012

Android developper doc :

http://developer.android.com/reference/android/widget/AutoCompleteTextView.html

Simple example :

http://www.botskool.com/geeks/how-create-auto-complete-textbox-android

Cook Book

http://androidcookbook.com/ViewTOC.seam

Run autocomplete android

http://stackoverflow.com/questions/7596508/autocomplete-data-retrived-via-http-request-not-hardcded-when-user-type-in-tex

with filter interface

http://stackoverflow.com/questions/8653260/autocomplete-in-android-not-working-with-dynamic-data

http://www.vingtseptpointsept.fr/2011/08/20/bricolons-un-peu-avec-idref/

1) Create below class in your activity

private class CostomTextWatcher implements TextWatcher {

@Override
public void afterTextChanged(Editable s) {
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.length() > 0) {
//Make HTTP connection and retrives autocomplete strings from webservice
}

}
}

2) set this above class to edittext using below way

etSearch.addTextChangedListener(new CostomTextWatcher());

You have to make http connection using Background Thread best is AsyncTask

 

 

 
Edit Text recherche dynamique

http://code.google.com/p/android-threshold-edittext/

Autre exemple

http://code.google.com/p/androidsearchexample/downloads/list

Search Suggestion On android
Exemple synthétique :

http://matthias.jimdo.com/blog/

Exemple pratique complet:

http://weblog.plexobject.com/?p=1689

explication globale

http://developer.android.com/guide/topics/search/search-dialog.html

Exemple de recherche Edit Text dynamique

package com.MobileAnarchy.Android.ThresholdEditText;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.TextView;

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

final TextView standardInput = (TextView)findViewById(R.id.TextViewStandardTextChange);
final TextView threasholdInput = (TextView)findViewById(R.id.TextViewThreasholdTextChange);

// Get the EditText reference
ThresholdEditText editText = (ThresholdEditText)findViewById(R.id.EditTextInput);

// Subscribe to the standard TextChanged events
editText.addTextChangedListener(new TextWatcher() {

@Override
public void afterTextChanged(Editable arg0) {
}

@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}

@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
standardInput.setText(arg0);
}

});

// You can manually set the threshold value (default is 500ms)
editText.setThreshold(1000);

// Subscribe to the OnTresholdTextChanged event
editText.setOnThresholdTextChanged(new ThresholdTextChanged() {

@Override
public void onThersholdTextChanged(Editable text) {
Log.d(« Test », « Threshold text changed event was called –  » + text.toString());
threasholdInput.setText(text);
}

});

}
}

package com.MobileAnarchy.Android.ThresholdEditText;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

public class ThresholdEditText extends EditText {

// =========================================
// Private members
// =========================================

private int threshold;
private ThresholdTextChanged thresholdTextChanged;
private Handler handler;
private Runnable invoker;
private boolean disableThresholdOnEmptyInput;

// =========================================
// Constructors
// =========================================

public ThresholdEditText(Context context) {
super(context);
initAttributes(null);
init();
}

public ThresholdEditText (Context context, AttributeSet attrs) {
super(context, attrs);
initAttributes(attrs);
init();
}

// =========================================
// Public properties
// =========================================

/**
* Get the current threshold value
*/
public int getThreshold() {
return threshold;
}

/**
* Set the threshold value (in milliseconds)
* @param threshold Threshold value
*/
public void setThreshold(int threshold) {
this.threshold = threshold;
}

/**
* @return True = the callback will fire immediately when the content of the EditText is emptied
* False = The threshold will be used even on empty input
*/
public boolean isDisableThresholdOnEmptyInput() {
return disableThresholdOnEmptyInput;
}

/**
* @param disableThresholdOnEmptyInput Set to true if you want the callback to fire immediately when the content of the EditText is emptied
*/
public void setDisableThresholdOnEmptyInput(boolean disableThresholdOnEmptyInput) {
this.disableThresholdOnEmptyInput = disableThresholdOnEmptyInput;
}

/**
* Set the callback to the OnThresholdTextChanged event
* @param listener
*/
public void setOnThresholdTextChanged(ThresholdTextChanged listener) {
this.thresholdTextChanged = listener;
}

// =========================================
// Private / Protected methods
// =========================================

/**
* Load properties values from xml layout
*/
private void initAttributes(AttributeSet attrs) {
if (attrs != null) {
String namespace= »http://schemas.android.com/apk/res/com.MobileAnarchy.ThresholdEditText »;

// Load values to local members
this.threshold = attrs.getAttributeIntValue(namespace, « threshold », 500);;
this.disableThresholdOnEmptyInput = attrs.getAttributeBooleanValue(namespace, « disableThresholdOnEmptyInput », true);;
}
else {
// Default threshold value is 0.5 seconds
threshold = 500;

// Default behaviour on emptied text – no threshold
disableThresholdOnEmptyInput = true;
}
}

/**
* Initialize the private members with default values
*/
private void init() {

handler = new Handler();

invoker = new Runnable() {

@Override
public void run() {
invokeCallback();
}

};

this.addTextChangedListener(new TextWatcher() {

@Override
public void afterTextChanged(Editable s) { }

@Override
public void beforeTextChanged(CharSequence s, int start, int count,    int after) { }

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

// Remove any existing pending callbacks
handler.removeCallbacks(invoker);

if (s.length() == 0 && disableThresholdOnEmptyInput)
{
// The text is empty, so invoke the callback immediately
invoker.run();
}
else {
// Post a new delayed callback
handler.postDelayed(invoker, threshold);
}
}

});
}

/**
* Invoking the callback on the listener provided (if provided)
*/
private void invokeCallback() {
if (thresholdTextChanged != null) {
thresholdTextChanged.onThersholdTextChanged(this.getText());
}
}

}

package com.MobileAnarchy.Android.ThresholdEditText;

import android.text.Editable;

public interface ThresholdTextChanged {
void onThersholdTextChanged(Editable text);
}