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.
Original Image Source by ColiN00B from Pixabay
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.
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.
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
<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.
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
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;
}
}
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 👨💻
You Can Follow Me @skyehi For More Like This And Others
Congratulations @skyehi! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)
Your next target is to reach 700 posts.
You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word
STOP
To support your work, I also upvoted your post!
Check out our last posts:
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord 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.
HTTP is in use instead of HTTPS and no protocol redirection is in place. Do not enter sensitive information in this website as your data won't be encrypted.
Read about HTTP unsafety: [1] [2]
_ Vote for our WITNESS to support this FREE service!
Thanks for the update I'll check it