i need to sum the values in the second activity. I can not get it to total correctly. would someone be kind enough to help me?
final EditText et = (EditText)findViewById(R.id.etwalkingburned);
final EditText ed = (EditText)findViewById(R.id.etrunningburned);
mcardiototalbutton = (Button)findViewById(R.id.cardiototalbutton);
mcardiototalbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int walkingburned = Integer.parseInt(et.getText().toString());
int runningburned = Integer.parseInt(ed.getText().toString());
Intent myIntent = new Intent(getApplicationContext(),TotalActivity.class);
myIntent.putExtra("CardioTotal",walkingburned);
myIntent.putExtra("CardioTotal",runningburned);
startActivity(myIntent);
}
});
}
public class TotalActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.totalactivity);
Bundle extras = getIntent().getExtras();
int walkingburned = extras.getInt("CardioTotal");
int runningburned = extras.getInt("CardioTotal");
int cardiototal = walkingburned + runningburned;
TextView tv = (TextView)findViewById(R.id.cardiototalresult);
walkingburned = walkingburned + 0;
runningburned = runningburned + 0;
cardiototal = walkingburned + runningburned;
tv.setText("Cals.:" + cardiototal);
}
The problem is the way you are putting and getting extras to/from your intent.
myIntent.putExtra("CardioTotal",walkingburned);
myIntent.putExtra("CardioTotal",runningburned);
Think of an extra as a key-value pair. You should have a different string as the first parameter each time you call putExtra, otherwise you will overwrite the value of what you've already put in. So basically you put in the walkingburned value and then overwrote it with the runningburned value because you used the same key string.
Likewise, in your second activity you need to reference the values by their unique string "key" or you will just get the same value two times.
In this situation, there is more than one way to skin a cat. More specifically, you could do the addition in your first activity and only store one extra (the sum) to avoid the confusion of multiple extras. But, I think it would benefit you more to understand how extras and intents works.
For starters, instead of using "CardioTotal"for each extra, you can simply call the string something similar to your variable name. This is what I do and it would make your code easier to understand in my opinion.
myIntent.putExtra("Walking Burned",walkingburned);
myIntent.putExtra("Running Burned",runningburned);
It doesn't really matter what String you put in the first parameter as long as you know that they are supposed to represent different values.
The second change you would then need to make is how you get the extra out of the intent.
int walkingburned = extras.getInt("CardioTotal");
int runningburned = extras.getInt("CardioTotal");
What you are currently doing is retrieving the same value (you are using the same key string therefore it is the same value) to two separate variables. So the value you would be seeing is double the runningburned value.
Now, since you have two different Strings for the two different variables in your intent, you can just say:
int walkingburned = extras.getInt("Walking Burned");
int runningburned = extras.getInt("Running Burned");
The rest of your code is fine.
You also don't need these lines in your TotalActivity
walkingburned = walkingburned + 0;
runningburned = runningburned + 0;
Sorry this was a really long answer but I wanted to explain a few things.
Hope it helps!
Related
https://developer.android.com/training/basics/firstapp/starting-activity
public class MainActivity extends AppCompatActivity {
public static final String SIGNUP_EMAIL = "com.example.myapplication.SIGNUP_EMAIL";
public static final String SIGNUP_PASSWORD = "com.example.myapplication.SIGNUP_PASSWORD";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void signup(View view) {
Intent intent = new Intent(this, SignupResultActivity.class);
EditText signup_email = (EditText) findViewById(R.id.signup_email);
EditText signup_password = (EditText) findViewById(R.id.signup_password);
String email = signup_email.getText().toString();
String password = signup_password.getText().toString();
intent.putExtra(SIGNUP_EMAIL, email);
intent.putExtra(SIGNUP_PASSWORD, password);
startActivity(intent);
}
}
public static final String SIGNUP_EMAIL = null;
public static final String SIGNUP_PASSWORD = null;
why should not use "null" in this code?
if you put SIGNUP_EMAIL=null and SIGNUP_PASSWORD=null, is not working
Intent is similar to Map, the value of these variables are the keys to index this map. Not only those keys must be non-null, but they must be different from each other.
Quoted from Start another activity (emphasis mine):
The putExtra() method adds the EditText's value to the intent. An Intent can carry data types as key-value pairs called extras. Your key is a public constant EXTRA_MESSAGE because the next activity uses the key to retrieve the text value. It's a good practice to define keys for intent extras using your app's package name as a prefix. This ensures the keys are unique, in case your app interacts with other apps.
SIGNUP_EMAIL and SIGNUP_PASSWORD are not default values for mail and password, they are string keys used to pass ang get the values, so they cannot be null.
They are public constants so that the intent can know them to retreive the value.
EDIT: note that the strings are declared final so that the keys cannot be changed afterwards, having a property declared final with a null value should have raised a mental flag as it is a bit useless..
when you want to pass a data from one activity to another one you should use intent.putExtra(name,data);
first parameter is the name and second is data that you want to send
you can use any string that you want for name parameter but it cant be null
in second activity you use it to get data from first activity by this code :
intent.getStringExtra(name)
You can use any unique string to map the values. Null wont work but "null" will work. But keep one thing in mind that for two different values you need to assign different keys also.
Like this:
public static final String SIGNUP_EMAIL = "null";
public static final String SIGNUP_PASSWORD = "Null";
I have a problem with with sharing data between two different activities. I have data like :
int number
String name
int number_2
int time
int total
I'm trying to make something like order list with this set of data . So it will take one set of data , then back to previous activity , move forward and again add data to it .
I have an idea of making it in array of object - but data inside was cleared after changing activity.
How can I make it ?
I don't know if and how to add Array of object to SharedPreferences , and get value of one element from there.
You should have a look at the documentation of the Intent(s) if you want to do that on the fly associating a key to the value(s) that you want to pass to your second activity.
Anyway, you can think any(sharedpref, database,...) way to pass your parameters but for those kind of things it's a convention and a good practice to follow that.
Don't used share preferences for this...Use the singleton pattern, extend Application, or just make a class with static variables and update them...
You can use .putExtra but since you are communicating with more than one activity the above suggestions are probably the best.
public class ShareData {
private String s;
private int s;
private static ShareData shareData = new ShareData();
private ShareData(){}
public static ShareData getInstance(){ return shareData}
//create getters and setters;
}
Why not to use Intents
Intent intent = new Intent(FirstActivity.this, (destination activity)SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);
in the second activity
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");
EDIT if you want to read more about adding array to shared preferences check this
Is it possible to add an array or object to SharedPreferences on Android
also this
http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html
From my Sudoku.java I make call to Game.java and pass the difficulty level along with.
private void startGame(int i) {
Log.d(TAG, "clicked on " + i);
Intent intent = new Intent(Sudoku.this, Game.class);
intent.putExtra(Game.KEY_DIFFICULTY, i);
startActivity(intent);
}
Here's part of my Game.java
public class Game extends Activity {
private static final String TAG = "Sudoku" ;
public static final String KEY_DIFFICULTY = "org.example.sudoku.difficulty" ;//What is this?
public static final int DIFFICULTY_EASY = 0;
public static final int DIFFICULTY_MEDIUM = 1;
public static final int DIFFICULTY_HARD = 2;
private int puzzle[] = new int[9 * 9];
private PuzzleView puzzleView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate" );
int diff = getIntent().getIntExtra(KEY_DIFFICULTY,DIFFICULTY_EASY); //What is this?
puzzle = getPuzzle(diff);
calculateUsedTiles();
puzzleView = new PuzzleView(this);
setContentView(puzzleView);
puzzleView.requestFocus();
}
}
My question is what is happening in line
public static final String KEY_DIFFICULTY = "org.example.sudoku.difficulty" ;
KEY_DIFFICULTY is final, how will i ever change it.
Also, while fetching the extra data info from intent, how is it storing it?
the value of this public static final String KEY_DIFFICULTY = "org.example.sudoku.difficulty" ; is not changing but imagine intent has a bucket(a hashmap) and KEY_DIFFICULTY is a key in it
You are storing a value against that key and getting it back via intent. You never change the key it self as it is final.
Even if you remove final it will work but you must retrieve the value with the same key you set it with.
So KEY_DIFFICULTY never changes but the value against it in extras bundle is set and retrieved.
public static final String KEY_DIFFICULTY =
"org.example.sudoku.difficulty" ;//What is this?
=> First of all, Intent stores data in a key-value pairs, same like HashMap. So whatever data you would want to store/fetch into/from it, you have to have KEY name.
Now as you have already made KEY_DIFFICULTY as static final, you won't be able to change it as it becomes constant.
Key is used to get the extra data so it should not be changed. And an intent can contain or storing datas via a Bundle. And for more clarification please look at Android Intents.
Cheers
Ok, first thing is that I am new in Android development, please do not shoot me for the question.
So, I am developing an app yhat needs to multiply from 3 EditTexts:
resultsEditText
amountEditText
taxEditText
They are set with the same name in the R.java. what I want is the following:
amountEditText * taxEditText = resultsEditText
I have no idea in how to implement this, I have searched the internet and this site, which I use as a reference for all my Android development needs, and all the code I found doesnt work at all. I dont know what else to do. Thanks in advance!
You need to set EditText input type as number as well so user can input only numbers.
int a = Integer.parseInt(resultsEditText.getText().toString().toTrim());
int b = Integer.parseInt(amountEditText.getText().toString().toTrim());
int c = Integer.parseInt(taxEditText.getText().toString().toTrim());
int result = a * b * c;
Button btnCal,btnSub;
EditText editLen,editWid,editFeet;
int a,b,res;
btnSub=(Button)findViewById(R.id.btnSub);
btnCal=(Button)findViewById(R.id.btnCal);
editLen=(EditText)findViewById(R.id.editLen);
editWid=(EditText)findViewById(R.id.editWid);
editFeet=(EditText)findViewById(R.id.editFeet);
btnCal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.parseInt(editLen.getText().toString());
b = Integer.parseInt(editWid.getText().toString());
res=a*b;
editFeet.setText(String.valueOf(res));
}
});
So I'm still working on my first little app here, new to Android and Java, so I'm stuck on a basic little problem here. Answers to my first questions were really helpful, so after researching and not coming up with anything, I thought I'd ask for some more help!
The idea is that on another screen the user makes a choice A, B, C, or D, and that choices is passed as a string through the intent. OnResume checks if the choice is not null and sets an integer that corresponds to that string. Later when the user pushes another button, some if else logic checks that int and performs and action based on which was chosen. The problem is that the App crashed at onResume.
I learned that I have to use equals(string) to compare string reference, but maybe the problem is that I am trying to compare a string in reference to a literal string? Any help would be greatly appreciated.
Thanks!
protected void onResume() {
super.onResume();
// Get the message from the intent
Intent intent = getIntent();
String choice = intent
.getStringExtra(ExtensionSetupSlector.TORQUE_SETUP);
// Create the text view
TextView displayChoice = (TextView) findViewById(R.id.displayChoice);
if (!choice.equals("")){
displayChoice.setText(choice);
if (choice.equals("A")) {
myChoice = 1;
}
if (choice.equals("B")) {
myChoice = 2;
}
if (choice.equals("C")) {
myChoice = 3;
}
if (choice.equals("D")) {
myChoice = 4;
}
}
}
myChoice is declare right after ...extends Activity{ Also I'm not quite sure If this should really be in onResume, but it was working before I started try to set myChoice in the onResume (when I was just displaying the choice). Thanks again!
Change if (!choice.equals("")) to check for null instead. Otherwise your app attempts to access an empty reference and crashes.