gpt4 book ai didi

java - 尝试与 web3j (Android) 取得平衡,出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 19:51:51 26 4
gpt4 key购买 nike

努力让任何东西在android上的web3j中工作,尝试这个例子(我已经替换了token和addr),我使用的地址确实有一些rinkeby ETH。在手机上测试,当我加载此类/Activity 时,应用程序崩溃,代码位于 oncreate 方法中。在 list 中打开互联网权限,并在构建gradle中编译android web3j。

 Web3j web3 = Web3jFactory.build(new 
HttpService("https://rinkeby.infura.io/token"));

EthGetBalance ethGetBalance = null;
try {
ethGetBalance = web3
.ethGetBalance("addr",DefaultBlockParameterName.LATEST)
.sendAsync()
.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

BigInteger wei = ethGetBalance.getBalance();

错误

06-30 02:15:47.115 18904-18904/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.user.test, PID: 18904
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.user.test/com.test.user.test.balance}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2607)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1325)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5756)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.test.user.test.balance.onCreate(balance.java:43)
at android.app.Activity.performCreate(Activity.java:5619)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2512)

错误引用的第43行是我提交的代码中的最后一行代码。当我注释掉该行应用程序时,它不会崩溃,只会收到一些(我认为是全部)警告。

最佳答案

您的 ethGetBalance 返回空值。我认为您输入了无效地址。这就是为什么方法web3j.ethGetBalance 失败。使用有效地址尝试此操作。

    Web3j web3 = Web3jFactory.build(new HttpService("https://ropsten.infura.io/your-token"));

String strAddress="0x24b********************"; //strAddress is your wallet address
EthGetBalance ethGetBalance=
web3.ethGetBalance(strAddress,DefaultBlockParameterName.LATEST).sendAsync().get();

BigInteger wei = ethGetBalance.getBalance();

ethGetBalance.getBalance() 用于获取以 wei 为单位的以太币余额。要在您的钱包中获取实际代币,请使用此转换方法。

  java.math.BigDecimal tokenValue = Convert.fromWei(String.valueOf(wei), Convert.Unit.ETHER);
String strTokenAmount = String.valueOf(tokenValue);

关于java - 尝试与 web3j (Android) 取得平衡,出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51111084/

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