Wednesday, 8 January 2014

ANDROID FORM VALIDATION- (BEST WAY)

ANDROID FORM VALIDATION- THE RIGHT WAY


            In our coding life, many times we need to validate the fields, like Email validation on EditText input text, give a error notification when get the value of EditText is null. then we have to take care about validation. For example, Any activity have multiple EditText there are a need to validate the EditText then We should create Validation for all the fields which work for overall application.
          Here I am showing what is best way to validate our form fields.

MainActivity.java

import com.dwivedi.androidformvalidation.Validator.Field;
import com.dwivedi.androidformvalidation.Validator.Form;
import com.dwivedi.androidformvalidation.Validator.FormUtils;
import com.dwivedi.androidformvalidation.Validator.validations.InRange;
import com.dwivedi.androidformvalidation.Validator.validations.IsEmail;
import com.dwivedi.androidformvalidation.Validator.validations.NotEmpty;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;




public class MainActivity extends Activity {

 
   private EditText mName;
   private EditText mEmail;
   private EditText mAge;
   private Button mSubmit;

   // Form used for validation
   private Form mForm;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       initFields();
       initValidationForm();
       initCallbacks();
   }

   

   private void initFields() {
       mName = (EditText) findViewById(R.id.name);
       mEmail = (EditText) findViewById(R.id.email);
       mAge = (EditText) findViewById(R.id.age);
       mSubmit = (Button) findViewById(R.id.submit);
   }

   private void initValidationForm() {
       mForm = new Form(this);
       mForm.addField(Field.using(mName).validate(NotEmpty.build(this)));
       mForm.addField(Field.using(mEmail).validate(NotEmpty.build(this)).validate(IsEmail.build(this)));
       mForm.addField(Field.using(mAge).validate(InRange.build(this, 0, 120)));
   }

   private void initCallbacks() {
       mAge.setOnEditorActionListener(new TextView.OnEditorActionListener() {
           @Override
           public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
               if (actionId == EditorInfo.IME_ACTION_DONE) {
                   submit();
                   return true;
               }
               return false;
           }

       });

       mSubmit.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               submit();
           }
       });
   }

   private void submit() {
       FormUtils.hideKeyboard(MainActivity.this, mAge);
       if (mForm.isValid()) {
        //   Crouton.makeText(this, getString(R.string.sample_activity_form_is_valid), Style.CONFIRM).show();
        Toast.makeText(this, getString(R.string.sample_activity_form_is_valid), Toast.LENGTH_LONG).show();
       }
   }
  }

Validation.java

package com.dwivedi.androidformvalidation.Validator.validations;


public interface Validation {

    String getErrorMessage();

    boolean isValid(String text);

}

Field.java

package com.dwivedi.androidformvalidation.Validator;

import android.widget.EditText;

import java.util.LinkedList;
import java.util.List;

import com.dwivedi.androidformvalidation.Validator.validations.Validation;



public class Field {

    private List<Validation> mValidations = new LinkedList<Validation>();
    private EditText mTextView;

    private Field(EditText textView) {
        this.mTextView = textView;
    }

    public static Field using(EditText textView) {
        return new Field(textView);
    }

    public Field validate(Validation what) {
        mValidations.add(what);
        return this;
    }

    public EditText getTextView() {
        return mTextView;
    }

    public boolean isValid() throws FieldValidationException {
        for (Validation validation : mValidations) {
            if (!validation.isValid(mTextView.getText().toString())) {
                String errorMessage = validation.getErrorMessage();
                throw new FieldValidationException(errorMessage, mTextView);
            }
        }
        return true;
    }

}



FormUtils.java

package com.dwivedi.androidformvalidation.Validator;

import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;


public class FormUtils {

    public static void showKeyboard(Context context, TextView textView) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            // only will trigger it if no physical keyboard is open
            imm.showSoftInput(textView, 0);
        }
    }

    public static void hideKeyboard(Context context, TextView textView) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            // only will trigger it if no physical keyboard is open
            imm.hideSoftInputFromWindow(textView.getWindowToken(), 0);
        }
    }
}


Form.java

package com.dwivedi.androidformvalidation.Validator;

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

import android.app.Activity;
import android.widget.EditText;
import android.widget.Toast;


public class Form {

    private List<Field> mFields = new ArrayList<Field>();
    private Activity mActivity;

    public Form(Activity activity) {
        this.mActivity = activity;
    }

    public void addField(Field field) {
        mFields.add(field);
    }

    public boolean isValid() {
        boolean result = true;
        try {
            for (Field field : mFields) {
                result &= field.isValid();
            }
        } catch (FieldValidationException e) {
            result = false;

            EditText textView = e.getTextView();
            textView.requestFocus();
            textView.selectAll();

            FormUtils.showKeyboard(mActivity, textView);

            showErrorMessage(e.getMessage());
        }
        return result;
    }

    protected void showErrorMessage(String message) {
       // Crouton.makeText(mActivity, message, Style.ALERT).show();
    Toast.makeText(mActivity, message, Toast.LENGTH_LONG).show();
    }
}


FieldValidationException.java

package com.dwivedi.androidformvalidation.Validator;

import android.widget.EditText;


public class FieldValidationException extends Exception {

    private EditText mTextView;

    public FieldValidationException(String message, EditText textView) {
        super(message);
        mTextView = textView;
    }

    public EditText getTextView() {
        return mTextView;
    }
}



BaseValidation.java

package com.dwivedi.androidformvalidation.Validator.validations;

import android.content.Context;


abstract class BaseValidation implements Validation {

    protected Context mContext;

    protected BaseValidation(Context context) {
        mContext = context;
    }

}



IsEmail.java


package com.dwivedi.androidformvalidation.Validator.validations;

import android.content.Context;

import com.dwivedi.androidformvalidation.R;



public class IsEmail extends BaseValidation {

    private static final String EMAIL_PATTERN =
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    private IsEmail(Context context) {
        super(context);
    }

    public static Validation build(Context context) {
        return new IsEmail(context);
    }

    @Override
    public String getErrorMessage() {
        return mContext.getString(R.string.zvalidations_not_email);
    }

    @Override
    public boolean isValid(String text) {
        return text.matches(EMAIL_PATTERN);
    }
}



The complete code this is GITHUB link. Checkout and enjoy coding.





   

ASYNCTASK CLASS IMPLEMENT CALLBACK FUNCTION WITH INTERFACE (BEST WAY)


Today I start writing on my blog, In this blog, My intention to show only code with very brief description.


BEST WAY TO USE Asynctask  CLASS IN YOU APPLICATION
OR
IMPLEMENT CALLBACK FUNCTION WITH INTERFACE


           Many Times we use Asyctask class to perform the background task in our android application. Here I am showing what is the best way to use Asynctask class with our application.
           We should create a abstract class which are extends Asyctask class and also a callback behaviour of a Interface which used to callback the result to UI component like Activity.

      Here code, how to do this

MainActivity.java

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;

import com.example.androidcallback.POJO.XMLItemTagClass;
import com.example.androidcallback.POJO.XMLRootClass;

public class MainActivity extends ListActivity implements
ICallBack<XMLItemTagClass, XMLRootClass> {

private static final String URL_FIRST_TASK = "http://dl.dropboxusercontent.com/u/72603672/demo/abc.xml";
MyAsyncTask myAsyncTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

myAsyncTask = new MyAsyncTask(this);
myAsyncTask.execute(URL_FIRST_TASK);

ListAdapter adapter = new ItemAdapter(this);
setListAdapter(adapter);
}

@Override
public void taskStart() {
Log.i("MainClass", "Task Start");
}

@Override
public void taskCompleted(XMLRootClass result) {

Log.i("MainClass", "Task completed result ");

}

@Override
public void taskProgress(XMLItemTagClass... progress) {

((ItemAdapter) getListAdapter()).addItem(progress[0]);

}

@Override
public Context getContext() {
return this;
}


}



ICallBack.java





import android.content.Context;

public interface ICallBack<Progress,Result> {
Context getContext();
void taskStart();
void taskCompleted(Result result);
void taskProgress(Progress... progress);
}



ITaskRunner.java

import android.os.AsyncTask;

public abstract class ITaskRunner<Params, Progress, Result> extends
AsyncTask<Params, Progress, Result> {

private ICallBack<Progress, Result> callBack;

public ITaskRunner(ICallBack<Progress, Result> callBack) {
this.callBack = callBack;
}

@Override
protected void onPreExecute() {
super.onPreExecute();
callBack.taskStart();
}

@Override
protected void onPostExecute(Result result) {

callBack.taskCompleted(result);

}

@Override
protected void onProgressUpdate(Progress... values) {

callBack.taskProgress(values);
}
}




The complete code this is GITHUB link. Checkout and enjoy coding.