ProblematicSolution
ProblematicSolution

Reputation: 41

Android:How can I access a value from a method of a class?

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

Upvotes: 1

Views: 41

Answers (1)

Alex Kamenkov
Alex Kamenkov

Reputation: 891

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

Upvotes: 1

Related Questions