1

see, I have 2 class lets say Login class and Welcome class, within Login Class I have Global Variable String Email; and an OnCreate() . and i set value for Email within that method, now my question is how do I get the value of that Variable that I initialized from a method?

public class LoginActivity extends AppCompatActivity {
private EditText email,password;

public String emailText;

protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        email = (EditText) findViewById(R.id.email);
        //I want to get this value
        emailText = email.getText().toString();
}
}

and my another class is

public class Welcome extends Activity{
protected void onCreate(Bundle savedInstanceState) {
     TextView textView = (TextView) findViewById(R.id.email);
     //this is what I did which is the variable that was unInitialized
     LoginActivity loginActivity = new LoginActivity();
        textView.setText(loginActivity.getEmailText());
}
}

1 Answers1

1

You have to start the Welcome activity with some extras:

    Intent startWelcomeActivityIntent = new Intent(context, Welcome.class);
    startWelcomeActivityIntent.putExtra("keyForUsername", userNameString);
    startWelcomeActivityIntent.putExtra("keyForPassword", passwordString);
    startActivity(startWelcomeActivityIntent);

Then retrieve this extras from the Welcome activity onCreate method:

protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intentWithData = getIntent();
    String userNameFromLoginActivity = intentWithData.getStringExtra("keyForUsername");
    String passwordFromLoginActivity = intentWithData.getStringExtra("keyForPassword");
}
Alex Kamenkov
  • 891
  • 1
  • 6
  • 16
  • ohh thats seems to work, thanks! i was wondering too if how should i do this in fragment. was their any java approach where i can get variable from methods? – ProblematicSolution Apr 01 '17 at 22:38
  • 1
    You have to set the extras via arguments, here is a good [example](http://stackoverflow.com/a/17436739/5281581) of how to pass variables from activity to fragment. – Alex Kamenkov Apr 01 '17 at 22:43