Search code examples
androidandroid-activityviewscreenbackground-process

Updating an activity that has not been opened


What would be the best method for updating the information on an activity that hasnt been opened by the user yet?

For example say I have three activities; A, B, and C. Lets say I want to open the application and press a button on activity A that changes the information displayed on activity B and C without having to open B and C first. I know that doing this would crash the application because the variables being changed on B and C would yet to be declared and initialized, I know that one way around this would be to start the app by first openening C which then opens B and then A, starting all three activities but this seems messy.

Is there a way to transparently open/start B and C without jumping around to different activities when the app is launched?
Thanks


Solution

  • You need to create your B and C Activities from a persistent Storage made by A, for example, use SharedPreferences to store the data you need to have updated, and use it too in B and C to load the previously stored data.

    The SharedPreferences works with key/value data, wich is useful in the whole context of the app, it also accepts Strings, ints, and almost whatever you need.

    As a mini template:

    SharedPreferences prefs = getSharedPreferences("name_of_your_preferences_store", Context.MODE_PRIVATE);
    
    ...
    
    public boolean setActualData(String data){
    
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("my_tag_for_specific_data_field", data);
            return editor.commit();
        }
    
    public String getActualData(){
    
                return prefs.getString("my_tag_for_specific_data", "data_defeult_return_value");
    
            }