androidstringandroid-activityandroid-intentextra

How to pass string between two activities


I have two activities A and B, and from activity A, I click on a button that opens a dialog box which contains a form consisting of two edit text fields and a button(the button in the dialog box is used to start activity B). So, my question is: how do I pass a string from activity B to activity A, but without closing the dialog box(the string will be used to fill one of the two edit text fields).


Solution

  • You need to create a class to store the variable. In ActivityB use set the value of the variable, the created class stores it and in ActivityA get the value of the variable.

    1. Create a class: GlobalVars.java. In this class put this:

      public class GlobalVars extends Application {

      private static String var2;
      
      public static String getVar() {
          return var2;
      }
      
      public static void setVar(String var) {
      var2 = var;
      }
      

      }

    In ActivityB put this line in to the appropriate place:

    String something;
    GlobalVars.setVar(something);
    

    In ActivityA put this line in to the appropriate place:

    String getsomething = GlobalVars.getVar();
    

    And that's it!