javabigintegerweb3-java

BigInteger throws numberFormatException


Edit: Resolved the issue with below code:

    String tokenId="0x1800000000001289000000000000000000000000000000000000000000000000";

    BigInteger token1;
    if (tokenId.startsWith("0x")){
        token1=new BigInteger(tokenId.substring(2),16);

I have a long String that I need to assign as BigInteger and pass it to another method of Web3j library. However, I keep receiving number format exception. Any help on this ?

Below is the method throwing exception:

public void getBalance1155(String walletAddress) throws ExecutionException, InterruptedException {

    //define constant values

    Web3j web3j=Web3j.build(new HttpService("https://mainnet.infura.io/v3/<apiKey>>"));
    String contractAddress = "0xfaaFDc07907ff5120a76b34b731b278c38d6043C";
    BigInteger tokenId=new BigInteger("0x1800000000001289000000000000000000000000000000000000000000000000",16);
    NoOpProcessor processor = new NoOpProcessor(web3j);
    Credentials credentials = Credentials.create("privatekey");
    TransactionManager txManager = new FastRawTransactionManager(web3j, credentials, processor);

    //Query Blockchain to get balance of WALLETADDRESS from Contract for given TokenID

    ERC1155 token = ERC1155.load(contractAddress, web3j, txManager, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT);
    RemoteCall<BigInteger> sendCall = token.balanceOf(walletAddress, tokenId);
    BigInteger balance=sendCall.sendAsync().get();
    log.info("balance >>>>>> " +balance);
}

Here's the Exception:

java.lang.NumberFormatException: For input string: "0x1800000000001289000000000000000000000000000000000000000000000000" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Long.parseLong(Long.java:692) at java.base/java.lang.Long.parseLong(Long.java:817)


Solution

  • As you are already using web3j you can use Numeric.decodeQuantity("0x1800000000001289000000000000000000000000000000000000000000000000") this decode the hexideimal into a BigInteger