How to declare global variables in Android?

前端 未结 17 2935
死守一世寂寞
死守一世寂寞 2020-11-21 04:12

I am creating an application which requires login. I created the main and the login activity.

In the main activity onCreate method I added the following

17条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 04:45

    You could create a class that extends Application class and then declare your variable as a field of that class and providing getter method for it.

    public class MyApplication extends Application {
        private String str = "My String";
    
        synchronized public String getMyString {
            return str;
        }
    }
    

    And then to access that variable in your Activity, use this:

    MyApplication application = (MyApplication) getApplication();
    String myVar = application.getMyString();
    

提交回复
热议问题