Android:如何从类的方法中访问值?

时间:2017-04-01 15:43:17

标签: java android

看,我有2个类让我们说Login类和Welcome类,在Login Class中我有全局变量String Email;OnCreate()。我在该方法中设置了电子邮件的值,现在我的问题是如何获取我从方法初始化的变量的值?

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

我的另一个班是

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 个答案:

答案 0 :(得分:1)

您必须使用一些额外内容启动欢迎活动:

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

然后从Welcome活动onCreate方法中检索此额外内容:

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

    Intent intentWithData = getIntent();
    String userNameFromLoginActivity = intentWithData.getStringExtra("keyForUsername");
    String passwordFromLoginActivity = intentWithData.getStringExtra("keyForPassword");
}