Button Print Toast When Clicked without answer Given - android

I have this button which calls two methods. See Code; Now i have tried to add a method on my onPictureSubmit(v) method which will print a Toast message (Please Submit Answer) if someone clicked the button without submitting an answer. Problem is it keeps crushing. Any help on how i can detect someone clicked the button without submitting answer will be appreciated.
My Button Code;
#Override
public void onClick(View v) {
switch (pass) {
case 0:
onDefinitionSubmit(v);
break;
case 1:
onPictureSubmit(v);
break;
case 2
break;
}
}
My Code :
private void onPictureSubmit(View v) {
if (v.getId() == R.id.picture_submit) {
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}

If I were you I'd declare the TextView, EditText, Button as a global variable, and then in your onCreate() I'd use the findViewById() to avoid NullPointerException.
Second, I'd check if the answerGiven (I guess is the answer) it's empty, so I'd create a method that returns me if it's empty or not the EditText.
public boolean isEtEmpty(String str){
if(str.isEmpty() || str.length() == 0 || str.equals("") || str == null){
return true;
}
else{
return false;
}
}
Then at the time you call onPictureSubmit() call this method doing this :
if (v.getId() == R.id.picture_submit) {
if (isEtEmpty(picture_answer.getText())){ //picture_answer is the EditText that you want to know if it's empty or not
Toast.makeText(v.getContext(), "Please Submit Answer",Toast.LENGTH_LONG).show();
}
else{
final int answerGiven = Integer.parseInt("" + ((EditText) findViewById(R.id.picture_answer)).getText());
final int answerKey = com.madonasystematixnote.mathhelper.lessons.PictureFragment.answer;
final int x = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_x)).getText());
final int y = Integer.parseInt("" + ((TextView) findViewById(R.id.picture_y)).getText());
}
}

Related

Calling on click listener multiple times for updating text views?

In my activity i am showing user a question and 3 options to choose from, these options are text-views.
On clicking the text-view On click listener is performed which updates the text-views according to the option selected.
Now user again after reading the question performs on click listener on options. But this is working only twice then it stops clicking and updating.
Debug is not working either i am beginner so i am confused.
#Override
public void onClick(View v) {
int id = v.getId();
if(id == R.id.optionA) {
Answer = optionA;
LogAnswer = "a : " + optionA;
Log.w(TAG, LogAnswer);
conditions(questionnumber);
}
else if (id == R.id.optionB) {
Answer = optionB;
LogAnswer = "b : " + optionB;
Log.w(TAG, LogAnswer);
conditions(questionnumber);
}
else if (id == R.id.optionC) {
Answer = optionC;
LogAnswer = "c : " + optionC;
Log.w(TAG, LogAnswer);
conditions(questionnumber);
}
}
conditions method change text-views according to option.
public void conditions(int i){
if(Answer.equals(optionA) && i == 1 )
{
questionnumber = 2;
MartialStatus = Single;
GetQuestion(2);
}
else if(Answer.equals(optionB) && i == 1 )
{
questionnumber = 2;
GetQuestion(2);
}
}
It may be that my text-view onclicklistener is calling same text-view listener which breaks.

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();
}

Simple Math Game?

I am new in Android and I would like to create simple Math quiz. I have a one textview that I display random question with random operator as below code.I would like, user will input their answer to EditText and submit their answer with ImageButton that I called submit answer. My question is, I could not handle to check user answer on Edittext via different method.How can I check user answer that evaluate the answer after submitbutton ?
public class MainActivity extends AppCompatActivity {
int number1, number2, result;
public EditText answer;
char operator;
ImageButton submitAnswer;
Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random rnd = new Random();
number1 = rnd.nextInt(100) + 1;
number2 = rnd.nextInt(100) + 1;
generateOperator();
TextView question = findViewById(R.id.questionText);
question.setText(number1 + " " + operator + " " + number2 + " " + "=" + " " + "?");
}
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1+number2;
} else if (op == 2) {
operator = '-';
result= number1-number2;
} else if (op == 3) {
operator = '*';
result = number1+number2;
}
return operator;
}
public void submitAnswer(View view) {
submitAnswer = findViewById(R.id.submitButton);
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( result == Integer.valueOf(answer.getText().toString())){
Toast.makeText(view.getContext(), "Correct",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(view.getContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
First of all, edir your generateOperator() method to keep answer.
public int generateOperator() {
int op = rand.nextInt(3) + 1;
if (op == 1) {
operator = '+';
result = number1 + number2;
} else if (op == 2) {
operator = '-';
result = number1 - number2;
} else if (op == 3) {
operator = '*';
result = number1 * number2;
}
return operator;
}
And then you can simply compare your result and the user's answer.
submitAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(result == Integer.valueOf(answer.getText().toString())){
//Answer is ok.
}
else {
//Some code...
}
}
});

A simple calculator

I'm new to Android. I'm trying to develop my first calculator. My calculator output is good, but I'm trying to make some changes to it. Please suggest. My output is 2+2=4.0 How can I get 4 if I put 2+2 and 4.0 when I put 2.8+1.2.
Also, please help me out in trying to figure out how can i keep on adding till i press =.
My code that I'm looking at is below:
private View.OnClickListener buttonClickListerner = new
View.OnClickListener() {
float r;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.clear:
screen.setText("");
operator.setText("");
FirstNum= 0;
showtext.setText("");
break;
case R.id.buttonAdd:
mMath("+");
operator.setText("+");
showtext.setText(String.valueOf(FirstNum));
break;
case R.id.buttonMinus:
mMath("-");
operator.setText("-");
break;
case R.id.buttonMul:
mMath("*");
operator.setText("*");
break;
case R.id.buttonequal:
mResult();
break;
case R.id.buttonDiv:
mMath("/");
operator.setText("/");
break;
case R.id.buttonPercent:
mMath("%");
r = FirstNum / 100;
showtext.setText("[" + String.valueOf(FirstNum) + "%" + "]");
screen.setText(String.valueOf(r));
break;
default:
String num = ((Button) v).getText().toString();
getKeyboard(num);
break;
}
}
};
public void mMath(String str){
FirstNum = Float.parseFloat(screen.getText().toString());
operation = str;
screen.setText("");
}
public void getKeyboard(String str){
String CurrentScreen = screen.getText().toString();
if(CurrentScreen.equals("0"))
CurrentScreen = "";
CurrentScreen = CurrentScreen + str;
screen.setText(CurrentScreen);
String ExScreen = CurrentScreen;
screen.setText(ExScreen);
}
public void mResult(){
float SecondNum = Float.parseFloat(screen.getText().toString());
float ThirdNum = Float.parseFloat(screen.getText().toString());
float result = 0;
//float exresult = result;
if(operation.equals("+")){
result = FirstNum + SecondNum;
// exresult = result + ThirdNum;
}
if(operation.equals("-")){
result = FirstNum - SecondNum;
//exresult = result - ThirdNum;
}
if(operation.equals("*")){
result = FirstNum * SecondNum;
//exresult = result * ThirdNum;
}
if(operation.equals("/")){
result = FirstNum / SecondNum;
//exresult = result / ThirdNum;
}
screen.setText(String.valueOf(result));
//screen.setText(String.valueOf(exresult));
showtext.setText(String.valueOf(FirstNum + operation + SecondNum));
//showtext.setText(String.valueOf(FirstNum + operation + SecondNum +
operation + ThirdNum));
}
}
I guess you should do your calculations as double and then before setting the output to TextView (or whatever you are using), check for the output if int or not and then decide which form of output to set to the TextView.
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integral type
}
See this
Edit:
The idea is to check that fractional part of the number is 0 (i.e.) the number is integer.
You may also Use these conditions [if true then variable is an Integer]
// check if
variable == Math.ceil(variable)
or
// check if
variable == Math.round(variable)
Also Math.round(float f) will return the interger form of the number!
To add multiple item first set up an array with a size of how long the user can input and then loop through each array adding them equivalently... i know this is a vague answer but you can ask me if anything is unclear and also an up vote would be nice. you got the right idea for the cases just try the following code
// array to sum
int[] numbers = new int[]{ 10, 10, 10, 10};
int sum = 0;
for (int i=0; i < numbers.length ; i++) {
sum = sum + numbers[i];
}
System.out.println("Sum value of array elements is : " + sum);
}

Check for Empty EditText fails

I've tried everything from matching strings, to using TextUtils.isEmpty. No matter what I do, b is always true (even when edittext is purposely left blank) which allows the code to proceed to the next steps (this is a Madlib app).
If anybody can see why the code isn't properly checking for blank edittext's and displaying the Please Fill In All Fields" toast when one is blank, it would be very appreciated. Thanks. Sorry for the messy code.
public class Madlibs extends Fragment {
switch (((MainActivity) getActivity()).getStory()) {
case 0:
output.setText(Stories[0]);
title = Titles[0];
actionBar.setTitle(title);
editTextNumber = 12;
addEdit = new BootstrapEditText[editTextNumber];
for (int i = 0; i < addEdit.length; i++) {
addEdit[i] = new BootstrapEditText(getActivity());
l_layout.addView(addEdit[i]);
params.setMargins(0, 20, 0, 20);
addEdit[i].setLayoutParams(params);
addEdit[i].setId(i);
}
addEdit[0].setHint("Name of Sickness");
addEdit[1].setHint("Adjective");
addEdit[2].setHint("Name of Boy");
addEdit[3].setHint("Body Part");
addEdit[4].setHint("Color");
addEdit[5].setHint("Animal");
addEdit[6].setHint("Article of Clothing");
addEdit[7].setHint("Relative");
addEdit[8].setHint("Adjective");
addEdit[9].setHint("Article of Clothing");
addEdit[10].setHint("Body Part");
addEdit[11].setHint("Number");
break;
case 1:
// fragment = new Madlibs();
break;
case 2:
// fragment = new MadlibsSaved();
}
convert = (BootstrapButton) view.findViewById(R.id.convert);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i;
String s;
for (i = 0; i < addEdit.length; i++) {
s = addEdit[i].getText().toString().trim();
if (s.isEmpty() || s.length() == 0 || s.equals("") || s == null) {
b = false;
}
else
{
b = true;
}
}
if (b = true) {
gather();
postIt();
outputText = output.getText().toString();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Please Fill In All Fields", Toast.LENGTH_LONG)
.show();
}
}
});
Your problem is here
if (b = true) { // HERE
gather();
postIt();
outputText = output.getText().toString();
}
You are using b = true which sets b to true, and since you are able to do this successfully, the conditional evaluates to true every time. What you want instead is the comparison operator ==
if (b == true) {
gather();
postIt();
outputText = output.getText().toString();
}
or even better, since the variable you are comparing is a boolean, you could just use
if (b) {} //This is "if b is true..."
if (!b) {} //This is "if b is false..."
You can see another one of my answers about this here.
for (i = 0; i < addEdit.length; i++) {
s = addEdit[i].getText().toString().trim();
if (s.isEmpty() || s.length() == 0 || s.equals("") || s == null) {
b = false;
}
else {
b = true;
}
}
For Loop ends here and the following is outside the For Loop :
if (b = true) {
gather();
postIt();
outputText = output.getText().toString();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Please Fill In All Fields", Toast.LENGTH_LONG)
.show();
}
Problem 1 :
if(b == true) {
}
Problem 2 :
Now, suppose edittext 1 is empty, b is set to true but then it'll straightaway move ahead in the loop to edittext 2 to the last edittext which are not empty hence it'll set b to false again. You'll need to put the check inside the for loop.

Categories

Resources