0

I have my activity with one boolean variable public.

I set the variable value to true in other class inside MainActivity, but when my application enters the onPause() function, the variable gets the value false, why?

public class MainActivity extends ActionBarActivity {

public boolean detectedState;

public boolean isDetectedState() {
    return detectedState;
    }

public void setDetectedState(boolean DetectedState) {
    this.detectedState = DetectedState;
} 

// i have one fragment in MainActivity...

public static class contentFragment extends Fragment{

   // Get and set value of Variable

     MainActivity activity = new MainActivity();

    System.out.println(activity.isDetectedState());
    //out is false
    activity.setDetectedState(enable);
    System.out.println(activity.isDetectedState());
    //out is true

  // if now i click in home Button for example, the application is with          state onPause.. and my out println is false, why?

}


 @Override
protected void onPause(){

   super.onPause();

    System.out.println(isDetectedState());
    //here out is false...
}

}
user2227682
  • 73
  • 1
  • 2
  • 8
  • 1
    Where is your onCreate method on MainActivity. If you want get your variable true, you need to call your Fragment class by using oncreate() of your MainActivity. Define onCreate() of MainActivity and call your fragment class... then you can do asiignments – codezoner May 27 '15 at 03:32
  • 1
    because isDetectedState was never true, if it was it was true for ` MainActivity activity` instance, so in your fragment onPause() rather log it there and it will be true, but from what you want you might need to follow the answers being provided, Sir, pass the boolean as bundle – Elltz May 27 '15 at 03:39

3 Answers3

0

You should understand that the value of detectedState is set to true for the instance of activity instantiated inside the Fragment class. Variable's value doesn't get affected if you change its value inside an inner class.

Shubham A.
  • 2,446
  • 4
  • 36
  • 68
0

You should never create Activity like this MainActivity activity = new MainActivity();

You can use interfaces to pass data between Activity and Fragment.

Aleksandr
  • 787
  • 6
  • 22
0

You can achieve it by making that variable static but it would be better if you store in the application class.check this

Community
  • 1
  • 1
Chandra Sharma
  • 1,339
  • 1
  • 12
  • 26