Android BillingClient多订阅按钮价格设置失败问题求助
问题分析与修复方案
核心问题
你的代码在设置按钮文本时存在两个致命问题,直接导致后续代码无法执行:
- 索引逻辑错误:三个按钮都使用
productDetails.get(0)获取产品信息,这本身不符合需求,应该分别对应第0、1、2个产品(周、月、年订阅)。 - 缺乏空值校验:没有判断
productDetailsList的长度、subscriptionOfferDetails是否为空,一旦某个环节返回空,调用get(0)会抛出NullPointerException或IndexOutOfBoundsException,导致回调代码中断,后续按钮的setText执行不到。
修复步骤
- 先校验计费请求结果:在回调中首先判断
billingResult是否成功,只有成功时才处理产品信息。 - 添加空值与长度校验:确保
productDetailsList的长度足够,且每个产品的subscriptionOfferDetails和定价信息不为空。 - 对应正确的产品索引:周按钮用索引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
相关产品推荐
相关产品推荐

