The "ethGetBalance" method will return the balance of any given account. Pls see example below:
// connect to node
Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/
// send asynchronous requests to get balance
EthGetBalance ethGetBalance = web3
.ethGetBalance("0xAccountAddress", DefaultBlockParameterName.LATEST)
.sendAsync()
.get();
BigInteger wei = ethGetBalance.getBalance();
Here is my suggestions:
ERC20 token balance
Just to clarify, all ERC20 tokens have the same set of methods (ERC20 protocol). Now, there are two ways to accomplish your task:
- use ERC20
balanceOf(address _owner)
method
// Get the account balance of another account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
Example:
first, create token instance
var tokenInst = web3.eth.contract(tokenABI).at(tokenAddress);
Then you can call methods of the token. For balance you should write the following:
tokenInst.balanceOf.call(address_to_check)
- use
balances
map if it is public.
// Balances for each account
mapping (address => uint256) balances;
Example is similar to previous:
first, create token instance
var tokenInst = web3.eth.contract(tokenABI).at(tokenAddress);
Then you can call methods of the token. For balance you can also write the following:
tokenInst. balances.call(address_to_check)
ETH balance
You want to use web3 balanceOf()
method.
Example:
web3.eth.getBalance(address);
Links:
web3ethgetbalance
Best Answer
@Luiz Soares Thank you for giving me the clue of the value being in WEI but solution provided didn't worked me.After some digging the documentation again got the solution
Convert.fromWei(ethGetBalance.getBalance().toString(), Unit.ETHER);