• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps passing variable from one class to another

ondrovic

Newbie
This is probably a dumb question but I would like to setup a boolean called dFlag in the main.class of my program and reference it in another class.

I already have it setup to work locally just hitting a snag on how to do it.
Code:
public class Main extends Activity {
      boolean dFlag; ///Debug flag, true=enabled | false=disabled
}

public class Other extends Activity {
      if(dFLag = true) {
         ///Output debug message
      }
}
Or is there an easier way to do what I want without having to re-invent the wheel so to speak?

Thanks for the help
 
The simplest - and dirtiest - solution would to make the variable a static class variable.

Code:
public class Main extends Activity {
      [COLOR=GREEN]public static[/COLOR] boolean dFlag; ///Debug flag, true=enabled | false=disabled
}

public class Other extends Activity {
      if([COLOR=GREEN]Main.[/COLOR]dFLag [COLOR=RED]==[/COLOR] true) {
         ///Output debug message
      }
}


Also be very careful to use == when to mean to use == and not using = when you mean to use ==. Getting those two confused will lead to make hours of frustrating debugging.

In the particular situation, you actually want to do neither. If you have a boolean variable, just use it, there's no need to test it against true.

The if above is equivalent to:
Code:
      if(Main.dFLag) {
 
The correct way to do this in android is:

Code:
public void launchNewActivity(Boolean dFlag) {
this.startActivity( new Intent(Main.this,Second.class).addExtra("dFlag",dFlag) );
}

and in the launched class:

Code:
Boolean dFlag;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
dFlag = i.getBooleanExtra("dFlag");
}
 
Back
Top Bottom