Search code examples
javaandroidandroid-intentbundle

Android Intent is not passing the variable from one class to another


In Android Studio, I created a simple field called name. I want to pass this variable called name to the class called MainActivity2. I have declared Intents and Bundle to this. However, the MainActivity1 class is not sending this variable to MainActivity2. The proof of this is that the code: Toast.makeText(getApplication(), "Name:" +name, Toast.LENGTH_LONG).show();

It should show: Name: +name

The problem is that it only appears: "Name: "

Please, can anyone help me? My code is:

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    EditText name; Button nextPage;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        name = findViewById(R.id.namefield);

        final String name = name.getText().toString();

        nextPage = findViewById(R.id.nextPage);

        nextPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent senderIntent = new Intent(getApplicationContext(), MainActivity2.class);
                Bundle bundle = new Bundle();
                bundle.putString("name", name);
                senderIntent.putExtras(bundle);

                startActivity(senderIntent);
                    Toast.makeText(getApplication(), "Name:" +name, Toast.LENGTH_LONG).show();
            }
        });
    }
}```

Solution

  • Try this, in MainActivity :

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        name = findViewById(R.id.namefield);
        nextPage = findViewById(R.id.nextPage);
    
        nextPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent senderIntent = new Intent(MainActivity.this, MainActivity2.class);
                String strName = name.getText().toString();
                senderIntent.putExtra("NAME", strName);
                startActivity(senderIntent);
            }
        });
    }
    

    then in MainActivity2 to get the String use this :

        Bundle extra = getIntent().getExtras();
        String newString = extra.getString("NAME");