Search code examples
javaandroidandroid-studiodefault-value

Android Studio defaultValue/ passing Variables


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));

Solution

  •             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.