我是一名Android开发人员,我制作了一个字符串,用于生成随机的6位OTP,它位于protected void onCreate(Bundle savedInstanceState) {
中,这是java程序中的第一件事
String otp = new DecimalFormat("000000").format(new Random().nextInt(999999));
Toast.makeText(getApplicationContext(), "Your OTP is " + otp, Toast.LENGTH_SHORT).show();
我的java程序中有另一个public void
,我必须在其中调用OTP字符串,但我不知道如何做到这一点。
任何类型的帮助都将不胜感激。
将String变量定义为类(静态(变量或类中的实例变量。
样品溶液
public class Main{
String otp; //Define your variable here
public void method1(){
//Now you can access the variable otp and you can make changes
}
public void method2(){
//Now you can access the variable otp and you can make changes
}
}
您可以将字符串定义为类数据成员,在onCreate方法中初始化它,并让同一类中的每个人都访问该数据成员。如:
String mOTP;
@Override
protected void onCreate(Bundle savedInstanceState) {
mOTP = new DecimalFormat("000000").format(new Random().nextInt(999999));
... Rest of code
}
或者,您可以创建另一个类,名为Consts或类似的类,并在那里创建一个静态String,然后从项目中的任何位置访问它。
public static class Consts{
public static String OTP_STRING;
}
然后在mainActivity 中
@Override
protected void onCreate(Bundle savedInstanceState) {
Consts.OTP_STRING = new DecimalFormat("000000").format(new Random().nextInt(999999));
... Rest of code
}