Ethereum Blockchain in Android Studio Using Web3j.

Image by author

In this article, we will deploy a quiz smart contract on the Ethereum Goerli Testnet. The main focus is to learn how we can deploy and interact with a smart contract on the Ethereum blockchain.

Disclaimer: Keep your hands away from keyboard while reading this article, only start coding once you’ve understood what’s happening here because it’s a bit complex topic.

You will learn the following 6 essential steps to create a DAPP.

  1. Install Web3j & Solc library.
  2. Write a Smart Contract using Remix IDE.
  3. Generate Abi & Bin files of Solidity Smart Contract.
  4. Generate Java class using Abi & Bin files.
  5. Deploy Smart Contract.
  6. Interact With the Deployed Smart Contract.

Before jumping into installations and development, let's first create an account on alchemy. After login you will see a demo app HTTPS URL, most probably it’ll be the Goerli network. If you want to use any other chain you can create a new key with that specified chain . we need this url to connect to a test blockchain(Rinkeby, Goerli, Mumbai… etc).

1. Install Web3j & Solc

Solc is a solidity compiler. To install solc run

npm install -g solc

To check solc version run:

solcjs --version

Web3j is a highly modular, reactive, type-safe Java and Android library for working with Smart Contracts and integrating with clients (nodes) on the Ethereum network.

To install web3j run the following command on Powershell.

Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/web3j/web3j-installer/master/installer.ps1'))

To check web3j version run:

web3j --version

2. Write a Smart Contract using Remix IDE

Smart Contracts are the backbone of decentralized apps. Your smart contracts must be public so the users can see the transperence. Open Remix IDE and paste the following code, you can smart contract in Remix since solidity and testing are out of the scope of this article so I won’t talk about it.

Here’s your smart contract in which the code is self-explanatory.

Quiz.sol

3. Generate Abi & Bin files of Solidity Smart Contract:

Once the smart contract is written now it’s time to generate the abi and bin files of this contract which will be used to generate a java class of this smart contract.

To generate abi & bin files, run the following command in your cmd

solcjs <contract>.sol --bin --abi --optimize -o <output-dir>/

My command looks like this

solcjs Quiz.sol --bin --abi --optimize -o C:\Users\Hp\AndroidStudioProjects\QuizDaap\app\src\main\java\com\example\quizdpp

After running this command successfully, you will see abi and bin file at your provided path in my case its: (C:\Users\Hp\AndroidStudioProjects\QuizDapp\app\src\main\java\com\example\quizdapp)

4. Generate Java class using Abi & Bin files.

Since we have Abi & Bin files of our smart contract, now we are good to generate Java file using web3j library which we installed earlier, so we can call solidity smart contract methods in android studio.

To generate java file run the following command in cmd.

web3j generate solidity -b /path/to/<smart-contract>.bin -a /path/to/<smart-contract>.abi -o /path/to/src/main/java -p com.your.organisation.name

My command looks like this

web3j solidity -b=Quiz_sol_Quiz.bin -a=Quiz_sol_Quiz.abi -p com.example.shoaibsmartcontract -o C:\Users\Hp\AndroidStudioProjects\QuizDapp\app\src\main\java\com\example\shoaibsmartcontract

After running this command successfully, you will see a new Java file Quiz_sol_Quiz.java in your output directory path.

Note: Till date (25-sept-2022) Web3j does not convert struct written in our solidity file to java. We have to do that manually.

In our smart contract, we have a struct Question. we need to convert that struct into a java class manually.

Question.java

Import the above Question in your Quiz_sol_Quiz.java.

Till now you should have the following files

  1. Question.java
  2. Quiz.sol
  3. Quiz_sol_Quiz.java
  4. Quiz_sol_Quiz.abi
  5. Quiz_sol_Quiz.bin

5. Deploy Smart Contract:

Sor far we have written our smart contract and have also converted it into java.

Don’t forget to add Internet permission in your AndroidManifest.xml.

Now let’s deploy it on Ethereum Goerli Testnet. To do that add web3j library in build.Gradle.

implementation("org.web3j:core:4.8.7-android") {
because("Web3j is a lightweight, highly modular, reactive, type safe Java and Android library for working with Smart Contracts and integrating with Ethereum network")
}

To deploy it we need to first connect with our Goerli Testnet, for that we will use the link given by Alchemy, it will be different in your case but the mine will also work for you

val web3j =
Web3j.build(HttpService("https://eth-goerli.g.alchemy.com/v2/zXC-cavYVle3qt-JvQXtjKxqznhYWIWY"))

Once we are connected with it, now we can deploy our smart contract using .deploy() the method.

val contractAddress =
Quiz_sol_Quiz.deploy(web3j, credentials, gasProvider).send().contractAddress

.deploy().send().contractAddress returns the address of the smart contract where it is deployed. we will save this address so that we can interact with our smart contract later.

My function to deploy a smart contract inside QuizViewModel.kt looks like this.

fun deploySmartContract(credentials: Credentials) {
viewModelScope.launch {
withContext(Dispatchers.IO) {
try {
val web3j =
Web3j.build(HttpService(Constants.GOERLI_TESTNET))
val contractAddress =
Quiz_sol_Quiz.deploy(web3j, credentials, gasProvider).send().contractAddress
_contractAddress.postValue(contractAddress)
} catch (e: Exception) {
_contractAddress.postValue("-1")
Log.d(TAG, "deploySmartContract: Exception: ${e.message}")
}
}
}
}

We need to call deploySmartContract() the function in our DeployContractActivity.

quizViewModel.deploySmartContract(getCredentialsFromPrivateKey())private fun getCredentialsFromPrivateKey(): Credentials {
val privateKey = "5ab6b0e9ff7d33b1c3e269f285c2eaa76cefe8725eef2e6ae8bfb257749e7b4c"
return Credentials.create(privateKey)
}

You should add your own private key in getCredentialsFromPrivateKey() which returns Credentials(web3j class).

DeployContractActivity.kt looks like this

After deploying the smart contract successfully you can see it on goerli.etherscan.io

https://goerli.etherscan.io/address/{YourDeployedContractAddress}

In my case it’s

https://goerli.etherscan.io/address/0x8a78bae2e518daf647ff407da88315ba2cde18a8
Deployed Contract Address

Once our smart contract is deployed now we can interact with it. Make sure you save the contract address because .load() the function which is used to load the smart contract requires the contract address.

6. Interact With the Deployed Smart Contract:

The smart contract is useless if you are not interacting with it, which means what’s the purpose of deploying a smart contract if you are fetching or altering its data?

To interact with a deployed smart contract Web3j generates a .load() function in our contract java class.

So I wrote the following loadSmartContractData()function which takes credientals and deployedContractAddress as params.

fun loadSmartContractData(credentials: Credentials, deployedContractAddress: String) {
viewModelScope.launch {
withContext(Dispatchers.IO)
{
try {
val web3j =
Web3j.build(HttpService(Constants.GOERLI_TESTNET))
val quiz =
Quiz_sol_Quiz.load(deployedContractAddress, web3j, credentials, DefaultGasProvider.GAS_PRICE, DefaultGasProvider.GAS_LIMIT)
Log.d(TAG, "loadSmartContractData: Is Contract Valid: ${quiz.isValid}")
val questions = quiz.questions.send() as ArrayList<Question>
_questions.postValue(questions)
} catch (e: Exception) {
Log.d(TAG, "loadSmartContractData: Exception: ${e.message}")
}

}
}
}

In the above code I first created a connection with Ethereum Goerli Blockchain using web3j.build()on which contract is deployed then I called .load() function and provided it the contract address of my already deployed contract address.

Here quiz.questions.send() returns an ArrayList of type Question.

My entire QuizViewModel() looks like this

Call loadSmartContract() after the smart contract is deployed in MainActivity.kt.

My MainActivity.kt looks like this

Congrats! if you have followed all the steps you will get the Arraylist of questions from our smart contract.

Code is available at GitHub: https://github.com/ShoaibKakal/Quiz-Dapp

Quiz Dapp

Hurrah! You have created your first (ig) decentralised app.

To learn more about the deployment of smart contracts in Android Studio read the below article.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store