You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android BillingClient多订阅按钮价格设置失败问题求助

问题分析与修复方案

核心问题

你的代码在设置按钮文本时存在两个致命问题,直接导致后续代码无法执行:

  1. 索引逻辑错误:三个按钮都使用productDetails.get(0)获取产品信息,这本身不符合需求,应该分别对应第0、1、2个产品(周、月、年订阅)。
  2. 缺乏空值校验:没有判断productDetailsList的长度、subscriptionOfferDetails是否为空,一旦某个环节返回空,调用get(0)会抛出NullPointerException或IndexOutOfBoundsException,导致回调代码中断,后续按钮的setText执行不到。

修复步骤

  1. 先校验计费请求结果:在回调中首先判断billingResult是否成功,只有成功时才处理产品信息。
  2. 添加空值与长度校验:确保productDetailsList的长度足够,且每个产品的subscriptionOfferDetails和定价信息不为空。
  3. 对应正确的产品索引:周按钮用索引0,月按钮用索引1,年按钮用索引2。

修改后的onProductDetailsResponse代码

public void onProductDetailsResponse(
        @NonNull BillingResult billingResult,
        @NonNull List<ProductDetails> productDetailsList) {
    // 先判断计费请求是否成功
    if (billingResult.getResponseCode() != BillingClient.BillingResponseCode.OK) {
        Log.i(TAG, "获取产品信息失败: " + billingResult.getDebugMessage());
        return;
    }

    productDetails = productDetailsList;
    // 校验产品列表长度是否符合预期
    if (productDetails.size() < 3) {
        Log.i(TAG, "产品数量不足,无法设置所有按钮价格");
        return;
    }

    // 用工具方法安全设置每个按钮的价格
    setButtonPrice(oneWeekPurchaseButton, productDetails.get(0));
    setButtonPrice(oneMonthPurchaseButton, productDetails.get(1));
    setButtonPrice(oneYearPurchaseButton, productDetails.get(2));
}

// 新增工具方法,安全获取并设置价格
private void setButtonPrice(AppCompatButton button, ProductDetails details) {
    if (details == null) {
        button.setText("获取失败");
        return;
    }
    List<ProductDetails.SubscriptionOfferDetails> offerDetails = details.getSubscriptionOfferDetails();
    if (offerDetails == null || offerDetails.isEmpty()) {
        button.setText("无可用报价");
        return;
    }
    ProductDetails.PricingPhases pricingPhases = offerDetails.get(0).getPricingPhases();
    List<ProductDetails.PricingPhase> phaseList = pricingPhases.getPricingPhaseList();
    if (phaseList == null || phaseList.isEmpty()) {
        button.setText("无定价信息");
        return;
    }
    button.setText(phaseList.get(0).getFormattedPrice());
}

额外检查点

  • 确认Google Play后台中one_year_premuim_test(注意拼写:premuim应为premium)这个产品ID是否正确创建并发布,拼写错误会导致产品信息查询失败。
  • 可以在回调中添加异常捕获,方便排查问题:
try {
    // 原设置按钮的代码逻辑
} catch (Exception e) {
    Log.e(TAG, "设置价格时出错", e);
}

内容的提问来源于stack exchange,提问作者ttcreator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:25:23