Coding a calculator - android

I'm just a beginner in coding using Android studio and I have a couple of questions in coding a calculator (The calculator is used to only compute carbon emissions so it varies a little bit compared to an actual calculator):
How do I have a clear all button?
How do I add all of the
products that the user has calculated and show its sum? (Kind of like
how those tracking expenses kind of app)
This is my code so far:
package com.carschoolingpromo.scires.carschooling;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
Button caremissionscheck = findViewById(R.id.checkcar);
caremissionscheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent tocarbonemissions = new Intent(Calculator.this, CarbonEmissions.class);
startActivity(tocarbonemissions);
}
});
Button distancecheck = findViewById(R.id.checkdestination);
distancecheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent checkdistance = new Intent(Calculator.this, DistancesList.class);
startActivity(checkdistance);
}
});
final Button multiply =(Button)findViewById(R.id.multiply);
final EditText num1 =(EditText)findViewById(R.id.carboninput);
final EditText num2 =(EditText)findViewById(R.id.distanceinput);
final TextView ans =(TextView)findViewById(R.id.answer);
final TextView carbontotal=(TextView)findViewById(R.id.sumofcarbon);
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double n1 = Double.parseDouble(num1.getText().toString());
double n2 = Double.parseDouble(num2.getText().toString());
ans.setText(String.valueOf(n1*n2));
}
});
}
}

How do I have a clear all button?
You need to create a new button in the layout file, and get a reference of it in your code, then set a click listener on that reference. Then in the onClick() implementation you will clear your 2 edit texts and 2 text views, something like this:
final Button clearAll =(Button)findViewById(R.id.clear_all);
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1.setText("");
num2.setText("");
ans.setText("");
carbontotal.setText("");
}
});
How do I add all of the products that the user has calculated and show its sum? (Kind of like how those tracking expenses kind of app)
For this you need to use some sort of a way to show a list on your UI, I suggest you look into this tutorial by google to creating lists

Related

Android Studio Unable to Start Activity, Cannot cast to android.view.View$OnClickListener

We are working on creating a basic app in my online class and I keep running into this issue where the Instructions have us type a method with an #Override for an onClick. I was able to get one of the methods to work with an autofill help from A.S. itself but this next one won't fix itself out. I have run into other issues over this class as well and I know the Instructions are a few years old. Possibly out of date now?
I'm pretty new to Android Java and coding overall. It seems that the app is trying to use the onClick method incorrectly. I will post the whole class I'm working with because I'm not sure where the problem is exactly.
package com.test.firstandroidapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
public class InformationPageActivity extends AppCompatActivity {
Button btnSave;
Spinner spnSeason;
SeekBar skbTemp;
TextView lblSeekValue;
Switch swchAllergy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information_page);
spnSeason = (Spinner) findViewById(R.id.spnSeason);
skbTemp = (SeekBar) findViewById(R.id.skbTemp);
swchAllergy = (Switch) findViewById(R.id.swchAllergy);
lblSeekValue = (TextView) findViewById(R.id.lblSeekValue);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener((View.OnClickListener) this);
skbTemp.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String display = String.valueOf(progress);
lblSeekValue.setText(display);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public void onClick(View v) {
String season, allergies;
int temperature;
season = spnSeason.getSelectedItem().toString();
temperature=skbTemp.getProgress();
allergies = (String) (swchAllergy.isChecked() ? swchAllergy.getTextOn() : swchAllergy.getTextOff()); //if the switch is on then the user has allergies
Intent intent = new Intent(InformationPageActivity.this, InformationResultsActivity.class); //pass information to the results activity
intent.putExtra("season", season);
intent.putExtra("temperature", temperature);
intent.putExtra("allergies", allergies);
this.startActivity(intent);
}
}
And here is the Main Menu Class parts that go to the view i'm trying to have opened, The onclicklistener is inside the onCreate method and the goInfo is it's own method
Button btnInfo = (Button) findViewById(R.id.btnInfo);
btnInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goInfo();
}
}
);
}
private void goInfo() {
Intent intent = new Intent(MainMenuActivity.this, InformationPageActivity.class);
this.startActivity(intent);
}
I was able to find the issue. I needed to add an implements statement to the class for the onclicklistener. I'm answering my own question in case someone in the future has the same error. Here is what I did.
My problematic class was
public class InformationPageActivity extends AppCompatActivity {
This was causing the error "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.firstandroidapp/com.test.firstandroidapp.InformationPageActivity}: java.lang.ClassCastException: com.test.firstandroidapp.InformationPageActivity cannot be cast to android.view.View$OnClickListener"
I solved the issue by fixing the class adding the implements
public class InformationPageActivity extends AppCompatActivity implements View.OnClickListener {

Custom Dialog Window/Pop up window keeps rejecting button input?? Android Studio

So I created a pop-up dialog window to serve as the tutorial for the user, I decided to run tests on it since it was working well but saw that when you added an active button to it, it would not work. Each time I pressed the button that brings up the tutorial(which worked before the addition of the button code), the addition I made with the button taking the user to another part now renders that button inactive and instead takes the user back to the start screen when the tutorial button is pressed.
This is the code I used for it:
package com.example.rockpaperscissors;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import static com.example.rockpaperscissors.R.id.tutorialButton;
public class MainMenu extends AppCompatActivity {
Button tutorialButton, playGameButton, testbutton;
Dialog tutorial_popup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tutorial_popup = new Dialog(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.activity_main_menu);
playGameButton = findViewById(R.id.playGameButton);
tutorialButton = findViewById(R.id.tutorialButton);
testbutton = findViewById(R.id.testbutton);
tutorial_popup = new Dialog(this);
playGameButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainMenu.this, MainGame.class));
}
});
tutorialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tutorial_popup.setContentView(R.layout.tutorial_popup);
tutorial_popup.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
tutorial_popup.show();
testbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainMenu.this, MainGame.class));
}
});
}
});
}
}
As you can see, there's another setOnClickListener within the tutorial which is basically supposed to take the user to another class/activity when pressed on. However, it does not do it and instead just ignores it, showing that there is an error.
tutorialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tutorial_popup.setContentView(R.layout.tutorial_popup);
tutorial_popup.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
tutorial_popup.show();
testbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainMenu.this, MainGame.class));
}
});
}
});
Is there something I missed when doing this? Please let me know how I can fix this.
Try setting the onclick on the button before showing the pop up
testbutton.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) {startActivity(new Intent(MainMenu.this, MainGame.class));}}); tutorial_popup.show();
So I found a solution to this answer, being that there was actually no need to add a buttonListener to the pop-up dialog as not only was it unnecessary, but it was also breaking the code. With how pop-up dialogs work in Android Studio, I realised through watching videos that you are able to click off of it without needing an "X" button or whatsoever, so I removed the buttonListener and tried again. Safe to say it ran perfectly this time with no problems whatsoever.
tutorialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tutorial_popup.setContentView(R.layout.tutorial_popup);
tutorial_popup.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
tutorial_popup.show();
}
});

getText is not working in Android studio

package com.example.mediosa.mediosa;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import com.firebase.client.Firebase;
public class registerActivity extends AppCompatActivity {
private Button buttonSignIn, buttonRegister;
private EditText editTextUsername;
private EditText editTextEmail;
private EditText editTextPassword;
private EditText editTextDOB;
private EditText editTextName;
private RadioButton radioButtonMale, radioButtonFemale;
private Firebase rootRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
rootRef = new Firebase(FIREBASE_URL");
buttonSignIn = (Button)findViewById(R.id.buttonSignIn);
editTextDOB = (EditText)findViewById(R.id.editTextDOBReg);
editTextUsername = (EditText)findViewById(R.id.editTextUsernameReg);
editTextEmail = (EditText)findViewById(R.id.editTextEmailReg);
editTextPassword = (EditText)findViewById(R.id.editTextPasswordReg);
editTextName = (EditText)findViewById(R.id.editTextNameReg);
radioButtonFemale =(RadioButton)findViewById(R.id.radioButtonFemale);
radioButtonMale = (RadioButton)findViewById(R.id.radioButtonMale);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
buttonSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(registerActivity.this ,
LoginActivity.class));
}
});
final String Name = editTextName.getText().toString();
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(registerActivity.this, Name ,
Toast.LENGTH_SHORT).show();
}
});
}
}
I am new to Android and was working on a project.
In this code (Part of that project) in am unable to read data from user as name. The compiler shows no error And the code works correctly but when i try to show the data in the Name string using toast, it is completely blank.
I need this name and other field to store data in Firebase DB, but it was not working and i found out there was some problem in reading data.
Would be really great if anyone can help me, thanks.
The problem is that you are not updating the value of Name , meanwhile there is no need for a variable if you only want to display the text. Here is how you display the text.
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(registerActivity.this,
editTextName.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
Try putting getText() inside the OnClickListener:
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name = editTextName.getText().toString();
Toast.makeText(registerActivity.this, Name ,
Toast.LENGTH_SHORT).show();
}
});
This is because you call getText() inside onCreate(). see where it is placed. Thus when the Activity is being created, the text inside EditText is empty.

onClickListener not working that was copied from another working activity

I have created a new activity, added it to my manifest file and copy and pasted code from another fully functioning activity yet my buttons do not work when I click on them. Here is my activity:
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class test extends Activity {
private Button btnChangeDate;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.salesticketoilui);
mainProgram();
}
public void mainProgram() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
} // end onClick
}); // end setOnClickListener
Button buttonExit = (Button)findViewById(R.id.buttonExit);
buttonExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
exitActivity();
} // end onClick
}); // end OnClickListener
// setup button listener for saving data and exit to main
Button buttonSaveExit = (Button) findViewById(R.id.buttonSaveExit);
buttonSaveExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
saveExit();
} // end onClick
}); // end OnClickListener
} // end MainProgram ()
public void saveExit() {
// does stuff
}
public void exitActivity () {
// does stuff
}
} // end class
any thoughts?
Based on the code you have shown, it doesn't appear that you ever call the method mainProgram so your click listeners will never actually get setup. Either call mainProgram from onCreate or just put that code directly into onCreate.
I believe the onClickListeners need to go inside of your onCreate method.
Listen to Scott
and looks like your missing the #Override
new View.OnClickListener() {
#Override
public void onClick(View view) {
exitActivity();
} // end onClick
}
Make sure your java settings are to 1.6 to avoid code completion missing this.
I had the same problem copying OnClickListener with ImageButtons from a class to another class, and renaming then with bulk copy/paste.
To make it work, I had to create new buttons in my layout and declare the events manually. Weird!

How can I keep my Java Android code short?

Hi I am developing an Android app using an EditText, and a add en minus button to control it's value.
I got it working now, but I wanna repeat it to multiple values. I know I can just repeat the code with different variables but the code would big really large.
Anyone an idea how to repeat the same code for multiple values?
This is my current code:
package com.lars.MyApp;
import com.lars.MyApp.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
import android.view.View.OnClickListener;
public class MyAppActivity extends Activity {
int currentValue = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText Value = (EditText) findViewById(R.id.Value);
Button addButton = (Button) findViewById(R.id.addButton);
Button minusButton = (Button) findViewById(R.id.minusButton);
addButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
addValue();
Value.setText("" + currentValue);
}
});
minusButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
minusValue();
Value.setText("" + currentValue);
}
});
}
public void addValue(){
if(currentValue <= 999){
currentValue = currentValue + 1;
}
}
public void minusValue(){
if(currentValue >= 1){
currentValue = currentValue - 1;
}
}
}
You should refactor your OnClickListeners so that they are generic. Probably the easiest way to do this is to change your addValue() method to be addValue(View v), and minusValue() to minusValue(View v). Then, in the layout xml, you add a property android:onClick=addValue or android:onClick=minusValue. You'll have to update the method bodies so that they check the view's id and do the right thing based on that, but you won't have to create and set a whole bunch of OnClickListeners in the onCreate method - you'll get that for free.

Categories

Resources