I am trying to make a decentralized android application. It is an online two player Tic-Tac-Toe game. I have implemented the back-end with solidity and a part of the front-end in android studio. More specifically, I got a wrapper class for my contract using solc and web3j, then included it in the android studio project. So I can call different functions of this wrapper class. Right now, a user can create an account and log in and create a game with this front-end. When a second player joins a created game, my contract emits an event to inform the creator that some player has joined the game. Besides, during a game, whenever a player makes a move, an event is emitted to let the other player know.

Now, the difficulty is that I don't know how to catch this event using Java. I have searched a lot about this, but did not find anything useful. Could anybody please explain how to do this or provide a link containing some example?


You can use the events methods exposed in the generated java wrappers.

Generate the Java wrappers

There are multiple ways to generate the wrappers like using the web3j-gradle-plugin, web3j-maven-plugin, web3j-cli...

For the web3j-gradle-plugin, you should add the following line to your build.gradle file:

plugins {
  id "org.web3j" version "4.8.4"

Then, put a solidity file containing some events under the src/main/solidity directory and run the generateContractWrappers Gradle task.

Now that you have the wrappers, you can either deploy the smart contract or load it.

Let's move on to how you can use them to get the events.

Use the wrappers to listen to events

If you check the generated wrappers, you will find two kinds of methods for each event:

  • get<event_name>Events(TransactionReceipt transactionReceipt) : This one can be used to fetch an event that was emitted in a certain transaction via providing its TransactionReceipt.
  • <event_name>EventFlowable(...) : And there are two overloads of this one, one that takes an org.web3j.protocol.core.methods.request.EthFilter and another one that takes couple org.web3j.protocol.core.DefaultBlockParameter.

If you choose the first one, then you will be able to fetch only the events that occurred in that specific transaction and will get them directly as a List< <event_name>EventResponse > containing the events.

For the latter, it will return a Flowable< <event_name>EventResponse >. You can use it to actually subscribe to the events, keep listening to them and also set callbacks same way you do with io.reactivex.Flowable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.