requiring editView boxes be completed before moving to another activity - android

Here is my current AddDebt.java section I'm looking at:
public void ButtonOnClick(View v) {
Intent intent = new Intent(this, MainActivity.class);
EditText debtors = (EditText) findViewById(R.id.editDebtor);
String debtor = debtors.getText().toString();
EditText myEdit = (EditText) findViewById(R.id.editBalance);
String myEditValue = myEdit.getText().toString();
double loanAmount = Double.parseDouble(myEditValue);
EditText myEdit2 = (EditText) findViewById(R.id.editRate);
String myEditValue2 = myEdit2.getText().toString();
double interestRate = Double.parseDouble(myEditValue2);
EditText myEdit3 = (EditText) findViewById(R.id.editTerm);
String myEditValue3 = myEdit3.getText().toString();
Double loanPeriod = Double.parseDouble(myEditValue3);
double r = interestRate/1200;
double r1 = Math.pow(r+1,loanPeriod);
double editMnthlypmt = (double) ((r+(r/(r1-1))) * loanAmount);
DecimalFormat df = new DecimalFormat("#.##");
editMnthlypmt = Double.valueOf(df.format(editMnthlypmt));
TextView textMnthlypmt = (TextView)findViewById(R.id.textMntlypmt);
switch (v.getId()) {
case R.id.calculate:
textMnthlypmt.setText("" + String.valueOf(editMnthlypmt));
break;
case R.id.addDebt:
if(debtors.getText().length() == 0){
Toast.makeText(getApplicationContext(), "Please enter debtors value", Toast.LENGTH_SHORT).show();
debtors.requestFocus();
}else if(myEdit.getText().length() == 0){
Toast.makeText(getApplicationContext(), "Please enter myedit value", Toast.LENGTH_SHORT).show();
myEdit.requestFocus();
}
else
{
//Transferring data to MainActivity
intent.putExtra("debtor",debtor);
intent.putExtra("loanAmount",loanAmount);
intent.putExtra("editMnthlypmt",editMnthlypmt);
//Next moves back to MainActivity
startActivity(intent);
}
break;
}
}
when "case R.id.addDebt:" is being chosen, I want to ensure that editDebtor, editBalance, editRate, and editTerm are all completed. If not, I want it to set focus on the topmost box that is incomplete. If completed I want it to switch to my intent.
Any suggestions.

try this,
case R.id.addDebt:
if(debtors.getText().length() == 0){
Toast.makeText(Activityname, "Please enter debtors value", Toast.LENGTH_SHORT).show();
debtors.requestFocus();
}else if(myEdit.getText().length() == 0){
Toast.makeText(Activityname, "Please enter myedit value", Toast.LENGTH_SHORT).show();
myEdit.requestFocus();
}else if().......
}else{
//Add your Intent here
}

Related

User Input of int won't be null

I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}

Why it didn't get current EditText value

I'm doing basic demo of android related to login, update user
I used user's id from login page to load user's information to update page
username = (EditText) findViewById(R.id.txtUsername);
age = (EditText) findViewById(R.id.txtAge);
weight = (EditText) findViewById(R.id.txtWeight);
height = (EditText) findViewById(R.id.txtHeight);
username.setText(db_username);
age.setText(db_age);
weight.setText(db_weight);
height.setText(db_height);
and update button
update.setOnClickListener(new View.OnClickListener() {
int sweight = Integer.parseInt(weight.getText().toString());
double sheight = Double.parseDouble(height.getText().toString());
int sage = Integer.parseInt(age.getText().toString());
#Override
public void onClick(View v) {
if (weight.equals("")) {
Toast.makeText(getApplicationContext(), "Please input weight!",
Toast.LENGTH_LONG).show();
return;
}else if(height.equals("")){
Toast.makeText(getApplicationContext(), "Please input height!",
Toast.LENGTH_LONG).show();
return;
}else if(age.equals("")){
Toast.makeText(getApplicationContext(), "Please input age!",
Toast.LENGTH_LONG).show();
return;
}else{
dbHandler.updateUser(sid,sweight,sheight,sage);
Toast.makeText(getApplicationContext(),
"User's information updated! ", Toast.LENGTH_LONG)
.show();
Toast.makeText(getApplicationContext(),
sid+sweight+sheight+sage+" and test", Toast.LENGTH_LONG)
.show();
Intent i = new Intent(UserUpdate.this, MainActivity.class);
startActivity(i);
finish();
}
}
});
For exam: weight: 70,height:1,65,age:21
when i changed it to: weight:50,height:1,65,age:21
the 2nd Toast show me that weight : 70 but not 50
You need to move these top three lines inside of the click method, not declare them as member variables of the anonymous class.
int sweight = Integer.parseInt(weight.getText().toString());
double sheight = Double.parseDouble(height.getText().toString());
int sage = Integer.parseInt(age.getText().toString());
#Override
public void onClick(View v) {
// Move them here
put this :
int sweight = Integer.parseInt(weight.getText().toString());
double sheight = Double.parseDouble(height.getText().toString());
int sage = Integer.parseInt(age.getText().toString());
in onclick method , before -> if (weight.equals(""))

How to deal with null EditText value in Android?

I'm developing an app for android, and currently the only thing it does is calculate grades. There's two input boxes, one that takes the current grade, and another that takes a possible exam grade, and then it tells you the final grade. However, when there is no value in at least one of those boxes, it crashes. I tried to make an if statement to detect if the final value was null, but that didn't work. Here's my code:
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText grade = (EditText) findViewById(R.id.grade1);
EditText exam = (EditText) findViewById(R.id.grade2);
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
double finalResult = (Double.parseDouble(stringGrade) * .8) + (Double.parseDouble(stringExam) * 0.2);
String finalResultString = String.valueOf(finalResult);
if (finalResultString == null){
finalResultString = "0";
} else {
intent.putExtra(EXTRA_MESSAGE, finalResultString);
startActivity(intent);
}}
and here's the code that renders it:
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView1 = new TextView(this);
textView1.setTextSize(30);
textView1.setText("Your final would be " + message);
setContentView(textView1);
Just for reference, the .8 and .2 is because the current grade is weighted at 80%, and the exam is weighted at 20%. How can I make it so it won't crash when nothing is put into the boxes?
usernameEditText.getText().toString(); would not return null. It will return an empty string. What you can do before calculating finalResult is to check stringGrade and stingExam are non-empty and numerical values and if one is not then stop the operation. i.e.
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
if (stringGrade.isEmpty() || stringExam.isEmpty()) {
Toast.makeText(this, "Invalid values", Toast.LENGTH_SHORT);
return;
}
try this:
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText grade = (EditText) findViewById(R.id.grade1);
EditText exam = (EditText) findViewById(R.id.grade2);
String stringGrade = (grade.getText().toString());
String stringExam = (exam.getText().toString());
if(stringGrade.equals("") ){
stringGrade = "0";
}
if(stringExam.equals("") ){
stringExam= "0";
}
double finalResult = (Double.parseDouble(stringGrade) * .8) + (Double.parseDouble(stringExam) * 0.2);
String finalResultString = String.valueOf(finalResult);
if (finalResultString == null){
finalResultString = "0";
} else {
intent.putExtra(EXTRA_MESSAGE, finalResultString);
startActivity(intent);
}}

How to calculate the sum of EditText boxes?

Hi all I am having a little trouble handling this question. I have 5 EditText boxes and I ask the user to put a number in them. Then I want to calculate the sum of the EditText boxes and do something with the sum. However I am having trouble in the case if the user don't put a number in all the boxes.
Is it possible to put a default value "0" in the boxes just in case not all the boxes are filled but the sum to be calculated although not all the boxes are filled?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_extra_question);
textBox1 = (EditText) findViewById(R.id.editText1);
textBox2 = (EditText) findViewById(R.id.editText2);
textBox3 = (EditText) findViewById(R.id.editText3);
textBox4 = (EditText) findViewById(R.id.editText4);
textBox5 = (EditText) findViewById(R.id.editText5);
buttON = (Button) findViewById(R.id.button1);
buttON.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
number1 = Integer.parseInt(textBox1.getText().toString());
number2 = Integer.parseInt(textBox2.getText().toString());
number3 = Integer.parseInt(textBox3.getText().toString());
number4 = Integer.parseInt(textBox4.getText().toString());
number5 = Integer.parseInt(textBox5.getText().toString());
sum = number1 + number2 + number3 + number4 + number5;
if(sum > 100)
{
Toast.makeText(getApplicationContext(), "Nice!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Fail!", Toast.LENGTH_LONG).show();
}
}
});
Do this for each number:
number1 = textBox1.getText().toString().trim().isEmpty()?0:Integer.parseInt(textBox1.getText().trim().toString());
Create on function like this
public int getIntFromString(String str) {
if (str != null) {
if (str.equalsIgnoreCase("")) {
return 0;
} else {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return 0;
}
}
} else {
return 0;
}
}
Then Your code should be
number1 = getIntFromString(textBox1.getText().toString().trim());
number2 = getIntFromString(textBox2.getText().toString().trim());
number3 = getIntFromString(textBox3.getText().toString().trim());
number4 = getIntFromString(textBox4.getText().toString().trim());
number5 = getIntFromString(textBox5.getText().toString().trim());
Yes your idea is correct. For each of the edit texts , just check:
if(textBox1.getText().toString().equals(""))
{
number1 = 0;
}
else
number1 = Integer.parseInt(textBox1.getText().toString());
You have to check Empty String using the below code and put "0" in every missing value.
number1 = textBox1.getText().toString().isEmpty()?0:Integer.parseInt(textBox1.getText().toString());
number2 = textBox2.getText().toString().isEmpty()?0:Integer.parseInt(textBox2.getText().toString());
number3 = textBox3.getText().toString().isEmpty()?0:Integer.parseInt(textBox3.getText().toString());
number4 = textBox4.getText().toString().isEmpty()?0:Integer.parseInt(textBox4.getText().toString());
number5 = textBox5.getText().toString().isEmpty()?0:Integer.parseInt(textBox5.getText().toString());

passing data from textview of activity 1 through textview of activity2

How to pass value of textview form one activity going to the other activity?
I have a scoring on my game that is shown on a textview and after it increment it will intent to the next activity. but the value of score from the first activity doesn't show on the textview of the second activity.
this is my code for my first activity
final TextView score2 = (TextView) findViewById(R.id.tvscore2);
Button page1 = (Button) findViewById(R.id.btnDog);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText etDog1 = (EditText) findViewById(R.id.etDog);
String Dog = etDog1.getText().toString();
if (Dog.equalsIgnoreCase("dog")) {
global.score += 10;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(view.getContext(),
sound1_3pig.class);
startActivityForResult(myIntent, 0);
} else if (global.score <= 0) {
global.score += 0;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
} else {
global.score -= 5;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
I want to display the result of the score activity 1 to the textview of the second activity
this is my second activity
final TextView score1 = (TextView) findViewById(R.id.tvscore1);
Button page1 = (Button) findViewById(R.id.btnCat);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText etCat = (EditText) findViewById(R.id.etCat);
String Cat = etCat.getText().toString();
if (Cat.equalsIgnoreCase("cat")) {
global.score += 10;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(view.getContext(),
sound1_3pig.class);
startActivityForResult(myIntent, 0);
finish();
} else if (global.score <= 0) {
global.score += 0;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
} else {
global.score -= 5;
score2.setText(String.valueOf(global.score));
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
As your second activity inflates a new layout, you need to explicitly pass your value from the first to the second activity and initialize it's TextView using this value.
Activity 1:
void goToSecondActivity() {
String value = mTextView.getText();
Intent in = new Intent(getActivity(), YourSecondClass.class);
in.putExtra("score", value);
startActivity(in);
}
Activity 2:
void onCreate(Bundle bundle) {
...
String score = getIntent().getStringExtra("score", "No score.");
mTextView.setText(score);
}
Use something like this.
Activity 1:
Intent i = new Intent(getActivity(), Activity2.class);
i.putExtra("Score", 20);
startActivity(i);
Activity 2:
Intent i = getIntent();
int score = i.getIntExtra("Score", 0);
My answer is also similar to what the others have suggested. try this, I have added some extra statements within your code(I presumed you want to send the value of variable score to the next activity, you can replace it with the variable you want to send) :
first activity:
score2.setText(String.valueOf(score));
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(this,
sound1_3pig.class);
myIntent.putExtra("Score", global.score);
startActivityForResult(myIntent, 0);
second activity:
put this in the onCreate() method of the second activity:
Intent intent = getIntent();
int score = intent.getIntExtra("Score",0);
so now you will get the value of score from the previous activity in the second activity. then you can set it in the textView you want to display it in by calling
textView.setText(score);

Categories

Resources