Android Studio defaultValue/ passing Variables [duplicate]
Android Studio defaultValue/ passing Variables [duplicate]
This question already has an answer here:
I'm new to Android Studio and java, so hopefully you can help me.
I want to pass a double variable from on activity to the next.
But I'm unsure what needs so go in the defaultValue in the receiving activity.
Here is the code from activity one:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button weiter = (Button)findViewById(R.id.weiter);
weiter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText EingabeBreite = (EditText)findViewById(R.id.breite);
double breite = Double.parseDouble(EingabeBreite.getText().toString());
Intent rüber = new Intent(getApplicationContext(), Main2Activity.class);
getIntent().putExtra("next", breite);
startActivity(rüber);
Here is the code from the second activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView ergebnis = (TextView)findViewById(R.id.textView2);
Bundle extras = getIntent().getExtras();
double breite = extras.getDouble("next");
ergebnis.setText(Double.toString(breite));
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
3 Answers
3
Intent weiter = new Intent(MainActivity.this,Main2Activity.class);
startActivity(weiter);
EditText EingabeBreite = (EditText)findViewById(R.id.breite);
double breite = Double.parseDouble(EingabeBreite.getText().toString());
Intent rüber = new Intent(getApplicationContext(),MainActivity.class);
getIntent().putExtra("next","breite");
startActivity(rüber);
First off- you're starting 2 intents. That's not what you want. Only one activity can be in the forefront, you want to do one of these. Not both.
Secondly- you don't want getIntent().putExtra(). You want ruber.putExtra(). You need to put the extra on the intent you send to the other activity. Calling getIntent will get the intent that started the current Activity, which isn't what you're sending to the next one.
getIntent().putExtra()
ruber.putExtra()
Activity
use this code :
Intent mIntent = new Intent(HomeActivity.this, CenterActivity.class);
mIntent.putExtra("thevalue ", 0.0d);
startActivity(mIntent);
Intent intent = getIntent();
double d = Double.parseDouble(intent.getExtras().getString("thevalue "));
add the code to second activity:
double breite=getIntent().getDoubleExtra("next",0d);
So easy
What happens when you run your app? Does it have any errors? If so, what are they? If not, how does the behavior differ from what you want?
– Code-Apprentice
Sep 8 '18 at 5:03