Skip to content Skip to sidebar Skip to footer

Java ,properly Using Static Variables To Prevent Deadlock - Synchronizing

I am new to android programming and 've not thoroughly studied java before . I am really confused on how to use synchronized to ensure thread safety on static variables : I usually

Solution 1:

I think all your need is to create Application Class

[1] All those variables you have taken in Util, which are used in about all other class, can be taken in this Application class. So these variables will be available to all other classes.

[2] Create Singelton instance of Appliction class. Just Google about it.

[3] Also create Singleton of DataBaseHelper(if possible and can apply), so, single instance helps you every where.


Application Class is Global class in android, so you can use it to store and access all Global-Data. e.g. :

publicclassAppDataextendsApplication {

    publicstatic AppData appData;

    publicint currentUserId; // etc.//Const.publicAppData() {
        appData = this;
    }

    @Override
    publicvoidonCreate() {
        super.onCreate();
        loginPreferences = getSharedPreferences(
            SPF_NAME, 0);

        pathToSDCard = Environment.getExternalStorageDirectory().getAbsolutePath();
        System.out.println("Path : " + pathToSDCard);
       //etc.
    }

 //    MOST IMP  FOR GETTIN SINGELTON INSTANCE     <<<---<<<---<<<---publicstatic AppData getAppData() {
        return appData;
    }
}

HOW TO USE IT, SEE THIS

classABCextendsActivity {
    AppData appData;
    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xyz);

        appData = AppData.getAppData();
        ...........
        ...........

        appData.VARIABLE_NAME...
    }
}

One thing more. In AndroidMenifest.xml

    ...
    ...
<application             //   In Application Tag
        android:name="PACKAGE_NAME.AppData"//  <<  Add here class name in which you have extended Application
        android:icon="@drawable/ic_launcher"
    ...
    ...

Post a Comment for "Java ,properly Using Static Variables To Prevent Deadlock - Synchronizing"