Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a realtime value change in Java like React.js

I got used to React.js for 6 months and starting to develop an app from Java scratch for my Android application.

In React.js, All it does when the boolean changed from false to true:

this.state = {
    checkmarkChecked: false
}
if (this.state.checkmarkChecked) {
    //If the checkmarkChecked is true
    //TODO: show all checks
} else {
    //If the checkmarkChecked is false
    //TODO: hide all checks
}

If the checkmarkChecked was switched to true, it calls the true one to show.

Now I am new to Java for Android development, i tried one of these:

//onCreate
while (true) {
    if (checkmarkChecked) {
        System.out.println("True");
    } else {
        System.out.println("False");
    }
}

Actually, the while(true) causes my app to freeze at the start.

like image 922
aliamanuba Avatar asked Dec 02 '25 09:12

aliamanuba


1 Answers

You may use a MutableLiveData that wraps a Boolean, and register the activity to observe it with .observe().

Whenever this boolean value changes, then onChanged() callback will be triggered with the new value of the boolean.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final MutableLiveData<Boolean> state = new MutableLiveData<>(false);
    
        state.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean newValue) {
                if (newValue) {
                    Toast.makeText(MainActivity.this, "True", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "False", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        Button myButton = findViewById(..);
        
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                state.setValue(!state.getValue());
            }
        });
        
    }
}

The button just for toggling the boolean value to test it

like image 154
Zain Avatar answered Dec 03 '25 21:12

Zain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!