片段中的内存泄漏问题

时间:2018-07-03 08:29:37

标签: java android memory-leaks android-profiler

我已经在我的应用中实现了MVP模式。我正在使用WeakReferences将View的引用存储在Presenter中。但是我的碎片仍然没有被GC销毁。下面是问题的屏幕截图。知道是什么原因造成的,以及如何消除此问题吗?

Screenshot of Android Profiler

以下是我的演示者的代码:

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));

}

}

1 个答案:

答案 0 :(得分:0)

这是问题所在

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

您有一个最终对象正在传递到存储库。删除整行。不用了在onRatingSubmitted和onError内部的view.get()中使用