Using setError for edit text input validation Android - java

I'm checking for invalid input to a group of edit texts in an alert dialog, by checking for null input and calling setError. But in my current implementation the dialog still closes even though there has been invalid input.
A boolean check has been added to each edit text to prevent the dialog from being dismissed if any of the edit texts set the boolean to false like this:
else if(TextUtils.isEmpty(strColour)) {
colourText.setError("Please enter a value");
entriesValid = false;
`
But the dialog is still dismissed despite the invalid input.
My question, whats the error here that allows the dialog to close on invalid input?
I set a break point on this line, if(entriesValid) to check if the condition is triggered but it doesn't break here meaning that the check is be skipped.
This is the complete custom dialog class:
public class MyMessageDialog {
public interface MyMessageDialogListener {
public void onClosed(String ship, String scientist, String email, String volume, String color);
}
#SuppressLint("NewApi")
public static AlertDialog displayMessage(Context context, String title, String message, final MyMessageDialogListener listener){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
builder.setTitle(title);
builder.setMessage(message);
final View layoutView = inflater.inflate(R.layout.custom_view, null);
builder.setView(layoutView);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
boolean entriesValid = true;
// get the edit text values here and pass them back via the listener
if(listener != null)
{
EditText shipText = (EditText)layoutView.findViewById(R.id.shipNameEditText);
EditText scientistNameText = (EditText)layoutView.findViewById(R.id.scientistEditText);
EditText scientistEmailText = (EditText)layoutView.findViewById(R.id.emailEditText);
EditText volumeText = (EditText)layoutView.findViewById(R.id.volumeEditText);
EditText colourText = (EditText)layoutView.findViewById(R.id.colourEditText);
listener.onClosed(shipText.getText().toString(),
scientistNameText.getText().toString(),
scientistEmailText.getText().toString(),
volumeText.getText().toString(),
colourText.getText().toString());
String strShipName = shipText.getText().toString();
String strScientistName = scientistNameText.getText().toString();
String strScientistEmail = scientistEmailText.getText().toString();
String strVolume = volumeText.getText().toString();
String strColour = colourText.getText().toString();
if(TextUtils.isEmpty(strShipName)) {
shipText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strShipName)) {
shipText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strScientistName)) {
scientistNameText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strScientistEmail)) {
scientistEmailText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strVolume)) {
volumeText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strColour)) {
colourText.setError("Please enter a value");
entriesValid = false;
}
}
if(entriesValid)
dialog.dismiss();
}
});
builder.show();
return builder.create();
}
}

Instead of checking listener to be null, add a try catch block. I have not tried this code. But my idea is to remove listener block with try catch and set the boolean flag accordingly. That way it becomes simple.
#SuppressLint("NewApi")
public static AlertDialog displayMessage(Context context, String title, String message, final MyMessageDialogListener listener){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
builder.setTitle(title);
builder.setMessage(message);
final View layoutView = inflater.inflate(R.layout.custom_view, null);
builder.setView(layoutView);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
boolean entriesValid = true;
// get the edit text values here and pass them back via the listener
try
{
EditText shipText = (EditText)layoutView.findViewById(R.id.shipNameEditText);
EditText scientistNameText = (EditText)layoutView.findViewById(R.id.scientistEditText);
EditText scientistEmailText = (EditText)layoutView.findViewById(R.id.emailEditText);
EditText volumeText = (EditText)layoutView.findViewById(R.id.volumeEditText);
EditText colourText = (EditText)layoutView.findViewById(R.id.colourEditText);
String strShipName = shipText.getText().toString();
String strScientistName = scientistNameText.getText().toString();
String strScientistEmail = scientistEmailText.getText().toString();
String strVolume = volumeText.getText().toString();
String strColour = colourText.getText().toString();
if(TextUtils.isEmpty(strShipName)) {
shipText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strShipName)) {
shipText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strScientistName)) {
scientistNameText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strScientistEmail)) {
scientistEmailText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strVolume)) {
volumeText.setError("Please enter a value");
entriesValid = false;
}
else if(TextUtils.isEmpty(strColour)) {
colourText.setError("Please enter a value");
entriesValid = false;
}
}
catch(Exception e)
{
entriesValid = false;
}
if(entriesValid)
dialog.dismiss();
}
});
builder.show();
return builder.create();
}
update - New solution - Tried and worked for me
public class Help_DialogScreen extends Dialog implements OnClickListener{
Context context;
public Help_DialogScreen(Context context) {
super(context);
// TODO Auto-generated constructor stub
this.context=context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.help_homescreen);
EditText tvGoToAddExpense = (EditText)findViewById(R.id.txtGoToAddExpense);
Button btnTestCLick = (Button)findViewById(R.id.btnTestClick);
btnTestCLick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "Click fired", Toast.LENGTH_SHORT).show();
// I have used Toast to show that on click of button, dialog is not getting dismissed. You can add your code and do your logic here.
}
});
}
#Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
}
In the code where you should show the dialog, add this code
Help_DialogScreen cdd=new Help_DialogScreen(CURRENTACTIVITY.this);
cdd.show();

Related

cannot resolve method 'getwindow()' in Activity

am trying to add this this line in my Activity builder.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
but I find find this error Cannot resolve method'getwindow'
as am trying to add my code like this
NewGuestCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TabsActivity.this);
builder.setTitle("Insert Table Name");
// Set up the input
final EditText input = new EditText(TabsActivity.this);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String Table_Name = input.getText().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(TabsActivity.this);
builder.setTitle("Insert number of Covers");
// Set up the input
final EditText input2 = new EditText(TabsActivity.this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_CLASS_NUMBER);
builder.setView(input2);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String Cover_check = input2.getText().toString();
TablesFragment.Check_Items = ConnectionClass.Ret_dt("Select * From ChecksItems Where Check_ID = 0");
if (!TablesFragment.Check_Items.containsKey("Change_Temp")) {
if (TablesFragment.Check_Items.size() > 0) {
ArrayList<Object> Valrows = new ArrayList<Object>();
if (TablesFragment.Check_Items.get("Item_ID").size() > 0) {
for (int i = 0; i < TablesFragment.Check_Items.get("Item_ID").size(); i++) {
Valrows.add("");
}
}
TablesFragment.Check_Items.put("Change_Temp", Valrows);
}
}
if (Integer.parseInt(Cover_check) > 0) {
String st = ConnectionClass.Ret_Col("Select Max (CheckSerail) AS Ser From Checks_V where Officer = 0 AND OutLet_ID = " + ConnectionClass.OutletID + " And Rest_ID_Active = " + ConnectionClass.Rest_ID);
if (st.trim() == "")
st = "0";
int Check_Serial = Integer.parseInt(st) + 1;
long Check_ID = Long.parseLong(ConnectionClass.SelectNewIDCheck());
st = "insert into Checks .......
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
builder.show();
as I need from this method that when the alert dialog start the keyboard starts automatically that I don't need to touch the edit text to show the key board
sorry if any thing is not clear and sorry for my bad english
I hope this case could be solved
by the way activity looks
public class TabsActivity extends AppCompatActivity {
There is a similar question on StackOverflow. You need to call getWindow() on the Dialog Class.
call getWindow() by giving any views reference.ex
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

inform user if internet is not present to connect it to do the further process

I am developing an app in which i have to inform user that you are not connected to internet for further process.
I have two button accept and reject when we click on either button it should notify to connect to internet
private void initializeClickListeners() {
acceptB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int checkedOrders = checkedCheckboxArray.size();
Log.v(TAG,"size of the checked orders is: "+checkedOrders);
String msgOrdersText = "Order";
if(checkedOrders == 0)
{
Toast.makeText(getActivity(), "No Order Selected", Toast.LENGTH_SHORT).show();
}
else if(checkedOrders != 0 )
{
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
if(checkedOrders==1)
{
msgOrdersText = "Order";
}
if(checkedOrders>1)
{
msgOrdersText = "Orders";
}
adb.setTitle("Accept "+msgOrdersText);
adb.setMessage("Do you want to deliver "+checkedOrders+" "+msgOrdersText);
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Log.v(TAG,"Adding orders to current list on Acceptance");
int oId;
DatabaseHelper db = new DatabaseHelper(getActivity());
db.getReadableDatabase();
Cursor cursor = db.getNewOrders();
Log.v(TAG,"Count: "+cursor.getCount());
StringBuilder orderIds = new StringBuilder();
for(int i:checkedCheckboxArray)
{
cursor.moveToPosition(i);
//oId = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.ORDER_ID));
oId = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.ORDER_ID));
db.updateOrderStatus(oId, "A");
//Log.v(TAG,"ORDER id: "+oId);
orderIds.append(oId+"$");
}
Log.v(TAG,"Selected orders in string: "+orderIds);
UpdateSelectedOrdersStatusAsyncTask updateStatus = new UpdateSelectedOrdersStatusAsyncTask();
updateStatus.execute(orderIds.toString(),"1");
cursor.close();
db.close();
Toast.makeText(getActivity(), checkedOrders+" order accepted", Toast.LENGTH_SHORT).show();
// set the selected orders to none
checkedCheckboxArray.clear();
// set the state of checkbox for all the items in list to false
for(int i=0;i<checkedState.length;i++)
{
checkedState[i] = false;
}
// refill the list adapter
fillAdapter(0);
// update the order count notification in menu bar
setNotificationCounter();
}
});
adb.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.v(TAG,"Orders not added to the current list");
//checkedCheckboxArray.clear();
}
});
AlertDialog ad = adb.create();
ad.show();
}
}
});
rejectB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int checkedOrders = checkedCheckboxArray.size();
Log.v(TAG,"size of the checked orders is: "+checkedOrders);
String msgOrdersText = "Order";
if(checkedOrders == 0)
{
Toast.makeText(getActivity(), "No Order Selected", Toast.LENGTH_SHORT).show();
}
else if(checkedOrders != 0 )
{
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
if(checkedOrders==1)
{
msgOrdersText = "Order";
}
if(checkedOrders>1)
{
msgOrdersText = "Orders";
}
adb.setTitle("Reject "+msgOrdersText);
adb.setMessage("Do you want to Reject "+checkedOrders+" "+msgOrdersText);
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.v(TAG,"Adding orders to current list");
int oId;
DatabaseHelper db = new DatabaseHelper(getActivity());
db.getReadableDatabase();
Cursor cursor = db.getNewOrders();
Log.v(TAG,"Count: "+cursor.getCount());
StringBuilder orderIds = new StringBuilder("");
for(int i:checkedCheckboxArray)
{
cursor.moveToPosition(i);
oId = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.ORDER_ID));
db.updateOrderStatus(oId, "R");
orderIds.append(oId+"$");
}
cursor.close();
db.close();
Log.v(TAG,"Selected orders in string: "+orderIds);
UpdateSelectedOrdersStatusAsyncTask updateStatus = new UpdateSelectedOrdersStatusAsyncTask();
updateStatus.execute(orderIds.toString(),"2");
Toast.makeText(getActivity(), checkedOrders+" order rejected/deleted", Toast.LENGTH_SHORT).show();
checkedCheckboxArray.clear();
// set the state of checkbox for all the items in list to false
for(int i=0;i<checkedState.length;i++)
{
checkedState[i] = false;
}
fillAdapter(0);
setNotificationCounter();
}
});
adb.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.v(TAG,"Orders not added to the current list");
}
});
AlertDialog ad = adb.create();
ad.show();
}
}
});
Now i am putting my device internet status code
public class DeviceInternetStatus {
private static final String TAG = "Buzz";
private static DeviceInternetStatus instance = new DeviceInternetStatus();
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
public static DeviceInternetStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
Log.v(TAG,"Type of Network(Device Internet Status): "+networkInfo);
connected = networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
return connected;
} catch (Exception e) {
Log.v("Buzz","Connectivity Exception"+ e.toString());
}
return connected;
}
You need to create a constructor passing the object of OnItemClickListener
like this,
static Class<? extends OnItemClickListener> cls;
public static DeviceInternetStatus getInstance(OnItemClickListner listner) {
cls=listener.getClass();
return instance;
}

Android refresh rating bar upon triggeration

I am having some problem when trying to refresh the rating bar after user submitted their rating. So basically I am passing the existing rating amount when certain button on my other Activity was triggered:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Object[] obj = new Object[2];
obj[0] = String.valueOf(eventIDTV.getText());
obj[1] = eventReviewModel;
new GetEventDetailAsyncTask(new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
// Passing whole object with value into another activity
Intent eventDtlIntent = new Intent(context, EventDetailMain.class);
// Pass in a list of rating star together with amount
eventDtlIntent.putExtra("eventPopulateStarObj", populateRatingStar);
context.startActivity(eventDtlIntent);
}
}).execute(obj);
}
});
And I am populating the rating bar when onCreate():
ratingStarList = (ArrayList<EventReview>) i
.getSerializableExtra("eventPopulateStarObj");
public void populateRatingProgressBar() {
int totalStar = 0;
// Get the total amount of rate records
for (int j = 0; j < ratingStarList.size(); j++) {
if (ratingStarList.get(j).getStarAmt() != null) {
totalStar += Integer.parseInt(ratingStarList.get(j)
.getStarAmt());
}
}
txtTotalRate.setText(totalStar + " Ratings for this event");
// Set progress bar based on the each rates
for (int i = 0; i < ratingStarList.size(); i++) {
if (ratingStarList.get(i).getStarAmt() != null) {
if (ratingStarList.get(i).getEventReviewRate().equals("5")) {
pb5Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("4")) {
pb4Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("3")) {
pb3Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("2")) {
pb2Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
} else if (ratingStarList.get(i).getEventReviewRate()
.equals("1")) {
pb1Star.setProgress(Integer.parseInt(ratingStarList.get(i)
.getStarAmt()));
}
}
}
}
It did populated correctly. However, I not sure how to refresh the rating bar after user submitted their rating. Here is the code when user submit their rating:
public void promptSubmitStar() {
AlertDialog.Builder Dialog = new AlertDialog.Builder(getActivity());
Dialog.setTitle("Confirm Rating");
LayoutInflater li = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View dialogView = li.inflate(R.layout.option_submit_star, null);
txtPromptStarRate = (TextView) dialogView
.findViewById(R.id.txtPromptStarRate);
txtPromptStarRate.setText("Confirm to submit " + starRate
+ " stars for this event?");
Dialog.setView(dialogView);
Dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EventReview eventReviewModel = new EventReview();
eventReviewModel.setEventID(eventID);
eventReviewModel.setEventReviewBy(userID);
eventReviewModel.setEventReviewRate(String.valueOf(starRate));
new CreateEventReviewAsyncTask(context)
.execute(eventReviewModel);
dialog.dismiss();
// Disable the rating bar by setting a touch listener which
// always return true
ratingBar.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
return true;
}
});
}
});
Dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
Dialog d = Dialog.show();
EventDialogueBox.customizeDialogueBox(context, d);
}
Any ideas? Thanks in advance.
Use setRating(starRate); to programmatically set the rating on the RatingBar.

Resume Method in Android

I want resume the same Activity if i without complete filling the form and click on submit button and exit my Activity .And again i start my app its same Activity i want to start.How can do this.Can some one help me please.Thanks in Advance.
Here is my code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_details);
SharedPreferences
settings=getSharedPreferences("prefs",0); boolean
firstRun=settings.getBoolean("firstRun",false);
if(firstRun==false)//if running for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
//execute your code for first time
}
else
{
Intent iSubmit = new Intent(Registration_Form.this,Employee_List.class);
startActivity(iSubmit);
finish();
//Default Activity startActivity(a);
}
databaseHelper = new DatabaseHelper(this);
databaseHelper.onOpen(db);
et_CompanyName = (EditText) findViewById(R.id.editText_CompanyName);
et_EmployeeName = (EditText) findViewById(R.id.editText_EmployeeName);
et_CompanyWebsite = (EditText) findViewById(R.id.editText_CompanyWebSite);
et_ContactNumber = (EditText) findViewById(R.id.editText_ConatctNo);
et_Email_Id = (EditText) findViewById(R.id.editText_EmailId);
radioGroup_FinancialYaer = (RadioGroup)findViewById(R.id.radioGroupFinanncialYear);
btnSubmit = (Button) findViewById(R.id.buttonSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String stringEmail_Id = et_Email_Id.getText().toString()
.trim();
final String stringCompanyWebsite = et_CompanyWebsite.getText()
.toString().trim();
if ((et_CompanyName.getText().toString().isEmpty())) {
et_CompanyName.setError("Field Can Not Be Empty !");
}
else if (!et_CompanyName.getText().toString().trim()
.matches("[a-zA-Z ]+")) {
et_CompanyName.setError("Accept Alphabets Only.");
}
else if ((et_EmployeeName.getText().toString().isEmpty())) {
et_EmployeeName.setError("Field Can Not Be Empty !");
}
else if (!et_EmployeeName.getText().toString().trim()
.matches("[a-zA-Z ]+")) {
et_EmployeeName.setError("Accept Alphabets Only.");
}
else if ((et_CompanyWebsite.getText().toString().isEmpty())) {
et_CompanyWebsite.setError("Field Can Not Be Empty !");
}
else if (!isValidUrl(stringCompanyWebsite)) {
et_CompanyWebsite.setError("Invalid URL");
}
else if ((et_ContactNumber.getText().toString().isEmpty())) {
et_ContactNumber.setError("Field Can Not Be Empty !");
}
else if (!isValidEmail(stringEmail_Id)) {
et_Email_Id.setError("Invalid Email");
}
else
{
String stringCompanyName = et_CompanyName.getText()
.toString().trim();
String stringContactNumber = et_ContactNumber.getText()
.toString().trim();
String stringEmployeeName = et_EmployeeName.getText()
.toString().trim();
int selectedId = radioGroup_FinancialYaer.getCheckedRadioButtonId();
Log.e("selectedId "," = " + selectedId);
radioButton_FinancialYaer = (RadioButton) findViewById(selectedId);
strFinancialYear = radioButton_FinancialYaer.getText().toString().trim();
Log.e("strRadioButton "," = " + strFinancialYear);
databaseHelper.insertRegstrationDetails(stringCompanyName,
stringEmployeeName, stringCompanyWebsite,
stringContactNumber, stringEmail_Id, strFinancialYear);
System.out.println("Data Inserted Successfully !!! ");
Intent iSubmit = new Intent(Registration_Form.this,Staff_Employee_Details.class);
startActivity(iSubmit);
finish();
}
}
});
}
// validating email id
private boolean isValidEmail(String email) {
String EMAIL_PATTERN = "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\#"
+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
private boolean isValidUrl(String url) {
Pattern p = Patterns.WEB_URL;
Matcher m = p.matcher(url);
if(m.matches())
return true;
else
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(Registration_Form.this);
alertbox.setTitle("Do you wish to exit ?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// finish used for destroyed activity
finish();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Nothing will be happened when clicked on no button
// of Dialog
}
});
alertbox.show();
}
return super.onKeyDown(keyCode, event);
}
}
Put all your EditText values in a table in your Database.
Keep an extra column called count in your table. When user presses Submit button increment the value of count on the basis of number of entries user has entered at that moment in your EditText and save it in database.
When user again launches your app, check value of count, if it is equal to your expected value route him as per your requirement, if it's less than expected then show your form activity, populate data from database.
You can implement this feature by using a Splash Screen.
EDIT : WHAT YOU ACTUALLY WANTED
If user presses back button and starts your application you will be directed to the same activity if it's your launcher activity, else you can check if all the fields aren't filled then you can save a boolean value in SharedPreference and check it's state while launching your app and launch this activity if it's true.

How to validate multiple edittext fields with a pop-up message or alert dialog box?

I'd like to know how to validate my 4 edittext fields if one or more of these fields are left empty after tapping the button to process the inputs. I have searched many solutions like using toast but It think it's not appropriate for multiple edittext fields and using textwatchers. I'd like the app to show a pop-up message or alert dialog box saying "Please fill up the necessary fields."
Any help would be appreciated.
You can use below common function for checking the Null values of the edittext:
public static boolean m_isError;
public static void checkEntryForEmptyValue(EditText p_editText, String p_nullMsg)
{
if (p_editText != null || p_nullMsg != null)
{
// use trim() while checking for blank values
if ((p_editText.getText().toString().trim().equalsIgnoreCase("")) || (p_editText.getText().toString().trim().length() <= 0))
{
m_isError = true;
p_editText.setError(p_nullMsg);
p_editText.requestFocus();
}
}
}
}
Use the above function as below inside your button click listener:
CommonUtil.m_isError = false;
CommonUtil.checkEntryForEmptyValue(edittext,getResources().
getString(R.string.MessageEmpty));
if (!CustomValidator.m_isError)
{
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_SHORT).show();
}
else
{
//Your dialog with the error messages.
}
u can use some tooltips for validation like qtip or poshytip
http://vadikom.com/demos/poshytip/
http://craigsworks.com/projects/qtip/
Write a validation function to check all text fields and append the tooltip object with the corresponding fields which fails the validation.
Use this validate function when you click on button and you can check the alert message after method is executed
boolean flag_1= true,flag_2=true,flag_3=true;
String alertmsg;
.
private boolean validate()
{
EditText et1 = (EditText)findViewById(R.id.et1);
EditText et2 = (EditText)findViewById(R.id.et2);
EditText et3 = (EditText)findViewById(R.id.et3);
if(et1.getText().toString().isEmpty())
{
alertmsg+= "Please fill 1st\n";
flag_1 = false;
}
if(et2.getText().toString().isEmpty())
{
alertmsg+= "Please fill 2nd\n";
flag_2 = false;
}
if(et3.getText().toString().isEmpty())
{
alertmsg+= "Please fill 3rd";
flag_3 = false;
}
return flag_1||flag_2||flag_3;
}
Try this :
EDIT:
Call this onClick of your process-input button:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.mRlayout1);
boolean success = formIsValid(rl);
if(success == false){
// alert dialog box
}
else{
// process ahead
}
Declare this function:
EDIT:
public boolean formIsValid(RelativeLayout layout) {
for (int i = 0; i < layout.getChildCount(); i++) {
View v = layout.getChildAt(i);
Class<? extends View> c = v.getClass();
if (c == EditText.class) {
EditText et = (EditText) v;
if(et.getText().toString().equals(""))
return false;
//Toast.makeText(getApplicationContext(), ""+et.getText().toString(), Toast.LENGTH_LONG).show();
}
}
return true;
}
By this you can validate N number of input controls with single call.
Thanks.
The Simplest soulution is that check that if the fields are empty then show dialog here is simple code snippet
private void checkEntries()
{
if(!(email.getText().toString().equals("")))
{
if(!(pass.getText().toString().equals("")))
{
if(UIHelper.getInstance().emailAddressValidation(email.getText().toString()))
{
if(pass.getText().length()>=5)
{
sendLoginRequest(email.getText().toString(),pass.getText().toString(),Constants.PHONE_ID);
}
else
{
dialogBoxInUIthread("String","Password length should be greater than 5 ",LoginController.this,true);
}
}
else
{
dialogBoxInUIthread("String","Invalid Email Id",LoginController.this,true);
}
}
else
{
dialogBoxInUIthread("String","Please enter password",LoginController.this,true);
}
}
else
{
dialogBoxInUIthread("String","Please enter email",LoginController.this,true);
}
}
private void dialogBoxInUIthread(final String title,final String msg, Context context,final boolean completed) {
/* runOnUiThread(new Runnable() {
public void run() {*/
AlertDialog.Builder alertbox = new AlertDialog.Builder(LoginController.this);
alertbox.setTitle(title);
alertbox.setMessage(msg);
alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
if(completed){
}else{ }
}
});alertbox.show();
/* }
});*/
}

Categories