I am a total beginner, I am wondering if anyone could help me out with the code. I am trying to make ideal daily water intake apps.
There will be only one edit text for user to input their weight and I want it to divide for example 0.024. Have button to calculate and then display the answer on screen.
public class WaterCalculate extends Activity {
//Declare textviews as fields, so they can be accessed throughout the activity.
EditText weightuser;
TextView tv4;
ImageButton calculate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.water_calculate);
//Bind the EditText views
weightuser = (EditText)findViewById(R.id.weight);
tv4 = (TextView)findViewById(R.id.res);
calculate = (ImageButton)findViewById(R.id.calc);
calculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
calculate();
}
});
}
private void calculate() {
//get entered texts from the edittexts,and convert to integers.
Double value1 = Double.parseDouble(weightuser.getText().toString());
//do the calculation
Double calculatedValue = (value1/0.024);
//set the value to the textview, to display on screen.
tv4.setText(String.valueOf("You need " + calculatedValue + "\nliters of water per day" ));
}
}
When i run the apps the button to calculate its not working and it show the app has stopped. Appreciate for the help.
I thought the problem is in this line.
tv4.setText(String.valueOf("You need " + calculatedValue + "\nliters of water per day" ));
Give a try like this...
tv4.setText("You need "+Double.toString(calculatedValue)+"\nliters of water per day");
and also ensure that you catched the exceptions at necessary places like converting editText value into double.
Try the below code, am sure it will work, when you use click listener for button you should use View.Onclick
class WaterCalculate extends Activity {
// Declare textviews as fields, so they can be accessed throughout the
// activity.
EditText weightuser;
TextView tv4;
ImageButton calculate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.water_calculate);
// Bind the EditText views
weightuser = (EditText) findViewById(R.id.weight);
tv4 = (TextView) findViewById(R.id.res);
calculate = (ImageButton) findViewById(R.id.calc);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calculate();
}
});
}
private void calculate() {
// get entered texts from the edittexts,and convert to integers.
Double value1 = Double.parseDouble(weightuser.getText().toString());
// do the calculation
Double calculatedValue = (value1 / 0.024);
// set the value to the textview, to display on screen.
tv4.setText(String.valueOf("You need " + calculatedValue
+ "\nliters of water per day"));
}
}
Related
I want to make a quizscore calculating app. I have some problems. How to I prevent entering value greater than 20 inside the edittext and if the edittext is empty, write 0 inside the edittext and calculate the 0 value. When the application runs, it calculates the score, but when the Edittext is entered null, the application closes. I want to if edittext is null, app sets the null value 0 and calculate score.
Here's the image my app:1: https://i.stack.imgur.com/efn9H.png
Here's the code I'm using:
public class MainActivity extends AppCompatActivity {
EditText editText1,editText2,editText3;
private Button calculate;
TextView textView1;
double c=0.0,x;
int a=0,b=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1=findViewById(R.id.correct_answer);
editText2=findViewById(R.id.false_answer);
editText3=findViewById(R.id.turnet);
textView1=findViewById(R.id.hesap);
calculate=findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a=Integer.parseInt(editText1.getText().toString());
b=Integer.parseInt(editText2.getText().toString());
x=a+b;
if (x<=20){
if (editText1.getText().toString().length()==0)
{
a=0;
Toast.makeText(getApplicationContext(),"Correct Answers must be max:20 .", Toast.LENGTH_LONG).show();
}
else{
a=Integer.parseInt(editText1.getText().toString());
}
if (editText2.getText().toString().length()==0)
{
Toast.makeText(getApplicationContext(),"False Answers must be max:20.", Toast.LENGTH_LONG).show();
b=0;
editText2.setText(0);
}
double c = a - (b / 3);
double result=((200.004394)+(c*3.44603333));
editText3.setText(Double.toString(c));
textView1.setText("Your Score: "+ Double.toString(result));
}
else{
Toast.makeText(getApplicationContext(),"All English questions dont greater than 20.", Toast.LENGTH_LONG).show();
}
};});}}
There is a problem with this code :
a=Integer.parseInt(editText1.getText().toString());
b=Integer.parseInt(editText2.getText().toString());
when one of your edittextes is empty, then an error will be thrown because Integer.parseInt cannot accept an empty string.
so use this:
a = 0;
b = 0;
if (editText1.getText().toString() != ""){
a=Integer.parseInt(editText1.getText().toString());
}
if(editText2.getText().toString() != ""){
b=Integer.parseInt(editText2.getText().toString());
}
x = a + b
You can use TextWatcher. Write a TextWatcher which change value to 20 if it is greater than 20 or set it to 0 if EditText's text becomes empty
What i'm trying to do is quite simple. I want to generate random numbers(rand1 & rand2) and have the user give the correct answer of the sum. There are 2 buttons and the correct answer could be on either one. I am using the randDecider variable to determine whether or not the correct answer should show up on the first or second button. The randDecider is either a 1 or 2.
The issue I am having is sometimes when I click on the correct answer, The score doesn't increment. And it turns out that sometimes when I press the wrong answer, the score increments. So i'm assuming it's a 50/50 chance the score will increment regardless if the answer is correct or not.
protected void setRandom(View v) {
//Assigning random values to ints
rand1 = r.nextInt(5) + 1;
rand2 = r.nextInt(5) + 1;
randDecider = r.nextInt(2)+1 ;
//The sum of the randoms
sum = rand1 + rand2;
//Setting the texts of the random values
randTV1.setText(rand1 + "");
randTV2.setText(rand2 + "");
/*If the random deciding number is 1, set the correct answer
on the choice1 button*/
if (randDecider == 1){
choice1.setText(sum+"");
choice2.setText(sum+1+"");
//If the correct answer was chosen, increment the score and set the text
if(v.getId()==R.id.choice1){
score++;
scoreTV.setText(score+"");
}
}
/*If the random deciding number is 2, set the correct answer
to the choice2 button*/
if (randDecider == 2){
choice1.setText(sum+1+"");
choice2.setText(sum+"");
//If the correct answer was chosen, increment the score and set the text
if(v.getId()==R.id.choice2){
score++;
scoreTV.setText(score+"");
}
}
I'd suggest splitting the two distinct functions a) creating and presenting the problem to be solved and b) checking the response and then c) introducing a class variable to store the answer until another problem is presented (which would be after responding b) ).
So you could
a) add a line in the class
int correctanswer;
b) Add a method for setting the problem e.g. setProblem (called initially and then within c))
c) Add a method for checking the response e.g. setResponse which calls the setProblem method when the score has been adjusted. The setResponse method being called when either button is clicked.
d) add a call to initially invoke the setProblem.
e) set the 2 onclick listeners to call the setResponse method.
The following could be a resolution (based upon your question) :-
public class MainActivity extends AppCompatActivity {
int score, correctanswer;
TextView scoreTV, randTV1, randTV2;
Button choice1, choice2;
Random r = new Random(System.currentTimeMillis());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get UI components
scoreTV = (TextView) this.findViewById(R.id.score);
randTV1 = (TextView) this.findViewById(R.id.rand1);
randTV2 = (TextView) this.findViewById(R.id.rand2);
choice1 = (Button) this.findViewById(R.id.choice1);
choice2 = (Button) this.findViewById(R.id.choice2);
// Initialise
score = 0;
scoreTV.setText(Integer.toString(score));
setProblem();
// Button Listeners
choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
}
});
choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button) v);
}
});
}
// Set the problem
public void setProblem() {
//Assigning random values to ints
int rand1 = r.nextInt(5) + 1;
int rand2 = r.nextInt(5) + 1;
int randDecider = r.nextInt(2)+1 ;
//The sum of the randoms
int sum = rand1 + rand2;
correctanswer = sum;
//Setting the texts of the random values
randTV1.setText(rand1 + "");
randTV2.setText(rand2 + "");
/*If the random deciding number is 1, set the correct answer
on the choice1 button*/
if (randDecider == 1){
choice1.setText(sum+"");
choice2.setText(sum+1+"");
} else {
choice2.setText(sum+"");
choice1.setText(sum+1+"");
}
}
// Check the user's response (called by onClick listeners)
public void checkResponse(Button v) {
if ((new Integer(v.getText().toString()) == correctanswer)) {
score++;
scoreTV.setText(score+"");
}
setProblem();
}
}
At the top of your method, you have several lines which generate the random numbers and the decider. These are correct.
Then, you show the random numbers and place the answers on the correct buttons, which is presumably also correct.
However, at the same time, you check whether the correct button is selected. This means you're checking against the last button the user pressed, not their answer.
One way to fix this is to save the sum and correct answer positions for at least one rotation. Change your setRandom method to generate the numbers and set them to the screen as they are now, but also to save the correct answer to an outside variable.
Then, in the button's onPressed method, check whether the pressed button is correct, increment the score, and call setRandom to put a new question on the screen.
The problem in your code stems from the fact that you check the answer right as you put the question on screen. Happy programming!
I'm trying to build basic calculator, but when I put a number at first edittext and hit add button, it gets crashed.
It is fine when I add two number in both editTexts. There was no problem in that. But the problem happened when I put only one number and hit add.
It is throwing NumberFormatException: Invalid int: "".
here is my basic code.
public class MainActivity extends AppCompatActivity {
EditText num1;
EditText num2;
Button add,sub,multi,div;
TextView MyResults;
String Number1 ;//;
String Number2 ;//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText)findViewById(R.id.num1);
num2 = (EditText)findViewById(R.id.num2);
add = (Button)findViewById(R.id.Add);
sub = (Button)findViewById(R.id.Sub);
multi = (Button)findViewById(R.id.Multiple);
div = (Button)findViewById(R.id.Divide);
MyResults = (TextView)findViewById(R.id.results);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Number1 =num1.getText().toString();
Number2 =num2.getText().toString();
int mAdd1 = Integer.valueOf(Number1);
int mAdd2 = Integer.valueOf(Number2);
int myAdd = mAdd1+mAdd2;
MyResults.setText(String.valueOf(myAdd));
Toast.makeText(getApplicationContext(), "Added: "+ myAdd, Toast.LENGTH_LONG).show();
}
});
}//end OnCreate.
When you leave an EditText empty
int mAdd2 = Integer.valueOf(Number2);
Will crash because a empty String is not a valid Integer (hence the NumberFormatException).
You could put it in a try/catch like this:
try {
Number1 =num1.getText().toString();
Number2 =num2.getText().toString();
int mAdd1 = Integer.valueOf(Number1);
int mAdd2 = Integer.valueOf(Number2);
MyResults.setText(String.valueOf(myAdd));
Toast.makeText(getApplicationContext(), "Added: "+ myAdd, Toast.LENGTH_LONG).show();
catch (NumberFormatException e) {
//Give a toast saying the user did not enter two correct values
}
Or alternatively, check the value beforehand and check if nothing was entered:
number1 =num1.getText().toString();
number2 =num2.getText().toString();
if (number1.equals("") || number2.equals("")) {
//Show error or set numbers to a different value
}
However, for this to work you must assume the user did not enter anything that isn't a valid Integer like a letter, for example by setting the EditText's input type to numbers.
android:inputType="number"
You should do validation checking for a blank edit text and not do the calculation in this case.
Instead you might take advantage of EditText's setError(CharSequence) method where you can show a message to the user why the input is not valid.
i try to make Multiple-calc operation in one click but when i click on button done its show error so how can i modification this code to be able to calc all of this operations in one click with out any errors . here is the code
public class calcit extends Activity {
EditText onehighx,twowightx,threefinallresultx,four100x,fiveresultof100x,sixresultofresultx;
Button donee;
BigDecimal onehigh,twowight,threefinallresult,four100,fiveresultof100,sixresultofresult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calcit);
donee = (Button) findViewById(R.id.button1);
onehighx = (EditText) findViewById(R.id.high);// high
twowightx = (EditText) findViewById(R.id.Weight);//Weight
threefinallresultx = (EditText) findViewById(R.id.finall_result);//result =Weight * result of result 100
four100x = (EditText) findViewById(R.id.e100);//100
fiveresultof100x = (EditText) findViewById(R.id.re_of_100);// result of 100 = high * 100
sixresultofresultx = (EditText) findViewById(R.id.result_of_100_100);// result of result 100 /ex : 1.75*1.75
donee.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onehigh = new BigDecimal(onehighx.getText().toString());
twowight= new BigDecimal(twowightx.getText().toString());
threefinallresult = new BigDecimal(threefinallresultx.getText().toString());
four100 = new BigDecimal(four100x.getText().toString());
fiveresultof100 = new BigDecimal(fiveresultof100x.getText().toString());
sixresultofresult = new BigDecimal(sixresultofresultx.getText().toString());
//---here i want to fix this code to be able to show all of this Multiple-calc operations in
//(threefinallresultx)------
fiveresultof100x.setText((onehigh).divide(four100).toString());
sixresultofresultx.setText((fiveresultof100).multiply(fiveresultof100).toString());
threefinallresultx.setText((twowight).divide(sixresultofresult).toString());
}
});
}
If I am not wrong you want to do calculations on values fetched from Edittexts but you are instead trying to divide or multiply setText boxes and not the values contained in them. So just fetch values in appropriate format and calculate them normally such as
onehigh=onehigh/four100;
fiveresultof100=fiveresultof100*fiveresultof100;
twowight=twowight/sixresultofresult;
and then set them in textboxes
fiveresultof100x.setText(onehigh);
ixresultofresultx.setText(fiveresultof100);
threefinallresultx.setText(twowight);
I want to grab Text when user click on the TextView
For Example :
TextView string = "this is a test for android and textView"
When user click on textview in android position grab android
Anyone have a solution for this ?
You can assign an onClick listener to the textview, make it final and then get its text.
final TextView txt = (TextView) findViewById(R.id.txt);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String getTxt = txt.getText().toString();
}
});
TextView text = (TextView) findViewById(R.id.yourTextViewId);
text.onClickListner(this);
#Override
public void onClick() {
String textOnTextView = text.getText().toString();
}
If you want to split lines and display them in different color then refer to following links.
Split text from string
Apply color to specific text
A button has onClick , I dont think that a TextView has onClick so that a user clicks it.
Correct me if i am wrong
If you want to select part of text, try to use EditText
This is not a solution for your need. But only one step to solution.
Use setTextIsSelectable(boolean) or the TextView_textIsSelectable XML attribute to make the TextView selectable (text is not selectable by default).
Using following code, I managed to get selected text as String. You need to first select string by dragging over it.
NB: you need minimum API 11 to use setTextIsSelectable(boolean)
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView) findViewById(R.id.textView1);
t1.setTextIsSelectable(true);// IMPORTANT
t1.setText("This is Android program");
t1.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_UP:
int start=t1.getSelectionStart();
int end=t1.getSelectionEnd();
String sub=t1.getText().subSequence(start, end).toString();
Toast.makeText(getBaseContext(), sub, 1).show();
}
return true;
}
});
}