create account

How To Build An Ohm's Law Calculator Android App - Hive Programmers by skyehi

View this thread on: hive.blogpeakd.comecency.com
· @skyehi ·
$2.24
How To Build An Ohm's Law Calculator Android App - Hive Programmers
Greetings to my favorite Science community online, StemSocial.

It's @skyehi and I'm happy to be back. Yesterday was kind of like an off day for me so I couldn't work on another episode on my series, Android App Development Tutorials for beginners.

I had a couple of science and programmer friends come over and we discussed a whole lot of stuff. One friend of mine, Kevin brought up the subject of Ohm's law and we wanted to discuss it.

Although I was a little rusty on the subject of physics because it's been quite a while, I contributed fairly well to the conversation.

It inspired me to share this episode with you where I teach on how to build an Ohm's law calculator App for Android.

I'm super excited to be adding some deep physics laws to my series. 


![Polish_20240115_131026914.jpg](https://files.peakd.com/file/peakd-hive/skyehi/23wWuAeFEtyp4yzhHPsEtHnSWL1H8hDx3gFQy3PLbGdK4G6VCEoW422Bcoe9TeYXirwsJ.jpg)[Original Image Source](https://pixabay.com/photos/lightbulb-idea-creativity-base-3104355/) by ColiN00B from Pixabay


![YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png](https://files.peakd.com/file/peakd-hive/skyehi/23swrbKc3yjMYSUJMwmHkXUC71AufZXrkQ315XAST7nXzaKhpkvsAScnV3nBnpS55SJ2r.png)



> For those that are a bit unfamiliar with the Ohm's law 

- The Law states that the current flowing through a conductor between two points is directly proportional to the voltage across the two points and inversely proportional to the resistance.

Here's the formula that expresses the Law. 

\[ V = I \times R \]

where:
- \( V \) represents Voltage,
- \( I \) represents Current,
- \( R \) represents Resistance

Now guys in an event where you want to calculate the Voltage, Current or Resistance of a conductor using the Ohm's law, you can totally rely on this App. 

Understanding the basics of Ohm's Law is very important for anyone dealing with electronics. If you're an electrical engineer, you should definitely be familiar with this particular law. 

- I dedicate this particular episode to @stemsocial , my favorite science community on the Hive Blockchain.

> I hope you're ready for this episode, let's get started with our work for the day. 


![2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png](https://files.peakd.com/file/peakd-hive/skyehi/EoAYDi9ZKfkBZi7rMWbojnS8KytoTpbSepvPmfeZmL2V2h8FDZ3xRpC58MZDkf1LeRQ.png)


### Prerequisites

For the benefit of newcomers to Android App development or my series, I'll share with you the required softwares you need to be able to go through with this tutorial.

- Android Studio IDE - the platform on which we'll develop this and all other Android Apps.

- Java Development Kit, JDK - You need to install JDK correctly on your PC for your PC to be able to execute Java commands or codes.

- Physical Android Device or Emulator - After building the App, we'll need to test it either on an emulator or a physical Android device.

If you have all these checked out, you're absolutely ready to go through with this tutorial 

---

### Creating A New Android Studio

We'll start our project by opening Android Studio and clicking on "Create A New Project". As we always do in this series, please select "Empty Activity" as the template of your App project.

When you're done selecting the template, click on the "Next" button and set both the App name and package name of your App.

> I'll call mine StemSocial Ohm's Law Calculator

You're totally free to name it with any relevant name guys.

Also ensure that Java is the selected programming language and not Kotlin.

When you're through with the project configuration, click the "Finish" button and wait while Android studio loads your new project space.


![YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png](https://files.peakd.com/file/peakd-hive/skyehi/23swrbKc3yjMYSUJMwmHkXUC71AufZXrkQ315XAST7nXzaKhpkvsAScnV3nBnpS55SJ2r.png)


### Designing our Ohm's law Calculator UI

Alright guys, it's time to work on the frontend or User Interface, UI of our App.

Our Ohm's Law Calculator will be designed to let the User input two of the variables of the law, to find the the missing variable.

For example, the user can input the Voltage and the Current, press the calculate button to see the results which would be the Resistance of the conductor using the Ohm's law logic.

This means in our user interface design, we need to include `EditText` elements for each of the variables, include a `Button` element to initiate the Calculation and a `TextView` element that would display the results. 

All of the user interface or frontend code will be written inside our `res/layout/activity_main.xml` file. So guys go ahead and open the XML file and let's start working on our design. 

> Here's how your design code should look like 
 
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editTextVoltage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Voltage (V)" />

    <EditText
        android:id="@+id/editTextCurrent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextVoltage"
        android:layout_marginTop="16dp"
        android:hint="Current (I)" />

    <EditText
        android:id="@+id/editTextResistance"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextCurrent"
        android:layout_marginTop="16dp"
        android:hint="Resistance (R)" />

    <Button
        android:id="@+id/btnCalculate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/editTextResistance"
        android:layout_marginTop="16dp"
        android:text="Calculate" />

    <TextView
        android:id="@+id/textViewResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnCalculate"
        android:layout_marginTop="16dp"
        android:text="Result: "
        android:textStyle="bold" />

</RelativeLayout>
```

Of course guys you're free to improve on the design to suite your preference but the basic elements I showed you should be present in your user interface design.


![YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png](https://files.peakd.com/file/peakd-hive/skyehi/23swrbKc3yjMYSUJMwmHkXUC71AufZXrkQ315XAST7nXzaKhpkvsAScnV3nBnpS55SJ2r.png)


### Implementing The Logic of our Code 

It's time to work on the backend or logic of our code. The logic code will be written inside our `MainActivity.java` file. 

We'll work on handling user interactions with all the `EditText` elements we included, and the button. 

We have to initialize them and then include a `setOnClickListener` method or function for our button to start the calculation. 

For the formula of the Ohm's law calculator, we need to create a `Double` variable for each Ohm's law variable which includes the Current, Voltage and Resistance. 

After creating the variable, I created an `If` function to check if at least two of the variables are present because we would need at least two of the Ohm's law variable to be present to use the Ohm's Law formula. 

After doing this, we insert whichever variable that the user included. So if the user gave an input for Resistance and Current, after clicking the button, we'll have the voltage value.

After implementing the logic code, we would create another `String` variable that will hold the results and have it displayed inside the `TextView` we created in our design layout.

That's all guys, it's going to be a marathon code so get ready for the logic cide 

> Here's how your logic code should look like guys


```java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    EditText editTextVoltage, editTextCurrent, editTextResistance;
    Button btnCalculate;
    TextView textViewResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextVoltage = findViewById(R.id.editTextVoltage);
        editTextCurrent = findViewById(R.id.editTextCurrent);
        editTextResistance = findViewById(R.id.editTextResistance);
        btnCalculate = findViewById(R.id.btnCalculate);
        textViewResult = findViewById(R.id.textViewResult);

        btnCalculate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                calculateOhmsLaw();
            }
        });
    }

    private void calculateOhmsLaw() {
        // Extract values from EditText fields
        double voltage = parseEditText(editTextVoltage);
        double current = parseEditText(editTextCurrent);
        double resistance = parseEditText(editTextResistance);

        // Check if at least two values are provided
        if (countProvidedValues(voltage, current, resistance) < 2) {
            textViewResult.setText("Provide at least two values.");
            return;
        }

        // Calculate the missing value using Ohm's Law
        if (Double.isNaN(resistance)) {
            resistance = calculateResistance(voltage, current);
        } else if (Double.isNaN(current)) {
            current = calculateCurrent(voltage, resistance);
        } else if (Double.isNaN(voltage)) {
            voltage = calculateVoltage(current, resistance);
        }

        // Display the result
        String resultText = String.format("Result: V = %.2fV, I = %.2fA, R = %.2fΩ", voltage, current, resistance);
        textViewResult.setText(resultText);
    }

    private double parseEditText(EditText editText) {
        String text = editText.getText().toString().trim();
        return text.isEmpty() ? Double.NaN : Double.parseDouble(text);
    }

    private int countProvidedValues(double... values) {
        int count = 0;
        for (double value : values) {
            if (!Double.isNaN(value)) {
                count++;
            }
        }
        return count;
    }

    private double calculateResistance(double voltage, double current) {
        return voltage / current;
    }

    private double calculateCurrent(double voltage, double resistance) {
        return voltage / resistance;
    }

    private double calculateVoltage(double current, double resistance) {
        return current * resistance;
    }
}
```


![2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png](https://files.peakd.com/file/peakd-hive/skyehi/EoAYDi9ZKfkBZi7rMWbojnS8KytoTpbSepvPmfeZmL2V2h8FDZ3xRpC58MZDkf1LeRQ.png)


### Congratulations

Congratulations guys, you have successfully built your very first Ohm's Law Calculator App for Android devices.

It's time to run the App. As always you can run it using either an emulator or a physical Android device. 

When your App launches, start by inputting two of the  electrical values  or variables, Voltage, Current or Resistance into the Ohm's Law Calculator app. 

When you're done, tap or press the "Calculate" button  to start the calculations. The results will be displayed inside the `TextView`

That's it guys, I hope you enjoyed this particular episode. Thank you so much for reading, stay tuned for more.

> Have A Great Day And Catch You Next Time On StemSocial. Goodbye 👨‍💻

<center>
You Can Follow Me @skyehi For More Like This And Others 
</center>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 137 others
properties (23)
authorskyehi
permlinkhow-to-build-an-ohms-law-calculator-android-app-hive-programmers
categoryhive-196387
json_metadata{"app":"peakd/2023.11.3","format":"markdown","tags":["health","stemng","stemgeeks","neoxian","waivio","cent","proofofbrain","chessbrothers","alive","stemsocial"],"users":["skyehi","stemsocial","Override"],"image":["https://files.peakd.com/file/peakd-hive/skyehi/23wWuAeFEtyp4yzhHPsEtHnSWL1H8hDx3gFQy3PLbGdK4G6VCEoW422Bcoe9TeYXirwsJ.jpg","https://files.peakd.com/file/peakd-hive/skyehi/23swrbKc3yjMYSUJMwmHkXUC71AufZXrkQ315XAST7nXzaKhpkvsAScnV3nBnpS55SJ2r.png","https://files.peakd.com/file/peakd-hive/skyehi/EoAYDi9ZKfkBZi7rMWbojnS8KytoTpbSepvPmfeZmL2V2h8FDZ3xRpC58MZDkf1LeRQ.png"]}
created2024-01-15 13:59:12
last_update2024-01-15 13:59:12
depth0
children4
last_payout2024-01-22 13:59:12
cashout_time1969-12-31 23:59:59
total_payout_value1.108 HBD
curator_payout_value1.135 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length12,469
author_reputation103,283,026,686,970
root_title"How To Build An Ohm's Law Calculator Android App - Hive Programmers"
beneficiaries
0.
accountstemsocial
weight500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,498,984
net_rshares5,377,843,618,776
author_curate_reward""
vote details (201)
@hivebuzz ·
Congratulations @skyehi! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

<table><tr><td><img src="https://images.hive.blog/60x70/http://hivebuzz.me/@skyehi/posts.png?202401151123"></td><td>You published more than 650 posts.<br>Your next target is to reach 700 posts.</td></tr>
</table>

<sub>_You can view your badges on [your board](https://hivebuzz.me/@skyehi) and compare yourself to others in the [Ranking](https://hivebuzz.me/ranking)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>


To support your work, I also upvoted your post!


**Check out our last posts:**
<table><tr><td><a href="/hive-122221/@hivebuzz/lpud-202401"><img src="https://images.hive.blog/64x128/https://i.imgur.com/pVZi2Md.png"></a></td><td><a href="/hive-122221/@hivebuzz/lpud-202401">LEO Power Up Day - January 15, 2024</a></td></tr></table>
properties (22)
authorhivebuzz
permlinknotify-skyehi-20240115t142908
categoryhive-196387
json_metadata{"image":["http://hivebuzz.me/notify.t6.png"]}
created2024-01-15 14:29:09
last_update2024-01-15 14:29:09
depth1
children0
last_payout2024-01-22 14:29:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length945
author_reputation369,434,232,474,027
root_title"How To Build An Ohm's Law Calculator Android App - Hive Programmers"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,499,776
net_rshares0
@keys-defender ·
kid no unsafe links
  <div class="pull-right">
  <img src="https://cdn.steemitimages.com/DQmeHxGH67uYFvPfd76LGms358u21JRfqGFim6GN2CF5Dc4/image.png"> &nbsp; &nbsp; &nbsp;
  </div>
  <div class="phishy">
  It looks like this post contains a link that does not use a secure protocol:
  <a href="https://peakd.com/hive-192847/@keys-defender/new-features-extended-phishing-protection">http://schemas.android.com/apk/res/android</a>
  </div> 
  <sub><br>HTTP is in use instead of HTTPS and no <a href="https://geekflare.com/http-to-https-redirection/">protocol redirection</a> is in place.</sub>
  <sub>
  Do not enter sensitive information in this website as your data won't be encrypted.
  </sub>
  <br><br><div class="pull-left">
  <sub><a href="https://peakd.com/hive-192847/@keys-defender/new-features-extended-phishing-protection">[More info on this free service]</a></sub>.
  <br><sub>Read about HTTP unsafety: &nbsp; <a href="https://whynohttps.com">[1]</a> &nbsp; <a href="https://web.dev/why-https-matters">[2]</a></sub><br>
  </div>
  <div class="pull-right">
    <div class="pull-right"><sub>{Current avg of HTTP links in Hive post/comments: 162.3/h}</sub></div>
    <div class="pull-right">
  Auto-reply  throttled 1/20 to reduce spam. If it still bothers you, reply "OFF  HTTP".
  </div><br><br>
  <div class="pull-left">
  <sub>Service sponsored by @cryptoshots.nft, 🔫 3D Shooter on Hive</sub>
  <br>_ <sub><a href="https://vote.hive.uno/@keys-defender">Vote for our <b><u>WITNESS</u></b> to support this FREE service!</a></sub>
  </div>
properties (22)
authorkeys-defender
permlinkantiunsafelinks-keys-defender-bot-1705711181975
categoryhive-196387
json_metadata{"tags":["unsafelinks"],"app":"hivejs/kd"}
created2024-01-20 00:39:42
last_update2024-01-20 00:39:42
depth1
children1
last_payout2024-01-27 00:39:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,527
author_reputation91,066,318,315,499
root_title"How To Build An Ohm's Law Calculator Android App - Hive Programmers"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,620,268
net_rshares0
@skyehi ·
Thanks for the update I'll check it
👍  
properties (23)
authorskyehi
permlinkre-keys-defender-2024120t94454641z
categoryhive-196387
json_metadata{"type":"comment","tags":["hive-196387","unsafelinks"],"app":"ecency/3.0.44-mobile","format":"markdown+html"}
created2024-01-20 09:44:03
last_update2024-01-20 09:44:03
depth2
children0
last_payout2024-01-27 09:44:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length35
author_reputation103,283,026,686,970
root_title"How To Build An Ohm's Law Calculator Android App - Hive Programmers"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,627,770
net_rshares3,741,976,856
author_curate_reward""
vote details (1)
@stemsocial ·
re-skyehi-how-to-build-an-ohms-law-calculator-android-app-hive-programmers-20240115t204322412z
<div class='text-justify'> <div class='pull-left'>
 <img src='https://stem.openhive.network/images/stemsocialsupport7.png'> </div>

Thanks for your contribution to the <a href='/trending/hive-196387'>STEMsocial community</a>. Feel free to join us on <a href='https://discord.gg/9c7pKVD'>discord</a> to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support.&nbsp;<br />&nbsp;<br />
</div>
properties (22)
authorstemsocial
permlinkre-skyehi-how-to-build-an-ohms-law-calculator-android-app-hive-programmers-20240115t204322412z
categoryhive-196387
json_metadata{"app":"STEMsocial"}
created2024-01-15 20:43:21
last_update2024-01-15 20:43:21
depth1
children0
last_payout2024-01-22 20:43:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length545
author_reputation22,927,767,309,334
root_title"How To Build An Ohm's Law Calculator Android App - Hive Programmers"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id130,508,562
net_rshares0