How do I get a variable in another activity?

后端 未结 3 1192
难免孤独
难免孤独 2020-12-31 12:58

How do I access variable value in another activity. In my example I have a string variable item which value is spinner selected value. How can I access this variable in ano

相关标签:
3条回答
  • 2020-12-31 13:52

    You can declare them as static variables and then in your other class you may access them like Activity1.stringName.

    public static String stringName; 
    
    stringName = .. // value from Spinner
    

    Then, in all the other Activities, you can access them as YourMainActivty.stringName.

    0 讨论(0)
  • 2020-12-31 13:57

    If you didn't want to use a global variable you could always create a method in your activity to return your string.

    public static String getMyString(){
        return item;
    }
    

    Then in your current activity you could call:

    String myValue = LoginScreen.getMyString();
    
    0 讨论(0)
  • 2020-12-31 13:59

    Try this.

    Step 1: Create a static Bundle object in Application class.( ApplicationClass.java)

         public static Bundle mMyAppsBundle = new Bundle():
    

    Step 2:

    Set key values pair in that bundle from anywhere. like this:

       ApplicationClass.mMyAppsBundle.putString("key","value");
    

    Step 3:

    Now you can get these values from anywhere like this way:

       String str = ApplicationClass.mMyAppsBundle.getString("key");
    

    Apply null check before using bundle objects for safety points of view.

    0 讨论(0)
提交回复
热议问题