How to pass data between activities using static variables in a public class?
I am trying to use static variables in a public class to pass them between activities.
I'm having a rare problem. I am giving values to static variables in an activity. This activity calls GLSurfaceView and listens for screen orientation changes.
If I give values to static variables in GLSurfaceView then everything works fine, the values are saved and I can restore them when the onCreate method is called again after changing the screen orientation.
The problem is that I am storing values for static variables outside of the GLSurfaceView class inside the onTouchListener methods. These values are not stored properly in static variables, because when I try to access them in the GLSurfaceView, these values are not what they were suppressed.
This is my static variable 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)
}
This is where I store the values in my activity class (I did debug and apparently they are 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 am trying to get these values in the GLSurfaceView class and the values are wrong, it returns the original initial value 1 instead of the value saved earlier.
currentPage=MagazineStatus.currentPage; //cargo datos guardados antes del cambio de orientación
What am I doing wrong?
source to share
If Android kills and restarts the process for your application, then the static variables will be bound to their default values. You might be better off using SharedPreferences
static variables instead: http://developer.android.com/guide/topics/data/data-storage.html#pref
source to share
Second activity : -
In xml file select one text box
Java code
public static String name;
TextView t=(TextView)findViewById(R.id.tv);
t.setText(name);
First Activity : -
in xml file take one editor and one button
Java code
button.setOnClickListener(new View.onClickListener){
@override
public void onClick(View v){
SecondActivity.name=editText.getText().toString();
Intent i=new Intent(firstActivity.this,SecondActivity.class);
startActivity(i);
}
}
source to share