Accessing global Variables in Android

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I have a class file which extends SurfaceView and implements SurfaceHolder.Callback which is saved as myView.java

public class myView extends SurfaceView implements SurfaceHolder.Callback

Now i got another java file GlobalVar.java which is like this

import android.app.Application;

class GlobalVar extends Application {

private int touchCount;

public int getCount()
  {
  return touchCount;
  }

public void setCount(int tCount)
  {
  touchCount = tCount;
  }
}

Inside myView class(myView.java) there is a function onTouchEvent

@Override
public boolean onTouchEvent(MotionEvent event) {
   int pointerCount = event.getPointerCount();
   }

Now what i want is to set the the global Variable touchCount to pointCount. And i tried like this

@Override
public boolean onTouchEvent(MotionEvent event) {
    int pointerCount = event.getPointerCount();
    GlobalVar tcount = ((GlobalVar)getApplicationWindowToken());
tcount.setCount(pointerCount);
  } 

And this is giving me error.So how can i set the global variable value inside this myView class file???

Application portion of manifest file

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".MyViewActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>
<application android:name=".GlobalVar"  android:icon="@drawable/icon"                 android:label="@string/app_name">
</application>

Answers

May be you ll need a some singleton class which will hold all you variables?

public class GlobalVar {

    public int getMyVar() {
        return myVar;
    }

    public void setMyVar(int myVar) {
        this.myVar = myVar;
    }

    private int myVar = 0;
    private static GlobalVar instance;

    static {
        instance = new GlobalVar();
    }

    private GlobalVar() {
    }

    public static GlobalVar getInstance() {
        return GlobalVar.instance;
    }

}

Usage pattern:

@Override
public boolean onTouchEvent(MotionEvent event) {
    int pointerCount = event.getPointerCount();
    GlobalVar.getInstance().setMyVar(pointerCount);
} 

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/4838228/accessing-global-variables-in-android

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils