pat
pat

Reputation: 61

How to update not showing fragments

I am developing an Android app which receives information from a local server from time to time. For the in-app navigation I chose to use a navigation drawer which is replacing the selected fragments with

getSupportFragmentManager().beginTransaction().replace(R.id.flContent, fragment).addToBackStack(null).commit();

adding the selected fragment to the backStack for proper BackPress navigation.

The fragments are initialized in my MainActivity in

  private OverviewFragment overviewFragment;
  private IncidentFragment incidentFragment;
  private SettingsFragment settingsFragment;

protected void onCreate(){
  ...
  overviewFragment = new OverviewFragment();
  incidentFragment = new IncidentFragment();
  settingsFragment = new SettingsFragment();
  ...
}

What I want to do now is to update the TextViews out of the information received from the server. I tried this with the following method:

public void setIncidentDetails(NetworkIncident incident) {
        if (incident != null) {
            ArrayList<String> medicNames = null;

            ((TextView) view.findViewById(R.id.inLocationText)).setText(incident.getLocation());
            ((TextView) view.findViewById(R.id.inKeywordText)).setText(incident.getKeyword());
            if(incident.isEmsCalled()) {
                ((TextView) view.findViewById(R.id.inEmsText)).setText("Rettungsdienst alarmiert");
            } else {
                ((TextView) view.findViewById(R.id.inEmsText)).setText("Kein Rettungsdienst alarmiert");
            }
            for (int i = 0; i < incident.getMedics().size(); i++){
                medicNames = new ArrayList<String>();
                NetworkMedic currentMedic = incident.getMedics().get(i);
                medicNames.add(currentMedic.getForename() + " " + currentMedic.getSurename());
            }
            ((TextView) view.findViewById(R.id.inMedicText)).setText(medicNames.toString());
        }
    }

This only works if I previously opened fragment containing the TextViews. Otherwise I get a NullPointerException on the "view.findViewById...". Obviously because it hasn't been initialized before ;)

My question is if there is another way to update the TextViews if the fragment is not showing (another fragment is selected in the NavigatinoDrawer) or if hasn't even been selected.

(Maybe some global resource file from which the fragment pulls its information onCreate / onResume)?

Upvotes: 2

Views: 53

Answers (1)

pat
pat

Reputation: 61

Thanks to @Tejas I could solve this question. You have to, indeed use a DB or store the data-to-update temporarily to update a currently non-showing fragment.

As soon as this fragment is brought into foreground you can retrieve the stored data to update your TextViews etc...

Upvotes: 1

Related Questions