简体   繁体   中英

Memory leak issues in Fragment

I have implemented MVP pattern in my app. And I'm using WeakReferences to store View's reference in my Presenter. But still my fragments are not being claimed by GC upon destroying. Below is the screenshot of problem. Any idea what is causing this and how to remove this issue?

Android Profiler屏幕截图

Below is the code for my Presenter:

public class ProductDetailPresenter implements ProductDetailContract.Presenter {

private final WeakReference<ProductDetailContract.View> view;
private CategoriesDataSource repo;

public ProductDetailPresenter(ProductDetailContract.View view, CategoriesDataSource repo) {
    this.view = new WeakReference<>(view);
    this.repo = repo;
    view.setPresenter(this);
}

@Override
public void start() {

}

@Override
public void submitRating(final Product product, final float mRating) {
    final ProductDetailContract.View view =ProductDetailPresenter.this.view.get();

    if (view != null) {
        repo.submitRating(product.getId(), mRating, true, new CategoriesDataSource.SubmitRatingCallback() {

            @Override
            public void onRatingSubmitted() {

                product.setRating(mRating);
                product.setRated(true);
                product.setUpdatedAt(new Date(System.currentTimeMillis()));
                repo.updateProductInDB(product);

                if (!view.isActive()) return;

                view.onRatingSubmitted(true, mRating);
            }

            @Override
            public void onError(Throwable throwable) {
                if (!view.isActive()) return;

                view.onRatingSubmitted(false, 0);
            }
        });
    }
}

@Override
public void onRateKarenClicked() {
    ProductDetailContract.View view = this.view.get();
    if (view != null) {
        view.openDialog();
    }
}

@Override
public void onAbhiKhareediyeClicked(Product product) {

    EventBus.getDefault().post(
            new ProductDetailContract.ContractEventMessages(
                    ProductDetailContract.ContractEventMessages.EVENT_START_QUANTITY_SCREEN, product));

}

}

This is the problem:

    @Override
    public void submitRating(final Product product, final float mRating) {
       final ProductDetailContract.View view =ProductDetailPresenter.this.view.get(); <-- this is bad

you have a final object that is being passed to the repo. Delete the whole line. You don't need it. Use in the view.get() inside the onRatingSubmitted and onError

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