Home > Software design >  How to recieve intent only for the first time for entering an activity but not the configuration cha
How to recieve intent only for the first time for entering an activity but not the configuration cha

Time:11-01

The problem is that the intent that I'm directly receiving from other activity is replacing the saved state from previous configuration change, now this part of the code is located in onCreate method meaning either the activity is loaded for the first time or on configuration change, it will be called.

My workaround here (the magic value 20) is to compare if the saved state before configuration change is containing the default value, if that's the case then it is safe to replace it with the value from intent.

However, is there a better approach of dealing with intent only when the activity is launched for the first time or simply stop getting intent after it has been received?

        brushViewModel = new ViewModelProvider(this).get(BrushViewModel.class);

        BrushModel brushModel = (BrushModel) getIntent().getSerializableExtra(MainActivity.INTENT_KEY_BRUSH);
        if(brushViewModel.getBrushSize() == 20){
            brushViewModel.setAll(brushModel);
        }

CodePudding user response:

Your brush related data should be null (or the initial value you give) in your ViewModel the first time your activity runs, but once it is set data on ViewModel doesn't change so you can check if your data on viewModel is null or not. if it is null fill it with your intent data. If it is not keep using it.

CodePudding user response:

what if using shared preferences does it not meet your needs?

set the value and check the data stored in local and if there is a value you want it means it is expected

  • Related