JustANoob
JustANoob

Reputation: 65

Android LiveData Not updating

I am currently trying to detect changes in another file from a fragment and updating the ui accordingly using LiveData. I have one class - datacontroller with getters and setters for my app's data.In the code below, I want the UI in a separate fragment to change every time the user adds a skill. I would appreciate if someone could point me to why my UI is not being updated and how to go about fixing it?

The getter for skills is: It is located in the dataController class and extends ViewModel

private MutableLiveData<List> skillMutable = new MutableLiveData<List>();
public  MutableLiveData<List> getSkills(){
   ArrayList<skill> listToReturn = new ArrayList<skill>();

    try {
        InputStream inputStream = context.openFileInput(skillFileName);

        if (inputStream != null) {
            InputStreamReader streamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(streamReader);

            String l;
            skill toAdd;
            while (( l = bufferedReader.readLine()) != null) {

                System.out.println("MY line  is" + l);
                String[] skillSeparated = l.split("_");
                toAdd= new skill(skillSeparated[0], skillSeparated[1]);
                listToReturn.add(toAdd);
            }

        }

        inputStream.close(); //close the file
    } catch (java.io.FileNotFoundException e) {
        //file doesnt exist
    } catch (IOException e) {
        e.printStackTrace();
    }
    skillMutable.setValue(listToReturn);
    return skillMutable;
}

and the code to update UI is: here and it is located in a class that extends Fragment

dataManager = new dataController(getContext());

    dataManager.getSkills().observe(this, skillMutable -> {
        // update UI
        if(dataManager.getResumeNumber() == "1") {
            resumeWebview.loadData(pdfManager.getResume1(), "text/html; charset=utf-8", "UTF-8");
        }
    });

Upvotes: 1

Views: 3265

Answers (2)

bartonstanley
bartonstanley

Reputation: 1317

The value of skillMutable is getting set before the observe() method is called. The observe() method must be called before the value is set. Otherwise, there is nothing observing skillMutable when its value changes.

The minimal thing you can do to see it work is to make skillMutable public and then call observe() on it before calling getSkills().

BTW, I'm not sure why MutableLiveData is needed here. Can the getSkills() method return ArrayList<skill> rather than returning MutableLiveData<List>?

Upvotes: 1

vanillaSugar
vanillaSugar

Reputation: 551

Check this answer

LiveData takes in an observer and notifies it about data changes only when it is in STARTED or RESUMED state.

Your skills aren't updated probably because your view didn't change state.

Upvotes: 0

Related Questions