开发者

How do I pass a Boolean value between classes?

开发者 https://www.devze.com 2023-04-13 02:43 出处:网络
I am completely blanking on what i believe to be simple Java syntax. Here is an example of my first class:

I am completely blanking on what i believe to be simple Java syntax.

Here is an example of my first class:

public ExampleClass {
    public boolean exampleBool = false;

    if(SomethingImportantHappensOnRuntime) {
        exampleBool = true;
    }
}  

And here's the second class:

public ExampleClass2 {
    if(exampleBool) {
        //do stuff
    }
}

How do I pass exampleBool from ExampleClass to ExampleClass2 so that when something important happens on runtime exampleBool will be set to true an开发者_运维知识库d the "if" inside "ExampleClass2" would run?


The easiest way to do so would be:

public ExampleClass {
    public static boolean exampleBool = false;

    public static boolean returnExampleBool () {
        return exampleBool;
    }

    if(SomethingImportantHappensOnRuntime) {
        exampleBool = true;
    }
}

public ExampleClass2 {
    if(ExampleClass.ReturnExampleBool()) {
        //do stuff
    }
}


It's not clear from the question whether you just want to be able to read a member variable from one class in another or whether you want to second class to react when the flag is set in the first.

For the you just need access, to the member variable, make the member variable private otherwise it can get modified by anything then provide an accessor to read its value:

public ExampleClass {
    private boolean exampleBool = false;

    public boolean getExampleBool() {
        return exampleBool;
    }

    void someMethodOrOther() {
        if(somethingImportantHappensOnRuntime()) {
            exampleBool = true;
        }
    }
}   

If you want ExampleClass2 to react when the exampleBool changes then it's more complicated. Theres a design pattern called the observer pattern which is the goto solution for this kind of situation.

This involves adding an interface between the two classes which allows the second class to listen to the first without the first having specific knowledge of the second.

interface ExampleClassObserver {
    public void exampleClassChanged(ExampleClass exampleClass);
}

public final class ExampleClass {
    private final List<ExampleClassObserver> observers = new ArrayList<ExampleClassObserver>();
    private boolean exampleBool = false;

    public boolean getExampleBool() {
        return exampleBool;
    }

    public final void addObserver(ExampleClassObserver observer) {
        observers.add(observer);
    }

    public final void removeObserver(ExampleClassObserver observer) {
        observers.remove(observer);
    }

    void someMethodOrOther() {
        if(somethingImportantHappensOnRuntime()) {
            exampleBool = true;
            notifyObservers();
        }
    }

    private void notifyObservers() {
        for (ExampleClassObserver observer : observers) {
            observer.exampleClassChanged(this);
        }
    }

}

public final class ExampleClass2 implements ExampleClassObserver {
    public ExampleClass2(ExampleClass exampleClass) {
        // we need to start observing the class so we're notified when the change happens
        exampleClass.addObserver(this);
    }
    public void exampleClassChanged(ExampleClass exampleClass) {
        if (exampleClass.getExampleBool()) {
            // do something
        }
    }
}

So what's happening here is that when the boolean flag is set anything that's observing gets notified of the change, when ExampleClass2 is notified it checks the flag and does what it needs.


I would have an instance of ExampleClass2 in ExampleClass. ExampleClass2 should have a method like setBoolean(boolean b) which updates the field in the object. When the even happens, you can call this setter method in ExampleClass2.


I want to thanks Raza for hes simple answer and share mine, is an adaptation for a Spinner with a Listener (setOnItemSelectedListener). This could be usefull for validating something was done with the spinner, before saving, or if the spinner is in the right position, etc:

First, set the two basics classes, Raza so gladly provide us:

public static boolean myBoolean = false;
    public static boolean ClassForRetruningBoolean() {
        return myBoolean;
    }

Second, I have to set the spinner listener:

spinner.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if (position == 0) {

                            myBoolean = false;

                        }

                        else if (position != 0) {

                            myBoolean = true;

                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        //Semicolons and parenthesis make crying faces
                    }
                }
        );

Third, you have to make that class available for your other class. Im doing this with AndroidAnnotations. Also, Im inside an Activity file.

@Bean
    TheClassWhereTheBooleanIs getingTheClassForTheBoolean;

After, that set an onClickListener for a Button, and retrieve the class where the boolean was writen:

    myButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                /*Validation for empty CNC text area*/
                else if (getingTheClassForTheBoolean.ClassForRetruningBoolean() == true /*you could also add another condition here && etc*/) {
                    Toast toast = Toast.makeText(getApplicationContext(), "Boolean is True therefore no saving", Toast.LENGTH_LONG);
                    toast.show();
                }

                /*Every validation has being pass now you can move on*/
                else {

//So if the validation pass you can do the intent, the boolean is false

                    Intent i = new Intent(getApplicationContext(), OtherActivity.class);
                    startActivity(i);
                }


                }
            });

Hope you guys find it usefull

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号