Add Double each time user clicks button on EditText - java

I am making a budget app and each time the user enters a new expense, I just append a TextView. I need to add each expense together, but I'm not sure how to do this on each click.
First, I thought to simply add all the numbers from the TextView, but I couldn't find a way to do this since they're all in just one TextView (as opposed to creating a new TextView on each click). So, I decided to simply parse the expense each time the user types it then add them together. But how can I add them after parsing in this way?
Thanks so much for the help
addExpenseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//TODO: Transfer this info to line in scroll view showing expenses
if (TextUtils.isEmpty(enterExpensesEditText.getText()) || TextUtils.isEmpty(enterExpensesNamesEditText.getText())) {
Toast.makeText(Expenses.this, "Expense Amount or Name Empty", Toast.LENGTH_SHORT).show();
} else {
String income = enterExpensesEditText.getText().toString() + "\n";
String incomeName = enterExpensesNamesEditText.getText().toString() + "\n";
expenseAmountTextView.append(income);
expenseNameTextView.append(incomeName);
//parse income to double in order to add it and later feed to EverydayBudget
totalIncome = Double.parseDouble(income);
}
enterExpensesNamesEditText.setText("");
enterExpensesEditText.setText("");
}
});

You parse only the current expense : totalIncome = Double.parseDouble(income);
maybe replace by totalIncome += Double.parseDouble(income);
Sorry guys but i don't understand your question where is the problem ? you append your textview when you have a new expense no ?
And why not use a ListView rather TextView ?

Related

Button1 and then Button2 when click it will generate one "letter or character" - Android

If the title is still a bit confusing what I really mean is that "when I click the button 1 followed by button 2 (with a bit time interval) it will generate a "letter" or "character" depending what values you coded on it it will input in textbox.
Please help I need this to complete my android application. I am having hard time dealing with this one.
My Code:
<Button
android:id="#+id/block1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="A"
android:textSize="16sp" />
inside my onCreate()
Button A = (Button) findViewById(R.id.block1);
Button B = (Button) findViewById(R.id.block2);
then setOnClickListener
A.setOnClickListener(this);
B.setOnClickListener(this);
inside my onClick() method and I did declare a global variable. String letter;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.block1:
letter += "A";
tts.speak("A.", TextToSpeech.QUEUE_FLUSH, null);
break;
case R.id.block2:
letter += "B";
tts.speak("B.", TextToSpeech.QUEUE_FLUSH, null);
break;
.
.
just like that..
Please do tell me what I am missing or what is needed to revised. Please do correct me If I'm wrong.. That is already a working program, but as I said earlier that I want a **"one click after another" then it will generate a single "variable/character" in the textbox.
EDITED:
I will write a simple answer based on what I understand of what you are asking...
I suggest you add a variable,
boolean aPressed = false;
Then in the click listener for A change the variable to true, Start a timer and then have an if statement in your B button's click listener testing if A was clicked from the variable aPressed. Afterwards stop the timer, see if the time taken meets what you want and put the text inside the text box as you wish.
I will not go into greater detail as it is unclear of what you are asking and I am surprised this hasn't been closed.
Hope I helped,
-Daniel
The following is simple logic, not exact code that will work.
// Replace "String" with the correct type to suit the task
private String mButOneValue = "";
private void twoClickAction(String valueOne, String valueTwo) {
... perform the action here using the passed fields ...
}
// This would be your current switch statement maybe. This
// prevents a long method with possible code duplication.
private String getValueOfClick(View v) {
... extract the "value" you want to track ...
return theValueYouWorkedOut;
}
#Override
public void onClick(View v) {
if (mButOneValue.equals("")) {
// capture the first value you want to track.
mButOneValue = getValueOfClick(v);
} else {
// first click value is known, get the second and
// and perform the action you want.
twoClickAction(mButOneValue, getValueOfClick(v));
// And be sure to clear the value first value.
mButOneValue = "";
}
}

How to display calculations result in a hinted TextView in Android Studio/Java?

I am trying to create a simple converter that will convert the amount given in dollars to euros.
This is my component tree:
id: button - onClick: convert
id: input - EditText
id: output - TextView
My output field (which its id is "output" as well) is a TextView because I don't want the user to be able to write in it. Unless I figure out a way to reverse the calculations which at this time I do not know how to do.
My question is how to display euroamount - which is the result of calculations - in the TextView field - which its id is "output"?
This is my code:
public void convert (View view){
EditText input = (EditText) findViewById(R.id.input);
Double usdamount = Double.parseDouble(input.getText().toString());
Double euroamount = usdamount * 0.88;
Log.i("input",input.getText().toString());
Log.i("output",euroamount.toString());
}
Thank you very much!
PS: I am a beginner so extensive explanation is appreciated!
You can do the following:
TextView output = (TextView) findViewById(R.id.output);
output.setText(euroamount.toString());

I am creating an android app and I want multiple people to have access to the same number and be able to change that number with two buttons

I am creating an app where people report whether or not they have the flu that week. I already have the code that allows me to be able to add to the number of people who do have the flu and the number of people who don't have the flu by pressing buttons. It then creates a percentage of people who have the flu based on that data. But whenever I close out of the app, all of the data goes away. The same data also won't be able to be accessed by the other people with the app.
Here is the code for the app.
public void fluButton()
{
Button hasFluButton = (Button)findViewById(R.id.fluButton);
hasFluButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
TextView t1 = (TextView)findViewById(R.id.influenzaPercent);
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(2);
numPeopleWFlu += 1;
percentFlu = ((double)numPeopleWFlu) / (numPeopleWOFlu + numPeopleWFlu);
String percent = defaultFormat.format(percentFlu);
t1.setText(percent + " of people have had the flu this week.");
}
}
);
}
public void noFluButton()
{
Button hasNoFluButton = (Button)findViewById(R.id.noFluButton);
hasNoFluButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
TextView t1 = (TextView)findViewById(R.id.influenzaPercent);
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(2);
numPeopleWOFlu += 1;
percentFlu = ((double)numPeopleWFlu) / (numPeopleWOFlu + numPeopleWFlu);
String percent = defaultFormat.format(percentFlu);
t1.setText(percent + " of people have had the flu in missouri this year.");
}
}
);
}`.
This answer will only provide you with a very vague solution as your question is broad.
Here's what you need to do, you need to rent a server and put all the data to that server.
Why do you need a server? Because you want lots of people to access the data as the same time. If you save the data to your app's SharedPreferences or something local, other people won't be able to get it.
So now you have a server, in your app, you retrieve the data from the server at the start of your app. There are lots of external libraries out there that can help you fetch something from the internet.
After you retrieved the data, you display it in some views and BOOM! You did the first part. The second part is to save the data to the server. When the user taps on a button or something, you save the data.
Sounds easy, huh?

EditText field not appending text

I am fairly new to Android. I am making a very simply calculator.
For the Plus button I've written code to getText from the editText field store it in an array index for later addition and then show the + sign to be appended so the user can see the operation.
But for the code posted below, everything else executes except it doesn't show the + sign appended to the EditText view.
button_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(lower_textfield.length() == 0)
{
Toast.makeText(getApplicationContext(), "Write a number to add first",
Toast.LENGTH_SHORT).show();
}
else
{
tmp = lower_textfield.getText().toString();
arr[0] = Integer.parseInt(tmp);
lower_textfield.append("+");
}
}
});
Here tmp is String and arr is Int Array.
Help would be appreciated.
The method
append()
on the EditText object should must work.
Check the inputType of the EditText object.
May be mistakenly you've written any numeric inputType like.
android:inputType="numberDecimal"
It should be
android:inputType="none"
OR
android:inputType="text"
First of all, make sure you're running on the GUI thread. Never touch GUI from a non-GUI thread.
If that isn't the problem, try this instead:
tmp = lower_textfield.getText().toString();
arr[0] = Integer.parseInt(tmp);
lower_textfield.setText(arr[0] + "+");

Another Android Activity or an iterative JAVA method?

I am new to Android application development and am trying to find a way to proceed through a series of screens that take in user input. I'm making a small math game where the user would answer basic two integer addition problems. So far the main menu is created. It has a New Game button which launches my GameActivity and it runs just fine for one math problem. However, after the user inputs their answer to the simple math problem, I would like to be able to continue on to another math problem once the user had answered the current problem and the method would return a correct/incorrect value. Initially I thought of doing something like a basic FOR loop from within the GameActivity :
for(int i = 0; i < 10; i++){ gameMethod(); }
gameMethod() is a JAVA method that simply generates 2 random numbers, adds them to get the correct answer and then prompts the user using an EditText field to type in their guess. It displays the random numbers and answer using TextView boxes created in an XML layout file.
Each call to the gameMethod would, at least I think, just re-input the randomized numbers into the TextView fields displayed on the screen each iteration. I really don't care what the previous numbers were so I figured I would just overwrite them. I wan't able to get the code to do that though. I put in a Log.d() statement or two and found that the FOR loop was in fact running through correctly 10 times, but it was not waiting for user input before firing off its next gameMethod().
In doing some looking around, I found the startActivityForResult() and wondered if this was a more appropriate way of approaching this. So in this way, I foresee having three Activities, the Main menu which calls the GameActivity which would then iterate through, say 10 times, each iteration calling yet another activity GameScreenActivity which would actually put the numbers on the screen, read in user input and then return 1 for a correct answer and 0 for an incorrect answer. So far in reading up on StarActivityForResult() I'm getting somewhat confused by the process and wondered if this was even a plausible path to be exploring.
Again, I'm very new at this Android programming and appreciate any and all help that I can get.
Thank you.
Sorry for not including the gameMethod() initially, I've added it below.
// Create and initialize arrays of integers
int[] a = {0,1,2,3,4,5,6,7,8,9,10};
int[] b = {0,1,2,3,4,5,6,7,8,9,10};
// Creates random number generator
Random randy = new Random();
// Generates two random values to add
int r1 = randy.nextInt(10);
int r2 = randy.nextInt(10);
// Calculates correct answer
int an = a[r1] + a[r2];
// Displays 1st number
TextView number1 = (TextView) findViewById(R.id.firstNumber);
number1.setText(Integer.toString(a[r1]));
// Displays 2nd number
TextView number2 = (TextView) findViewById(R.id.secondNumber);
number2.setText(Integer.toString(b[r2]));
// Displays correct answer
TextView answer1 = (TextView) findViewById(R.id.answerNumber);
//hide answer until user puts in theirs
answer1.setVisibility(View.INVISIBLE);
answer1.setText(Integer.toString(an));
//hide the answer place holder value
TextView uAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber);
uAnswerDisplay.setVisibility(View.INVISIBLE);
//Get the EditText field that the user will input their answer to
EditText inputText = (EditText) findViewById(R.id.userInput);
//set up a listener to run once the ENTER key is hit after their answer has been entered
inputText.setOnKeyListener(new EditText.OnKeyListener(){
public boolean onKey(View v, int keyCode, KeyEvent event){
//only go on the ENTER key when pressed DOWN
if((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)){
EditText innerInputText = (EditText) findViewById(R.id.userInput); //get the EditText box reference
TextView innerUAnswerDisplay = (TextView) findViewById(R.id.userAnswerNumber); //get the TextView box that the answer will go in
String inputString = innerInputText.getText().toString(); //capture the user's input
int uAnswer = Integer.parseInt(inputString); //parse user answer to an integer
int cAnswer = Integer.parseInt((((TextView) findViewById(R.id.answerNumber)).getText()).toString());
innerUAnswerDisplay.setText(Integer.toString(uAnswer)); //display the string after converting from integer
//change colors of text based on correctness
if (uAnswer == cAnswer){ innerUAnswerDisplay.setTextColor(Color.GREEN); } //green for correct
else { innerUAnswerDisplay.setTextColor(Color.RED); } //red for incorrect
innerUAnswerDisplay.setVisibility(View.VISIBLE); //make the user input answer visible
TextView innerAnswer1 = (TextView) findViewById(R.id.answerNumber);
innerAnswer1.setVisibility(View.VISIBLE); //hide answer until user puts in theirs
} //end of if
return false; //return false
} //end of onKey
}); //end of setOnKeyListener
Sorry for all the edits, I couldn't get the edits to include the code and post correctly so I broke it up into chunks and added a little at a time.
From what you say, I'd consider two ways of letting the user answer questions:
have an onclick listener on the input EditText that triggers a new loop;
have a dialog activity that gets started in the beginning of the loop, which prompts the user for a new answer, your game activity would receive the answer via its onActivityResult.

Categories