0

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.

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
  • U can move the String outside of the method scope and add the ‘static’ keyword in front of it. (Though this is usually bad design) – Stan van der Bend Oct 18 '20 at 17:09
  • provide some more source code of `onCreate()` and your other method that invoke `onCreate()`. – pl-jay Oct 18 '20 at 17:12

2 Answers2

0

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
}
Dan Baruch
  • 1,063
  • 10
  • 19
0

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


  }

}
Hasindu Dahanayake
  • 1,344
  • 2
  • 14
  • 37