I want to calculate square root by inputing string. I try to use Math.sqrt(string) but it doesn't work. Do you have any idea how to calculate this?
I really have no idea how to use it with this library.
public class MainActivity extends ActionBarActivity {
// IDs of all the numeric buttons
private int[] numericButtons = {R.id.btnZero, R.id.btnOne, R.id.btnTwo, R.id.btnThree, R.id.btnFour, R.id.btnFive, R.id.btnSix, R.id.btnSeven, R.id.btnEight, R.id.btnNine};
// IDs of all the operator buttons
private int[] operatorButtons = {R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide,R.id.buttonSqr,R.id.tan,R.id.cos,
R.id.sin,R.id.open_bracket,R.id.close_bracket};
// TextView used to display the output
private EditText txtScreen;
// Represent whether the lastly pressed key is numeric or not
private boolean lastNumeric=true;
// Represent that current state is in error or not
private boolean stateError;
// If true, do not allow to add another DOT
private boolean lastDot;
private boolean firstTime = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (EditText) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
//Find and set OnClickListener to numeric buttons.
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
firstTime = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
//Find and set OnClickListener to operator buttons, equal button and decimal point button.
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
Log.d("dsfds",txtScreen.getText().toString());
lastNumeric = false;
lastDot = false; // Reset the DOT flag
firstTime = true;
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Decimal point
findViewById(R.id.btnDot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lastNumeric && !stateError && !lastDot) {
txtScreen.append(".");
lastNumeric = false;
lastDot = true;
//firstTime = false;
}
}
});
//delete
findViewById(R.id.btndel).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (txtScreen.getText().toString().length() > 1) {
//remove string
String screen_new = txtScreen.getText().toString().substring(0, txtScreen.getText().toString().length() - 1);
txtScreen.setText(screen_new);
} else {
txtScreen.setText("");
}
lastNumeric = false;
stateError = false;
lastDot = false;
//firstTime = false;
}
});
// Clear button
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
//firstTime = false;
}
});
// Equal button
findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});
}
//Logic to calculate the solution
private void onEqual() {
// If the current state is error, nothing to do.
// If the last input is a number only, solution can be found.
//if (lastNumeric && !stateError) {
if ((firstTime || lastNumeric) && !stateError){
// Read the expression
String txt = txtScreen.getText().toString();
Log.d( txt, "error");
txt = txt.replaceAll("x", "*").replaceAll("รท", "/");
// Create an Expression (A class from exp4j library)
Expression expression = new ExpressionBuilder(txt).build();
try {
// Calculate the result and display
double result = expression.evaluate();
txtScreen.setText(Double.toString(result));
lastDot = true; // Result contains a dot
} catch (ArithmeticException ex) {
// Display an error message
txtScreen.setText("Error");
stateError = true;
lastNumeric = false;
}
}
}
}
First convert your String into a number using a DecimalFormat object and it's parse function then compute your square root.
DecimalFormat df=new DecimalFormat();
sq=java.lang.Math.sqrt(df.parse(myString).doubleValue());
Related
I am trying to create an activity which contain an edittext, of which background color and fonts should be changed whenever the button is been clicked.
To perform these actions on the edittext, I have created two ArrayList of int value and saved all the color's id and the font's id in this ArrayList. whenever the button is clicked the background color didn't change but the color's Hexa code print in the edittext and these color codes comes with extra ff values in front of every color's code like #ff1EFA9D and in the font method I am getting an error that says:-
Unable to start activity ComponentInfo{com.nanb.alpha/com.nanb.alpha.postcreater}: java.lang.ArrayIndexOutOfBoundsException: length=4; index=-1
I have tried to find the solution over the internet but didn't get any solution that satisfies the error.
code For changing the background color and font of the edittext is given below
private EditText editText;
private ImageButton color,font;
ArrayList<Integer> bgcolorlist = new ArrayList<Integer>(10);
ArrayList<Integer> fontstyle = new ArrayList<Integer>(6);
int fontstylename=R.font.abril_fatface,bgcolor=R.color.white,fontpostion = fontstyle.indexOf(fontstylename);
int postion = bgcolorlist.indexOf(bgcolor);
private void Initialization() {
cancel = view.findViewById(R.id.backbutton);
createnextbutton = view.findViewById(R.id.nextbutton);
editText = view.findViewById(R.id.textpost);
color = view.findViewById(R.id.bgcolorbutton);
font = view.findViewById(R.id.fontstyle);
}
//codes are for the background color changing
private void backgroundcolormethod() {
bgcolorlist.add(R.color.white);
bgcolorlist.add(R.color.darkGreen);
bgcolorlist.add(R.color.colorPrimaryDark);
bgcolorlist.add(R.color.colorAccent);
bgcolorlist.add(R.color.colorPrimary);
bgcolorlist.add(R.color.orange);
bgcolorlist.add(R.color.edittextbg5);
bgcolorlist.add(R.color.edittextbg4);
bgcolorlist.add(R.color.edittextbg3);
bgcolorlist.add(R.color.edittextbg2);
bgcolorlist.add(R.color.edittextbg1);
editText.setBackgroundColor(bgcolor);
color.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(postion == 10){
//Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(bgcolorlist.get(postion));
postion = 0;
}else{
int newpostion = postion + 1;
editText.setText(bgcolorlist.get(newpostion));
postion = newpostion;
}
}
});
}
//codes for changing the fonts
private void fontstylemethod() {
fontstyle.add(R.font.abril_fatface);
fontstyle.add(R.font.cedarville_cursive);
fontstyle.add(R.font.alfa_slab_one);
fontstyle.add(R.font.annie_use_your_telescope);
fontstyle.add(R.font.aclonica);
fontstyle.add(R.font.aguafina_script);
fontstyle.add(R.font.arizonia);
editText.setTypeface(Typeface.defaultFromStyle(fontpostion));
font.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fontpostion == 6){
Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(fontstyle.get(postion));
fontpostion= 0;
}else{
int newpostion = fontpostion + 1;
editText.setText(fontstyle.get(newpostion));
fontpostion = newpostion;
}
}
});
}
Help me to solve these errors.
Try changing your codes to this:
ArrayList<Integer> bgcolorlist = new ArrayList<Integer>(11);
ArrayList<Integer> fontstyle = new ArrayList<Integer>(7);
int fontpostion = 0;
int postion = 0;
private void Initialization() {
cancel = view.findViewById(R.id.backbutton);
createnextbutton = view.findViewById(R.id.nextbutton);
editText = view.findViewById(R.id.textpost);
color = view.findViewById(R.id.bgcolorbutton);
font = view.findViewById(R.id.fontstyle);
}
//codes are for the background color changing
private void backgroundcolormethod() {
bgcolorlist.add(R.color.white);
bgcolorlist.add(R.color.darkGreen);
bgcolorlist.add(R.color.colorPrimaryDark);
bgcolorlist.add(R.color.colorAccent);
bgcolorlist.add(R.color.colorPrimary);
bgcolorlist.add(R.color.orange);
bgcolorlist.add(R.color.edittextbg5);
bgcolorlist.add(R.color.edittextbg4);
bgcolorlist.add(R.color.edittextbg3);
bgcolorlist.add(R.color.edittextbg2);
bgcolorlist.add(R.color.edittextbg1);
editText.setBackgroundColor(bgcolorlist.get(0));
color.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(postion == 10){
//Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(bgcolorlist.get(postion));
postion = 0;
}else{
postion++;
editText.setText(bgcolorlist.get(postion));
}
}
});
}
//codes for changing the fonts
private void fontstylemethod() {
fontstyle.add(R.font.abril_fatface);
fontstyle.add(R.font.cedarville_cursive);
fontstyle.add(R.font.alfa_slab_one);
fontstyle.add(R.font.annie_use_your_telescope);
fontstyle.add(R.font.aclonica);
fontstyle.add(R.font.aguafina_script);
fontstyle.add(R.font.arizonia);
editText.setTypeface(Typeface.defaultFromStyle(fontstyle.get(0)));
font.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fontpostion == 6){
Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(fontstyle.get(postion));
fontpostion= 0;
}else{
fontpostion++;
editText.setText(fontstyle.get(fontpostion));
}
}
});
}
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.
I made an app for my use for calculating a string of values appear in an another activity. My app has 3 editTexts and one button. If we press button calculate with the input in edit text and calculated values will displayed in a second activity. I made it successfully but my problem is if the user is leave any of the boxes empty and press the button, the system will Force Close. To avoid this I made editText in graphical layout pre entered with a hint. But if the user accidentally presses button after editing the editText again system shows a Force Close.
I tried many if else methods but it does not work. Some one show me a correct way to check all editText boxes.
public class Screen1 extends Activity {
public static StringBuilder EXTRA_MESSAGE=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
Button bu1= (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View message)
{ int f1,f3,f4;
String vis;
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
String e1=t1.getText().toString();
String e3= t3.getText().toString();
String e4= t4.getText().toString();
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1)
{
sb.append(String.format("%.1f", i)+" mcg = "+(f1*60*i*f4)/(f3*1000)+"\n");
}
vis=sb.toString();
Intent intent = new Intent(message.getContext(),Screen2.class);
intent.putExtra("EXTRA_MESSAGE",vis);
startActivity(intent);
}
});
}
}
Using [TextUtils][1] check isEmpty() text inside your onClick:
#Override
public void onCreate(Bundle savedInstanceState){
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
Button bu1 = (Button) findViewById(R.id.bu);
bu1.setOnClickListener(this);
}
#Override
public void onClick(View message){
boolean foundEmpty = false;
if(TextUtils.isEmpty(t1.getText())) {
foundEmpty = true;
t1.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t2.getText()){
foundEmpty = true;
t2.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t3.getText()){
foundEmpty = true;
t3.setError("Please enter a value");
}
if(!foundEmpty){
/* none of your text fields are empty */
int f1, f3, f4;
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
final StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1) {
sb.append(String.format("%.1f", i)+
" mcg = "+
(f1*60*i*f4)/(f3*1000)+"\n");
}
final String vis = sb.toString();
Intent intent = new Intent(message.getContext(), Screen2.class);
intent.putExtra("EXTRA_MESSAGE", vis);
startActivity(intent);
}
}
From what I gather from your question, you're getting an error when bu1 is clicked, and at least one of the EditTexts is empty. This is because you're calling Integer.parseInt() on an empty String. The following code will check if the boxes are empty, and show a Toast if any are. It will also show a Toast if the user enters anything that's not a valid number:
public class Screen1 extends Activity
{
private static final String EXTRA_MESSAGE = "extra_msg";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
final EditText t1 = (EditText)findViewById(R.id.a);
final EditText t3 = (EditText)findViewById(R.id.c);
final EditText t4 = (EditText)findViewById(R.id.d);
Button bu1 = (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View message)
{
int f1,f3,f4;
String e1 = t1.getText().toString();
String e3 = t3.getText().toString();
String e4 = t4.getText().toString();
if (e1.equals("") || e3.equals("") || e4.equals(""))
{
Toast.makeText(Screen1.this, "Please enter all numbers.", Toast.LENGTH_SHORT).show();
return;
}
try
{
f1 = Integer.parseInt(e1);
f4 = Integer.parseInt(e4);
f3 = Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for (float i = 0.1f; i <= 5; i = i + .1f)
{
sb.append(String.format("%.1f", i) + " mcg = " + (f1 * 60 * i * f4) / (f3 * 1000) + "\n");
}
Intent intent = new Intent(Screen1.this, Screen2.class);
intent.putExtra(EXTRA_MESSAGE, sb.toString());
startActivity(intent);
}
catch (NumberFormatException e)
{
Toast.makeText(Screen1.this, "Invalid numbers.", Toast.LENGTH_SHORT).show();
}
}
}
);
}
}
I have an app here which adds the number. I have 4 edittexts here. What I want to happen is that when i entered none in one of the edittexts, it will assume that I entered 0. How can it be done? Here is my code:
public class Order extends Activity {
Button GoBackHome;
private Button button1;
private EditText txtbox1,txtbox2,txtbox3,txtbox4;
private TextView tv;
Button PayNow;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
GoBackHome = (Button) findViewById(R.id.gohomebutton);
PayNow = (Button) findViewById(R.id.button2);
txtbox1= (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.editText5);
txtbox2= (EditText) findViewById(R.id.editText2);
txtbox3= (EditText) findViewById(R.id.editText3);
txtbox4= (EditText) findViewById(R.id.editText4);
button1.setOnClickListener(new clicker());
GoBackHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, MainActivity.class);
startActivity(i);
}
});
PayNow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, Payment.class);
startActivity(i);
}
});
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
}
}
}
You can do as Tushar said or you can initialize the value in the XML. Something like
<EditText
android:name="#+id/editText1"
android:text="0"/>
FYI you might also find it cleaner to handle your button clicks on xml like:
<Button
android:name="#+id/btn1"
android:onClick="handleClicks"/>
and then in java you'd have a public void method:
public void handleClicks(View clickedView){
if(clickedView.getId() == btn1.getId(){
...
} else if (...){}
}
initialize as :
txtbox1.setText("0");
Check the EditText length when you get it
String value = null;
if(ed.getText().length()){
value = textBox.getText().toString();
} else
value = 0+"";
You can set android:hint="0" in your XML file, then, in your code, you can check if it's empty (maybe using TextUtils.isEmpty()) and setting some variable to 0.
android:hint="0" will make a "0" appear in your EditTexts, but the "0" will disappear when anything is inputted.
Then you can change the onClick() to this:
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
try {
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
} catch (NumberFormatException e) {
vis = "0";
}
// Do something with "vis"
}
}
Or you can create a method to check a value, try to parse to an int or return a default value.
public int getInt(String edtValue, int defaultValue) {
int value = defaultValue;
if (edtValue != null) {
try {
value = Integer.parseInt(edtValue);
} catch (NumberFormatException e) {
value = defaultValue;
}
}
return value;
}
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;
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();
/* }
});*/
}