Make a String in java Global

103 views Asked by At

I am an Android developer and I have made a string for generating a random 6-digit OTP which is there in the protected void onCreate(Bundle savedInstanceState) {, the first thing in a java program.:

String otp = new DecimalFormat("000000").format(new Random().nextInt(999999));
Toast.makeText(getApplicationContext(), "Your OTP is " + otp, Toast.LENGTH_SHORT).show();

I have another public void in my java program in which I have to call the OTP String but, I don't know how to do that.

Any type of help will be appreciated.

2

There are 2 answers

2
Hasindu Dahanayake On BEST ANSWER

Define your String variable either as a class(static) variable or instance variable in your class.

Sample solution

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


  }

}
0
Dan Baruch On

You can either define the string as a class data member, initialize it in the onCreate method and have everyone in the same class access that data member. As in:

String mOTP;

@Override
protected void onCreate(Bundle savedInstanceState) {
mOTP = new DecimalFormat("000000").format(new Random().nextInt(999999));
... Rest of code
}

Or, you can create another class, named Consts or something of the sort, and create a static String there and access it from where ever in your project.

public static class Consts{
     public static String OTP_STRING;
}

and then in mainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
Consts.OTP_STRING = new DecimalFormat("000000").format(new Random().nextInt(999999));
... Rest of code
}