Search code examples
androidandroid-activitystaticglsurfaceview

How to pass data between activities using static variables on a public class?


I'm trying to use static variables on a public class for passing them between activities.

I'm having a rare problem doing that. I'm giving values to the static variables on a activity. This activity calls a GLSurfaceView and listen for screen orientation changes.

If i give values to the static variables on the GLSurfaceView, then, all works fine, the values are stored and i can retrieve them when the onCreate method is called again after a screen orientation change.

The problem is when i store values on the static variables outside the GLSurfaceView class, inside the onTouchListener methods of the activity. These values are not stored properly on the static variables, because when i try to access them on the GLSurfaceView those values are not what they were supossed to be.

This is my static variables class:

public class MagazineStatus {
//clase utilizada para almacenar variables estáticas.   
static int currentPage=1; //página actual   
//Valores originales cuando pasamos de un modo a otro, por ejemplo, de portrait a landscape.
static float oScale=0.0f;
static float oX=0.0f;
static float oY=0.0f;
static float oZrot=0;   
static boolean modeChanged=false; //indica si hemos cambiado de modo 
(landscape/portrait)    
}

Here i'm storing the values on my activity class (i did a debug and aparently they are being stored correctly):

        for (int i=0;i<thumbnailLinearLayouts.size();i++){
        final int auxIndex=i;
        thumbnailLinearLayouts.get(i).setOnTouchListener(new OnTouchListener(){
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                MagazineStatus.currentPage=auxIndex;
                System.out.println("MagazineStatus.currentPage: "+MagazineStatus.currentPage);
                return true;
            }                               
        });
    }

And here i'm trying to retrieve these values on the GLSurfaceView class, and the values are not correct, It is retrieving the original initial value, 1, instead of the value stored before.

currentPage=MagazineStatus.currentPage;     //cargo datos guardados antes del cambio de orientación

What i am doing wrong?


Solution

  • If Android kills and restarts the process for your application, then the static variables will get assigned to their default values. You might be better of using SharedPreferences instead of static variables: http://developer.android.com/guide/topics/data/data-storage.html#pref