我按照官網的檔案說明查詢一個智能合約的情況。但我得不到想要的結果,這是我的代碼:
Web3j web3j = Web3jFactory.build(new HttpService(url));
List<Type> inputParameters = new ArrayList<>();
List<TypeReference<?>> outputParameters = new ArrayList<>();
Function function = new Function("getManufacturer",
inputParameters,
outputParameters);
String functionEncoder = FunctionEncoder.encode(function);
EthCall response = web3j.ethCall(
Transaction.createEthCallTransaction(contractAddress,
DefaultBlockParameterName.LATEST
).sendAsync().get();
List<Type> someType = FunctionReturnDecoder.decode(response.getValue(),function.getOutputParameters());
Iterator<Type> it = someType.iterator();
Type resault = someType.get(0);
String a = resault.toString();
Log.d("MainActitity", a + "111");
問題解答
web3j是很不錯的,不過需要多一點練習,你會發現它是一個很棒的通過java開發以太坊的API:
代碼有2個問題:
1.問題在代碼中的第三行。清單
outputParameters
應該包含方法的所有傳回變量。是以,如果你希望得到一個字元串,你應該這麼寫:
Arrays.asList(new TypeReference< Utf8String>() {})
2.但是,可能會有更有趣的發現,你甚至不必擔心編寫Java代碼來實作你的solidity功能,因為web3j可以做到這一點。
SolidityFunctionWrapperGenerator為你生成這些檔案。你所需要的智能合約的.bin和.abi,它們生成一個Java類。你可以用位址、web3j執行個體和
Credentials.java
來執行個體化該類。這樣,你就可以調用區塊鍊中的智能合約的方法,就像使用其他Java類一樣。。
原文《以太坊常見問題和錯誤》中的:
http://cw.hubwiz.com/card/c/ethereum-FAQ/1/1/15/另外推薦幾個很受歡迎全網稀缺的互動教程: