gpt4 book ai didi

java - Fragment中的内存泄漏问题

转载 作者:太空宇宙 更新时间:2023-11-04 10:21:13 25 4
gpt4 key购买 nike

我已经在我的应用程序中实现了 MVP 模式。我使用 Wea​​kReferences 将 View 的引用存储在我的 Presenter 中。但我的 fragment 在销毁时仍然没有被 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));

}

}

最佳答案

这就是问题:

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

您有一个正在传递到存储库的最终对象。删除整行。你不需要它。在view.get()里面使用onRatingSubscribed和onError

关于java - Fragment中的内存泄漏问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51149963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com