Not able to display very large calculation value in editext - java

private TextView info;
private EditText input;
private Button getInfo;
long answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInfo = (Button) findViewById(R.id.button1);
getInfo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
input = (EditText) findViewById(R.id.editText1);
String s2 = input.getText().toString();
long inputNumber = Integer.parseInt(s2);
for (int i = 0; i <= inputNumber; i++) {
answer = fibonacci(i);
}
input.setText(answer + "");
}
});
}
public static long fibonacci(long n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
I made a program which generates fibonacci series for the number I give input through edit text and display the output value in edittext .Issue is when I enter 30 it generates fibonacci series but when I enter 50 or 100 app does not respond and stops .

I think it is because you have a lot of calculation on UI thread.
Try calculate it in AssyncTask, for example.

Related

How to randomly generate random operators in android studio

public class MainActivity extends AppCompatActivity {
Button startButton;
ArrayList<Integer> answers=new ArrayList<Integer>();
int LocationOfRightAnswer;
TextView resultTextView;
TextView pointText;
Button button1;
Button button2;
Button button3;
Button button4;
int score=0;
int numberofquestions = 0;
TextView sumText;
TextView timertext;
RelativeLayout game;
Button playAgain;
public void playAgain(View view) {
score = 0;
numberofquestions = 0 ;
timertext.setText("30s");
pointText.setText("0/0");
resultTextView.setText("");
playAgain.setVisibility(View.INVISIBLE);
generateQuestion();
new CountDownTimer(30100,1000) {
#Override
public void onTick(long millisUntilFinished) {
timertext.setText(String.valueOf(millisUntilFinished / 1000) + "s");
}
#Override
public void onFinish() {
playAgain.setVisibility(View.VISIBLE);
timertext.setText("0s");
resultTextView.setText("Your Score is " + Integer.toString(score) + "/" + Integer.toString(numberofquestions));
}
}.start();
}
public void generateQuestion() {
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
char[] ops = {'+' , '-' ,'*', '/'};
int l = random.nextInt(3) ;
sumText.setText(Integer.toString(a) + "+" + Integer.toString(b) );
LocationOfRightAnswer = random.nextInt(4);
answers.clear();
int incorrectAnswer;
for (int i=0; i<4; i++) {
if (i == LocationOfRightAnswer) {
answers.add(a + b);
}else {
incorrectAnswer = random.nextInt(41);
while (incorrectAnswer == a + b) {
incorrectAnswer = random.nextInt(41);
}
answers.add(incorrectAnswer);
}
}
button1.setText(Integer.toString(answers.get(0)));
button2.setText(Integer.toString(answers.get(1)));
button3.setText(Integer.toString(answers.get(2)));
button4.setText(Integer.toString(answers.get(3)));
}
public void chooseAnswer(View view) {
if (view.getTag().toString().equals(Integer.toString(LocationOfRightAnswer))) {
score++;
resultTextView.setText("Correct");
} else {
resultTextView.setText("Wrong!");
}
numberofquestions++;
pointText.setText(Integer.toString(score) + "/" + Integer.toString(numberofquestions));
generateQuestion();
}
public void start (View view) {
startButton.setVisibility(View.INVISIBLE);
game.setVisibility(View.VISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton =(Button) findViewById(R.id.startButton);
sumText = (TextView) findViewById(R.id.sumTextView);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
resultTextView = (TextView) findViewById(R.id.resultTextView);
pointText = (TextView) findViewById(R.id.pointsTextView);
timertext = (TextView) findViewById(R.id.timerTextView);
playAgain = (Button) findViewById(R.id.playAgain);
game = (RelativeLayout) findViewById(R.id.gamelayout) ;
playAgain(findViewById(R.id.playAgain));
}
}
please help me to adjust my code so that I the app can use all operators instead of just addition. I have tried to do it but I have only managed to create the array list for the operators but I could not find a way to change the code to include all of the operators.
Try this:
ArrayList<Double> answers=new ArrayList<Double>();
public void generateQuestion() {
Random random = new Random();
int a = random.nextInt(21);
int b = random.nextInt(21);
char[] ops = {'+' , '-' ,'*', '/'};
int l = random.nextInt(3) ;
char op = ops[random.nextInt(4)];
double correctAns=0;
switch(op){
case '+' : correctAns = a+b;
break;
case '/' : correctAns = (double)a/b;
break;
case '*' : correctAns = a*b;
break;
case '-' : correctAns = a-b;
break;
}
sumText.setText(Integer.toString(a) + op + Integer.toString(b) );
LocationOfRightAnswer = random.nextInt(4);
answers.clear();
int incorrectAnswer;
for (int i=0; i<4; i++) {
if (i == LocationOfRightAnswer) {
answers.add(correctAns);
}else {
incorrectAnswer = random.nextInt(41);
while (incorrectAnswer != correctAns) {
incorrectAnswer = random.nextInt(41);
}
answers.add((double)incorrectAnswer);
}
}
button1.setText(Double.toString(answers.get(0)));
button2.setText(Double.toString(answers.get(1)));
button3.setText(Double.toString(answers.get(2)));
button4.setText(Double.toString(answers.get(3)));
}
change ArrayList<Integer> answers=new ArrayList<Integer>(); to ArrayList<Double> answers=new ArrayList<Double>(); (int/int can be a double)
create a double variable contains the right answer (int/int can be a double)
choose an operation randomly.
use switch to define what operation is needed on a and bin case that every operation selected.
set the text to Integer.toString(a) + op + Integer.toString(b) instead of Integer.toString(a) + "+" + Integer.toString(b)
swap a+b to correctAns

How to make Toast pop up if EditText field is empty or the inputted value is equal to 0?

First of all, I'm new to Android Studio. I'm currently trying to make a BMI calculator app where the user has to enter their weight and height and select the unit of measurement used for both. A Toast message (R.string.toastError) should pop up upon clicking a button if: (1-2) the EditText fields for weight and height are empty and (3) if the value of HeightInput is less than or equal to zero; else, the calculation should proceed.
The whole math part worked fine when I tested it, but when I left the fields blank, the app just crashes. The Toast pops up though when HeightInput = 0, but not when the EditText field for Weight is left empty at the same time. I think it's the way I wrote the 'if' statement that's giving me a problem.
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
Here's the whole code for reference:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// weight units spinner
final Spinner spinWeightUnit = (Spinner) findViewById(R.id.spinnerWeightUnit);
spinWeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> WeightList = ArrayAdapter.createFromResource(this, R.array.WeightUnits, android.R.layout.simple_spinner_item);
WeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinWeightUnit.setAdapter(WeightList);
// height units spinner
final Spinner spinHeightUnit = (Spinner) findViewById(R.id.spinnerHeightUnit);
spinHeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> HeightList = ArrayAdapter.createFromResource(this, R.array.HeightUnits, android.R.layout.simple_spinner_item);
HeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinHeightUnit.setAdapter(HeightList);
// calculate button
Button buttonCalculate = (Button) findViewById(R.id.buttonCalculate);
buttonCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
// weight conversion constant
if (finalWeightUnit.equals("kilograms")) {
constantWeight = 1.00;
} else {
constantWeight = 1 / 2.204623;
}
// height conversion constant
switch (finalHeightUnit) {
case "inches":
constantHeight = 0.0254;
break;
case "centimeters":
constantHeight = 0.01;
break;
case "feet":
constantHeight = 1 / 3.2808;
break;
default:
constantHeight = 1.00;
break;
}
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
I'd appreciate any help! Thanks!
Try below in if statement
if (editTextWeightInput.getText().toString().trim().isEmpty() || editTextHeightInput.getText().toString().trim().isEmpty() || HeightInput <= 0)
When you leave an EditText Empty the getString() function returns a null value. First you need to check for null in the if condition.
if (editTextWeightInput.getText() == null || editTextWeightInput.getText().toString().length() == 0 || HeightInput <= 0)
You need to validate your declaration code also.
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
if(TextUtil.isEmpty(editTextWeightInput.getText().toString())||TextUtil.isEmpty(editTextHeightInput.getText().toString())){
Toast.makeText(getApplicationContext(), R.string.toastError,
Toast.LENGTH_SHORT).show();
}else{
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
}

How to count sum total in Java using Android Studio

I just learned Java using Android Studio.
My code error for use integer to count sum.
I try to decode string to integer but still error.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtvalue = (EditText) findViewById(R.id.value);
final Spinner edtjw = (Spinner) findViewById(R.id.spinner1);
txtpa = (TextView) findViewById(R.id.pa);
txttotal = (TextView) findViewById(R.id.total);
btncount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String value = edtvalue.getText().toString().trim();
String jw = edtjw.getSelectedItem().toString().trim();
double h = Double.parseDouble(value);
double j = Double.parseDouble(jw);
String numbertostring = String.format ("%.2f", (0.02*h));
String numbertostring2 = String.format ("%.2f", (0.025*h));
String numbertostring3 = String.format ("%.2f", (0.0275*h));
if (j == 1){
txtpa.setText(numbertostring);
} else if (j ==2){
txtpa.setText(numbertostring);
} else if (j ==3){
txtpa.setText(numbertostring);
} else if (j ==4){
txtpa.setText(numbertostring2);
} else if (j ==5){
txtpa.setText(numbertostring3);
} else {
txtpa.setText(0);
}
int tot = (h*j)+txtpa;
txttotal.setText("Total : " + tot);
}}
By looking at the code snippet, you should get string value from txtpa which is of type TextView, then parse it into double
double tot = (h*j)+Double.parseDouble(txtpa.getText().toString());
as mentioned in the above comment by Naitik Soni.

getting value in Interger array using for loop

I am new to programming and started android few week back.
public class MainActivity extends AppCompatActivity {
int a,i,j,k;
/*char [][] s1= new char[][]
{
{'A','B','C','D'},
{'E','F','G','H'},
{'I','J','K','L'},
{'M','N','O','P'},
{'Q','R','S','T'},
{'U','V','W','X'},
{' ','Y','Z',' '}};*/
char [][] s2=new char[8][8];
char[][] s3=new char[8][8];
int[] getlist= new int[10];;
char choice,choice1;
int x,b,c,d;
String[] messageText = new String[10];
String[] messageEdit = new String[10];
public void letterNo(View view) { // Method to show screen for getting number of letters
setContentView(R.layout.displaylettersno);
}
public void getNumber(View view) { // Method to get Numbers of Letter
EditText et = (EditText) findViewById(R.id.editText);
String s = et.getText().toString();
x = Integer.parseInt(s);
if (x > 0 && x < 9) {
et.setText("");
} else {
Toast.makeText(getApplicationContext(), "Wrong Entery... Enter again", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.gettingcolumnno);
// Toast.makeText(getApplicationContext(),"Click on Column No in Which 1st Letter Appear",Toast.LENGTH_LONG).show();
TextView textView = (TextView) findViewById(R.id.textView8);
for (i = 0; i < x; i++){
textView.setText("Enter Column No. in which Your letters of name is
present:" );
}
}
public void buttondone(View view) {
EditText op = (EditText) findViewById(R.id.operator2);
String num = op.getText().toString();
for (i = 0; i < x; i++)
{
getlist[i] = Integer.parseInt(String.valueOf(op.getText()));
}
Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
I want to develop a Name guess game
1- it will ask user to enter the no. of letters he thought
2- it will ask user to enter the column no in which his letter present ( i want this to run according to user enter the no of letter .
suppose user enter 4 digits and it will ask to enter the column no 4 times.
and similarly it has a edit box where user enter column no .
i am using for loop for this purpose but it only show 1 time i am stuck here for 1 week . help me if you understand what i am trying to do . following is my code
Done button has to be pressed number of letters time to get columns.
TextView textView = (TextView) findViewById(R.id.textView8);
int numberOfColumnsEntered = 0;
public void getNumber(View view) {
// get number logic then
textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
}
public void buttondone(View view) {
EditText op = (EditText) findViewById(R.id.operator2);
String num = op.getText().toString();
getlist[numberofColumnsEntered] = Integer.parseInt(num);
numberofColumnsEntered++;
textView.setText("Enter Column No. "+(numberOfColumnsEntered+1)+" in which your letters appear");
if(numberofColumnsEntered == x) {
Toast.makeText(getApplicationContext(), "Inserted", Toast.LENGTH_LONG).show();
}
}

Button in Java eclipse

I made a program that computes the geometric mean and my program is already working but i have some sort of errors. Whenever i click the btnCalculate with an empty input in my inputValues my program stops working. how am I going to deal with this error? Thanks:)
final AutoCompleteTextView inputValues = (AutoCompleteTextView) findViewById(R.id.txt_input);
final TextView txtTotalNum = (TextView) findViewById(R.id.txt_totalNumber);
final TextView GeoMean= (TextView) findViewById(R.id.txt_GeoMean);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
});
Button btnclear = (Button)findViewById(R.id.btnclear);
btnclear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
inputValues.setText("");
txtTotalNum.setText("");
GeoMean.setText("");
}
You are getting errors because your code is trying to split on empty strings or null and then accessing values[] that really have no index at all. Just check if the string fetched by the EditText has a length>0.
#Override
public void onClick(View agr0) {
String fetchedValues = ( inputValues.getText().toString());
if(fetchedValues.length>0)
{
String []values = fetchedValues.split(",");
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
else
{
//alert the user that the field is empty
}
}
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
if(values !=NULL){
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
// try this
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
if(inputValues.getText().toString().length()>0){
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
});
Your program stops at
convertedValues[a] =Integer.parseInt(values[a]);
because for an empty input the split array has no values, so its length is 0. And when you try to access values[0]you get an ArrayIndexOutOfBoundsException.
Just check if the input is emty, before splitting it.
if(!inputValues.getText().toString().equals("")){
... // do your stuff
} else {
// show a message
}

Categories