Email validation only when field is not blank in Android - java

Validate email format only if EditText is not blank in Android. And if the field is blank validation should not be check. I did not find any solution in this scenario which is useful for me.

Try this code
final EditText emailEditTxt= (EditText)findViewById(R.id.text);
String emailStr = emailEditTxt.getText().toString().trim();
if(emailStr!=null)
if(emailStr.length()>=1){
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (emailStr .matches(emailPattern))
{
Toast.makeText(getApplicationContext(),"valid email address",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}
}

Try this..
boolean flag;
String pass = editText.getText().toString().trim();
if(!pass.equals("")) {
flag = isEmailValid(pass);
}
public static boolean isEmailValid(CharSequence email) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
and use the flag value for further use

Use this method for check email pattern is valid or not
public static boolean isEmailValid(CharSequence email) {
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

validateEmail
private boolean validateEmail() {
if (!edemail.getText().toString().trim().isEmpty()&&!ValidationMethod.emailValidation(edemail.getText().toString()))
{
input_layout_email.setError("Invalid Email"); // Your textInput Layout or other set your error on edittext email
requestFocus(edemail);
return false;
}
else {
input_layout_email.setErrorEnabled(false);
}
return true;
}
// if you need requestfocus other wise remove
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
ValidationMethod.java // put in your project
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidationMethod {
static Matcher m;
static String emailExpression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,20}$";
static Pattern emailPattern = Pattern.compile(emailExpression, Pattern.CASE_INSENSITIVE);
static String passwordExpression ="((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\\W).{8,20})";
static Pattern passwordPattern=Pattern.compile(passwordExpression);
public static boolean emailValidation(String s)
{
if( s == null)
{
return false;
}
else
{
m = emailPattern.matcher(s);
return m.matches();
}
}
public static boolean passwordValidation(String s)
{
if( s == null)
{
return false;
}
else
{
m = passwordPattern.matcher(s);
return m.matches();
}
}
public static boolean emailValidation2(String s)
{
m = emailPattern.matcher(s);
return m.matches();
}
}

try This
<form>
<lable for="userEmail">Email : </label>
<input type="email" id="userEmail" placeholder="johndoe#example.com" required="required">
<form>

Lets say you have declared EditText like this.
EditText emailField;
then in your method
emailField = (EditText)view.getViewById(R.id.NAME_OF_FIELD_IN_XML);
if(!TextUtils.isBlank(emailField.getText().toString())){
//validate your email address
}
Use below link for email validation code.
http://stackoverflow.com/questions/12947620/email-address-validation-in-android-on-edittext

You can try this for validation.
public boolean Email_validation(String CorpId)
{
String regExpn =
"^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+"[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+"([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$";
CharSequence inputStr = CorpId;
Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches())
return true;
else
return false;
}

Related

Android: OnTextChanged email validation is not working as expected

I am using the fololowing code to validate the email input
private boolean validateEmail(String email) {
String emailPattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
Pattern pattern = Pattern.compile(emailPattern);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
I execute this on onTextChanged. The code is below (I am using ButterKnife)
#OnTextChanged(R.id.et_email)
public void checkCorrectEmail() {
if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
isValidated = false;
mEditTextEmail.setError("Please enter email address");
mEditTextEmail.requestFocus();
} else {
isValidated = true;
}
}
The issue is that it is not intelligent enough. For an example, if I type myemail#gmail.com it still show the error message. However if I type myemail#gmail.com then a space and clicked delete the space then everything is fine, error gone.
Formerly this validation was on onClick of a button. What have I done wrong here?
#OnTextChanged(R.id.et_email)
public void checkCorrectEmail () {
if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
isValidated = false;
mEditTextEmail.setError("Please enter email address");
mEditTextEmail.requestFocus();
} else {
isValidated = true;
mEditTextEmail.setError(null);
}
}
100% working
Try this :
#OnTextChanged(R.id.et_email)
public void checkCorrectEmail() {
if (!validateEmail(mEditTextEmail.getText().toString().trim())) {
isValidated = false;
mEditTextEmail.setError("Please enter email address");
mEditTextEmail.requestFocus();
} else {
mEditTextEmail.setError(null)
isValidated = true;
}
}
clear the error on correct input
Use the in-build Email pattern checker method:
#OnTextChanged(R.id.et_email)
public void checkCorrectEmail () {
if (!Patterns.EMAIL_ADDRESS.matcher(mEditTextEmail.getText().toString()).matches()){
isValidated = false;
mEditTextEmail.setError("Please enter a Valid E-Mail Address!");
mEditTextEmail.requestFocus();
}else {
isValidated = true;
mEditTextEmail.setError(null);
}

How to refer to data from within inner class

I'm new to java programming so I apologize for the possibly incorrect wording of the question. I have a boolean function updateEntryDB that should return false if the response from my database is "Error" and true if it is "Success". How do I get the boolean response from the #override method OnSuccessBool, so that my updateEntryDB function will return the proper response? Thanks for any help.
private boolean updateEntryDB(final String tag)
{
//Log.i(TAG, "updateEntryDB");
String np = numPlate.getText().toString();
dbWork dbWork = new dbWork();
dbWork.updateEntryTime(tag, np, requestQueue, new dbWork.VolleyCallback() {
#Override
public void onSuccess(String result) {
}
#Override
public boolean onSuccessBool(String result) {
String dbResponse = result;
test.setText(dbResponse);
String[] errSucc = dbResponse.split(":");
if(errSucc[0].equals("Error"))
{
return false;
}
else if(errSucc[0].equals("Success"))
{
return true;
}
return false;
}
});
}

How to optimize my Java code for using Java 7 switch?

I have a query is that I have a string that I get through a param, the issue is that the split I realize you do not know if it's the best, but the idea was to separate these value chains that interest me, and then compare them.
public class TestSplit {
public static final String CODIGO_BUSCAR = "001";
public static final String CODIGO_NUEVO = "002";
public static final String CODIGO_MODIFICAR = "003";
public static final String CODIGO_ELIMINAR = "004";
public static final String CODIGO_CONSULTAR = "006";
public static void main(String[] args) throws Exception {
boolean mostrarBotonNuevo = false;
boolean mostrarBotonModificar = false;
boolean mostrarBotonConsultar = false;
boolean mostrarBotonEliminar = false;
boolean mostrarBotonBuscar = false;
String key = "{javax.faces.partial.ajax=true, javax.faces.source=j_idt88:linkAjax, javax.faces.partial.execute=#all, javax.faces.partial.render=mensajesGrowl, j_idt88:linkAjax=j_idt88:linkAjax, parametroAccion={javax.faces.partial.ajax=true, javax.faces.source=j_idt80:j_idt82:linkAjax, javax.faces.partial.execute=#all, javax.faces.partial.render=mensajesGrowl, j_idt80:j_idt82:linkAjax=j_idt80:j_idt82:linkAjax, parametroAccion={menuForm=menuForm, j_idt46_activeIndex=0, javax.faces.ViewState=KAITjDUzvPckml3R4yYr9j3J2z/iwqr8HrkQyCyPl4QUNAom0iY7kGQqomJaUN4enfhiwIGBXb1c9bgohVXD3P0emxCpykIM9fGP2hBtKq2fPssmHkbbYDNa5DX2mxTvTssCeRZ/Y1dTSim2x/J/lJQFpa8e/GJh8KkK7AaVCb1X3kk5J5nZHIlhDpfnRwGe7VfHxkQNKsdiDhf+lCwp+rDb0eGsOyGnRSaIB83TVbCBqN6E8IARA6i5FiQe6qW6hxAA0tpCoMGQO69sKau3TCZEAbDCyLnaGa471QEl4974sSziZVQBRywJJsdBM+seSrgnO04idUdCpY7n/qJLyB8L5yNn5beTki/azTOMBPKQgK2NC/ACILU/E8QeQ6zq0vJ43/I16s+t1IgB3ajnOAMsvkMyU9LLDjlbCrMnlyoUVlPIwVK6Qg+dBTkyNOXXTuYLm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j_idt55=j_idt46:j_idt55, menuItemCotizaciones005=menuItemCotizaciones005, menuItemCotizaciones006=menuItemCotizaciones006, j_idt46:j_idt55_menuid=2_9, menuItemCotizaciones003=menuItemCotizaciones003, menuItemCotizaciones004=menuItemCotizaciones004, menuItemCotizaciones001=menuItemCotizaciones001, menuItemCotizaciones002=menuItemCotizaciones002}, principalForm=principalForm, idSeleccionoRegistro=false, j_idt120:input=, j_idt124:select_focus=, j_idt124:select_input=, j_idt129:select_focus=, j_idt129:select_input=, j_idt134:calendar_input=, j_idt137:calendar_input=, javax.faces.ViewState=YmaLdynq93csVHnfBbfsdEoqLX1VsE34AnGcIl1K609wg0pfECjwZI0e3Y/hu6fvEhAElNo9Theyrh8/cEDWpeiQRJ/is89OXCI3dpp1Gk8oEERlP3xS4ivexx3OzET5k2UqbGDOYvv9yejBe7jwCJqA4Uw/yXtXHc959XW7sAjV9Rs8d5JqWgchaayW0UaWdPb0piAs+e5WETWxYZShLXGF3kQ+ikf4NG1xUEiOnXvUHyn+Th7tbmRqSEa/idPOKzoirxMunWtGXWg9/Uu3cl2OqBwDJEMT99ryys5THtds8fgrixOvNksVsuk8HkeR/QrwFq9LM7CqWu1ho9PyAraySSg5WRN9IZkcFV7MGw5TzJG9pVkGZs21xeZozB28Fk5tiG9c3G9qa9IXYL53RLOZb27/wLZlWPedGkiDoEzXXdnSP315uRshDASLCMzvqJFy4/Y4IX2Sdk5Ks4px9aqGMoXFUd2vJpOQniKrx+tkzUsX5NNheLQZCHGchSDivhjwxmbxk/hy0KnKAsitC/XM2cb47Jvd/Y/zqDmFMu05Jya36rOC+bT7hElV9u/NZgf0ZscFuZ4x6LIWKyjkhAmRanSOBDlFs24fu3NMv+FE2Q5OpGzgHyDn+gq1fo4tcNk9szeSuF06FMtIA5vnd1GCojssv5c0cRv656ndBLx9hHmIULjg9avxu0fpKHTLQultYTXTp9m7OCkESSTKV/qLymItsGgwLK3NvDEQ0a3ovweO6GKEi8MTnOxn0aFw06F7YmsObd4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j+mdb3SuGcrHcaNb4e7jyO9S/JziaoX+WOKfj3lZ7Enr32NMeNospIiXqYu6DzMdW8egfjGydZuKx/zfDsycvYUJ1HKD8W588F5ZkDTxSH3C/CPf50FpTEEBX+RXe7+6WPs71rUTepkqAjOYMgw4gVpD+nNx5C...";
String keyFormat [] = key.split("=");
for(String value : keyFormat) {
System.out.println("--> "+value);
if(value.endsWith(CODIGO_BUSCAR)) {
mostrarBotonBuscar = true;
}
if(value.endsWith(CODIGO_NUEVO)) {
mostrarBotonNuevo = true;
}
if(value.endsWith(CODIGO_MODIFICAR)) {
mostrarBotonModificar = true;
}
if(value.endsWith(CODIGO_ELIMINAR)) {
mostrarBotonEliminar = true;
}
if(value.endsWith(CODIGO_CONSULTAR)) {
mostrarBotonConsultar = true;
}
}
System.out.println("--> mostrarBotonBuscar: "+mostrarBotonBuscar+" mostrarBotonNuevo: "+mostrarBotonNuevo+
" mostrarBotonModificar: "+mostrarBotonModificar+" mostrarBotonEliminar: "+mostrarBotonEliminar+
" mostrarBotonConsultar: "+mostrarBotonConsultar);
}
}
Basically what I do is use the slipt to separate strings and compare whether the value ends in "001", "002", "003", "004" and "006", what other details do not matter, and then they meet is activate the corresponding boolean state.
I was thinking to use a switch or while operator to optimize my code, if anyone can give me a guidance to improve my code, because as noticing the loop is comparing each chain, the idea is to compare each and finish the loop.
I don't think while even fits here. switch will not do any good either (rather leave it as it is, or better, change ifs to else-ifs.. But I can give a better idea, that involves none of them. Just make use of || operator. That will require changing your for loop to something like:
for(String value : keyFormat) {
System.out.println("--> "+value);
mostrarBotonBuscar = mostrarBotonBuscar || value.endsWith(CODIGO_BUSCAR);
mostrarBotonNuevo = mostrarBotonNuevo || value.endsWith(CODIGO_NUEVO);
mostrarBotonModificar = mostrarBotonModificar || value.endsWith(CODIGO_MODIFICAR);
mostrarBotonEliminar = mostrarBotonEliminar || value.endsWith(CODIGO_ELIMINAR);
mostrarBotonConsultar = mostrarBotonConsultar || value.endsWith(CODIGO_CONSULTAR);
}
That's it. Nothing else you need. Moreover it will also stop evaluating the corresponding endsWith() methods once the flag is set to true.
Thus concern with doing subtring and switch ....
public class TestSplit {
public static final String CODIGO_BUSCAR = "001";
public static final String CODIGO_NUEVO = "002";
public static final String CODIGO_MODIFICAR = "003";
public static final String CODIGO_ELIMINAR = "004";
public static final String CODIGO_CONSULTAR = "006";
public static void main(String[] args) throws Exception {
boolean mostrarBotonNuevo = false;
boolean mostrarBotonModificar = false;
boolean mostrarBotonConsultar = false;
boolean mostrarBotonEliminar = false;
boolean mostrarBotonBuscar = false;
String key = "{javax.faces.partial.ajax=true, javax.faces.source=j_idt88:linkAjax, javax.faces.partial.execute=#all, javax.faces.partial.render=mensajesGrowl, j_idt88:linkAjax=j_idt88:linkAjax, parametroAccion={javax.faces.partial.ajax=true, javax.faces.source=j_idt80:j_idt82:linkAjax, javax.faces.partial.execute=#all, javax.faces.partial.render=mensajesGrowl, j_idt80:j_idt82:linkAjax=j_idt80:j_idt82:linkAjax, parametroAccion={menuForm=menuForm, j_idt46_activeIndex=0, javax.faces.ViewState=KAITjDUzvPckml3R4yYr9j3J2z/iwqr8HrkQyCyPl4QUNAom0iY7kGQqomJaUN4enfhiwIGBXb1c9bgohVXD3P0emxCpykIM9fGP2hBtKq2fPssmHkbbYDNa5DX2mxTvTssCeRZ/Y1dTSim2x/J/lJQFpa8e/GJh8KkK7AaVCb1X3kk5J5nZHIlhDpfnRwGe7VfHxkQNKsdiDhf+lCwp+rDb0eGsOyGnRSaIB83TVbCBqN6E8IARA6i5FiQe6qW6hxAA0tpCoMGQO69sKau3TCZEAbDCyLnaGa471QEl4974sSziZVQBRywJJsdBM+seSrgnO04idUdCpY7n/qJLyB8L5yNn5beTki/azTOMBPKQgK2NC/ACILU/E8QeQ6zq0vJ43/I16s+t1IgB3ajnOAMsvkMyU9LLDjlbCrMnlyoUVlPIwVK6Qg+dBTkyNOXXTuYLm9hXdaIcjbXXqLbQj7igfFWA9dAmCn5AAHA8ttIQ6kEBuTc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Cotizaciones006=menuItemCotizaciones006, j_idt46:j_idt55_menuid=2_9, menuItemCotizaciones003=menuItemCotizaciones003, menuItemCotizaciones004=menuItemCotizaciones004, menuItemCotizaciones001=menuItemCotizaciones001, menuItemCotizaciones002=menuItemCotizaciones002}, principalForm=principalForm, idSeleccionoRegistro=false, j_idt120:input=, j_idt124:select_focus=, j_idt124:select_input=, j_idt129:select_focus=, j_idt129:select_input=, j_idt134:calendar_input=, j_idt137:calendar_input=, javax.faces.ViewState=YmaLdynq93csVHnfBbfsdEoqLX1VsE34AnGcIl1K609wg0pfECjwZI0e3Y/hu6fvEhAElNo9Theyrh8/cEDWpeiQRJ/is89OXCI3dpp1Gk8oEERlP3xS4ivexx3OzET5k2UqbGDOYvv9yejBe7jwCJqA4Uw/yXtXHc959XW7sAjV9Rs8d5JqWgchaayW0UaWdPb0piAs+e5WETWxYZShLXGF3kQ+ikf4NG1xUEiOnXvUHyn+Th7tbmRqSEa/idPOKzoirxMunWtGXWg9/Uu3cl2OqBwDJEMT99ryys5THtds8fgrixOvNksVsuk8HkeR/QrwFq9LM7CqWu1ho9PyAraySSg5WRN9IZkcFV7MGw5TzJG9pVkGZs21xeZozB28Fk5tiG9c3G9qa9IXYL53RLOZb27/wLZlWPedGkiDoEzXXdnSP315uRshDASLCMzvqJFy4/Y4IX2Sdk5Ks4px9aqGMoXFUd2vJpOQniKrx+tkzUsX5NNheLQZCHGchSDivhjwxmbxk/hy0KnKAsitC/XM2cb47Jvd/Y/zqDmFMu05Jya36rOC+bT7hElV9u/NZgf0ZscFuZ4x6LIWKyjkhAmRanSOBDlFs24fu3NMv+FE2Q5OpGzgHyDn+gq1fo4tcNk9szeSuF06FMtIA5vnd1GCojssv5c0cRv656ndBLx9hHmIULjg9avxu0fpKHTLQultYTXTp9m7OCkESSTKV/qLymItsGgwLK3NvDEQ0a3ovweO6GKEi8MTnOxn0aFw06F7YmsObd4ITKIR8qwHTjORGcPDskBL0mS3+r7idBG8JEgTyjPM4l9D9lYree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MeNospIiXqYu6DzMdW8egfjGydZuKx/zfDsycvYUJ1HKD8W588F5ZkDTxSH3C/CPf50FpTEEBX+RXe7+6WPs71rUTepkqAjOYMgw4gVpD+nNx5C...";
String keyFormat [] = key.split("=");
for(String value : keyFormat) {
int size = value.length();
if(size > 3) {
String vcodIdeObj = value.substring(size-3, size);
switch (vcodIdeObj) {
case CODIGO_BUSCAR:
mostrarBotonBuscar = true;
break;
case CODIGO_NUEVO:
mostrarBotonNuevo = true;
break;
case CODIGO_MODIFICAR:
mostrarBotonModificar = true;
break;
case CODIGO_ELIMINAR:
mostrarBotonEliminar = true;
break;
case CODIGO_CONSULTAR:
mostrarBotonConsultar = true;
break;
}
}
}
}
}
Please validate my code, thanks.

Is it possible to evaluate a boolean expression for String comparions?

I will have a String like
('abc' != 'xyz' AND 'thy' = 'thy') OR ('ujy' = 'ujy')
The String will be able to have as many "AND" groups as it wants. There will not be any nested groups within the AND groups. All groups will ALWAYS be serparated by an OR.
I can just switch out the AND for && and OR for ||.
What I would like is to pass this String into some type of eval method and output TRUE or FALSE.
Is there anything out there that can do this?
You can use the built-in Javascript engine coming with the JDK1.6 to evaluate string containing math expressions.
You an give a lookup here: ScriptEngine
Here an example:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Myclass {
public static void main(String[] args) {
try {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("JavaScript");
String myExpression = "('abc' == 'xyz' && 'thy' == 'thy') || ('ujy' == 'ujy')";
System.out.println(se.eval(myExpression));
} catch (ScriptException e) {
System.out.println("Invalid Expression");
e.printStackTrace();
}
}
}
Just remember to replace the following:
'AND' with '&&',
'OR' with '||',
'=' must be '=='
Otherwise it will not accept your expression and will throws a javax.script.ScriptException
you can use script package to achieve this like
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
String[] vars = {"var1 = 'xyz'", "var2 = 'xyz'"};
try {
for (String var : vars) {
engine.eval(var);
}
System.out.println(engine.eval("var1 == var2 "));
} catch (ScriptException e) {
e.printStackTrace();
}
I think you have to parse it and write custom classes for it like this
public interface StringEquals{
public boolean equals(String s1, String s2);
}
public class Equals implements StringEquals{
private String mS1;
private STring mS2;
public NotEquals(String s1, String s2){
mS1 = s1;
mS2 = s2;
}
public boolean equals(){
return mSq1.equals(mS2);
}
}
public class NotEquals implements StringEquals{
private String mS1;
private STring mS2;
public NotEquals(String s1, String s2){
mS1 = s1;
mS2 = s2;
}
public boolean equals(){
return !mS1.equals(mS2);
}
}
public class AndGroup{
private List<StringEquals> mStrings;
public AndGroup(List<StringEquals> list){
mStrings = list;
}
public boolean getResult(){
for(StringEquals e: mStrings){
if (!e.equals()){
return false;
}
}
return true;
}
and a class to parse it:
public boolean eval(String evalString){
List<AndGroup> groups = new LinkedList<AndGroup>();
String[] ands = evalString.split("OR");
for (String andExp : ands){
List<StringEquals> list = new LinkedList<StringEquals>();
String compares = andExp.split("AND");
for (String comp: compares){
if (comp.contains("!="){
String[] notEqual = comp.split("!=");
list.add(new NotEquals(notEqual[0], notEqual[1]));
} else {
String[] equal = comp.split("=");
list.add(new Equals(equal[0], equal[1]);
}
}
groups.add(new AndGroup(list));
}
for (AndGroup g: groups){
if (g.getResult()){
return true;
}
}
return false;
}
not tested, but it may point you into the right direction
I think you can try groovy (if it's an option for you) with it's groovy.util.Eval, but first you should process your string and replace AND\OR with && and ||.

Smack messaging client other than Chat Text

client1 can send txt message to client2 using
connection.getChatManager().createChat(to, this).sendMessage(message);
How to send other kind of message: like INFO message ? (client1 to client2) ?
Because I want, INFO message should not be displayed in the chat window....is it possible ? using smack, smackx library.
Many Thanks.
What you want do do here is to add an extension to your text message. Here is a rough guide.
Chat chat = connection.getChatManager().createChat(to, this);
Message message = new Message(to, Message.Type.chat);
message.setBody("hello");
message.setProperty(prop0, val0);
message.setProperty(prop1, val1);
chat.sendMessage(message)
The properties are carried in a separate namespace (use toXML() to look at it) and will not appear in the chat window. On the 'other side', the applications uses getProperty() to retrieve the value.
If you do not want key/value pairs, but structured data, use addExtension() in the message body. This is a little more complicated because you basically have to extend PacketExtension, provide your own namespace. You might even have to write a PacketExtensionProvider.
Here is the example for message extension.
The basic XML structure of the XMPP protocol is:
<message
from='sender_jid'
to='receiver_jid'
type='message_type'>
<body> content </body>
</message>
The process of sending messages:
//build chat
Chat chat = chatManager.createChat("jid");
//build extension
UserInfo4XMPP userInfo4XMPP = new UserInfo4XMPP();
userInfo4XMPP.setNameText("userx");
userInfo4XMPP.setUrlText("http://www.liaoku.org/");
//build message
Message message = new Message();
message.setBody("hello");
message.addExtension(userInfo4XMPP);// add the extension
//send
chat.sendMessage(message);
The UserInfo4XMPP is defined as:
import org.jivesoftware.smack.packet.ExtensionElement;
public class UserInfo4XMPP implements ExtensionElement{
private String elementName = "userinfo";
private String nameElement = "name";
private String urlElement = "url";
private String nameText = "";
private String urlText = "";
#Override
public String getElementName() {
return elementName;
}
#Override
public CharSequence toXML() {
StringBuilder sb = new StringBuilder();
sb.append("<");
sb.append(elementName);
sb.append(">");
sb.append("<");
sb.append(nameElement);
sb.append(">");
sb.append(nameText);
sb.append("</");
sb.append(nameElement);
sb.append(">");
sb.append("<");
sb.append(urlElement);
sb.append(">");
sb.append(urlText);
sb.append("</");
sb.append(urlElement);
sb.append(">");
sb.append("</");
sb.append(elementName);
sb.append(">");
return sb.toString();
}
#Override
public String getNamespace() {
return "";
}
public String getNameText() {
return nameText;
}
public void setNameText(String nameText) {
this.nameText = nameText;
}
public String getUrlText() {
return urlText;
}
public void setUrlText(String urlText) {
this.urlText = urlText;
}
}
A more complicated example of message extention:
Message videoMsg = new Message();
VideoChatRTP videoXml = new VideoChatRTP();
videoXml.setVideoType(VideoMediaType.REQUEST);
videoXml.setAddress(address);
videoMsg.setTo(receive);
videoMsg.addExtension(videoXml);
XMPPConnection conn = BaseService.getInstance().getConnection();
conn.sendPacket(videoMsg);
The extension class VideoChatRIP must implement PacketExtension:
public class VideoChatRTP implements PacketExtension {
private VideoMediaType videoType;
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public VideoMediaType getVideoType() {
return videoType;
}
public void setVideoType(VideoMediaType videoType) {
this.videoType = videoType;
}
public static final String NAME = "jingle";
public static final String NAME_SPACE = "com:roger:video";
public VideoChatRTP() {
super();
}
#Override
public String getElementName() {
return NAME;
}
#Override
public String getNamespace() {
return NAME_SPACE;
}
#Override
public String toXML() {
StringBuffer sb = new StringBuffer();
sb.append("<jingle").append(" xmlns=\"").append(NAME_SPACE).append(
"\">");
sb.append("<type>").append(videoType).append("</type>");
sb.append("<ipAddress>").append(address).append("</ipAddress>");
sb.append("</jingle>");
return sb.toString();
}
}
The Listener:
ProviderManager.getInstance().addExtensionProvider(VideoChatRTP.NAME, VideoChatRTP.NAME_SPACE, new VideoChatReceive());
Processing:
public class VideoChatReceive implements PacketExtensionProvider {
#Override
public PacketExtension parseExtension(XmlPullParser parser)
throws Exception {
boolean done = false;
String requestType = "asdasd";
String ipAddress = "asdasd";
while (!done) {
int eventType = parser.next();
String name = parser.getName();
if (eventType == XmlPullParser.START_TAG) {
if (name.equals("type")) {
requestType = parser.nextText();
}
if (name.equals("ipAddress")) {
ipAddress = parser.nextText();
}
}
if (eventType == XmlPullParser.END_TAG) {
if (name.equals("jingle")) {
done = true;
}
}
}
VideoChatRTP videoRtp = new VideoChatRTP();
videoRtp.setVideoType(VideoMediaType.valueOf(requestType));
videoRtp.setAddress(ipAddress);
return videoRtp;
}
}

Categories