简体   繁体   中英

Android "getter" is returning the wrong value

I have class B that extends class A and I am trying to access a variable from class A, but it's not returning the proper value.

(1) Variable declaration at the top of class A:

private int tripCount;

(2) I have a ViewModel observer in onCreate of class A that is looking for changes in a ROOM database and setting the tripCount variable accordingly:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // we are going to overwrite this
    // setContentView(R.layout.activity_base);

    baseViewModel = ViewModelProviders.of(this).get(TripViewModel.class);
    baseViewModel.getAllTrips().observe(this, new Observer<List<TripEntity>>() {
        @Override
        public void onChanged(@Nullable final List<TripEntity> trips) {
            tripCount = trips.size();
            Log.v("BaseActivity","tripCount: " + tripCount);
        }
    });
}

(3) Getter method for class A:

public int getTripCount() {
    return this.tripCount;
}

(4) Class B is extending class A and is trying to access the tripCount variable/value in the following way:

tripCount2 = super.getTripCount();
Log.v("TripActivity","tripCount: " + tripCount2);

The log is showing that tripCount2 from class B is 0 and tripCount from class A is > 0. Is there something wrong with my implementation here?

I found the answer to my question.

Instead of using the getter and setter methods, I made the tripCount variable "protected" so that I could access it from the subclass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM