How to make a calculator in Android Studio 2020 | Part 3
HTML-код
- Опубликовано: 9 авг 2020
- In this video, learn how to make a calculator in Android Studio using Java. This calculator will be able to perform many functions like calculating exponentials, basic arithmetic, and you will also be able to use parentheses. All of this will be made possible through the use of a math parser called Mxparser. You will learn how you can download the Mxparser library and use it in your Android Studio projects.
We will be covering some of the core functions and techniques used for app development in Android Studio. This tutorial is designed for beginners trying to get started in app development with Android devices being the primary target.
Android Studio is a great platform for creating apps that can be deployed on the google play store. If you're new to the series I'd go and check out the Android Studio Playlist. There you will be able to see how to create basic apps so you can become a developer.
Join the Discord Server!!!
/ discord
Check out the Android development playlist for more videos like this!
• Android App Developmen...
How to make a calculator in Android Studio 2020 | Part 1
• How to make a calculat...
#androidstudio #appdevelopment #PracticalCoding Хобби
more efficient way to learn instead of watcing 20++ hours tutorials.
Thanks!
Glad you found the videos helpful
Waiting for the next!
you're way is awesome and your voice is great, i really hope you do a complete course for android development
Thanks! I'm glad you're liking the videos. Should be posting some more videos again soon
I really dont understand y dis Channel has so less number of subs. I hb seen literally dumb channels that deliver nothing and still hv subs in K. This series here was genuinely informative, very lucid and well presented. Looking forward for more such content.🔥
That's really good to hear! Glad you enjoyed the calculator series
I recently made my first simple calculating Android app using MIT app developer. Now I'm here to learn how to make it the proper way and this channel really presented it so well .
I can watch your videos all day keep going.
Glad to hear you're linking the videos!
Very good series!!, please stay around !!
Glad you liked it! I just finished up finals week. I'll be posting more videos soon
Thank you so much sir!
For all those who are facing issue white using the updateText function-> Just use double quotes first inside bracket/parenthesis, and the parameter strToAdd automatically appeared. You don't have to explicitly write "strToAdd" inside the function updateText.
I am only starting to learn android app development using Java I am not really sure of the conventions. Thank you for these videos for explaining the entire process of how to create an Android app with real life example. I was wondering why you are using the display.setOnClickListener(){}. Isn't it possible to create separate methods outside the onCreate(){} as public void EdtTxt(View v) {} and write the code inside this. Then in the activity_main.xml file we can use the attribute android:onClick="EdtTxt".
Thanks a lot!
very good i am java programer but this is way bether and much dificult...i lik it you good eplainer...i try to learn it...
Thanks! Happy to hear you're liking the videos
It’s amazing ❤
Thanks! I'm glad you're enjoying the series.
Hi, I'm new to programming and I really appreciate the tutorial, I'm learning a lot of new things and for me it's worked really really well. I am truly amazed you have as little subs as you do.(One more though!).
I was wondering if at min 20 you have to use this complicated for loop system with the super long methods, isn't it possible to instead make the program alternate between ( and ). I tried it and it seems to work, I did as follows:
Right after the line where you declare the Mainactivity class I declared a new int variable and set it to equal 0, I think you can't do this within the method itself because otherwise the value will be initialized to 0 every time you press the parentheses button and therefore only give ( brackets:
int counterNum = 0;
Then within the parentheses method I added the following code:
public void parenthesesBTN(View view){
if (counterNum % 2 == 0){
updateText("(");
counterNum++;
} else {
updateText(")");
counterNum++;
}
}
I'm not sure if this would for some reason crash though! I'd love to hear your thoughts. And once again awesome series!
Glad to hear that you're liking the videos! I remember when I was first making this app, I used the exact same logic that you put in your comment. There's nothing wrong with it, but you'll never be able to put in 2 opening parentheses using that logic. For example, you could never place in an expression like ((3-5)*6)+4. The moment you click an opening parentheses, the next one will always be a closing one. I'm sure there's a way to make the code I wrote for the parentheses simpler, I just haven't looked at it in a while.
Please add more tutorials.:>
thanks for the video. I think +/- button and point button have not been covered in the video
Amazing video! I hope someone could help me…if I try to set the mainactivity, the zeroBTN doesn’t appear…
Wait for your next video
Yeah the last one took a while to get out. The next video should be out soon though
You can use hint to show "enter the value"
This project contains Java compilation errors, which can cause rendering failures for custom views. Fix compilation problems first.
What do I have to do to fix this problem?
hi tech...i hope your doing well...i didn't understand the substring can you pleas explain it a little more
When i assigned the on click to the buttons I got errors for all of them and it says “using ‘android:onClick’ on older version of the platform is broken”
Hello does anyone know how to prevent typing of multiple operands like +++1 or 1+***** something like that with this code ty
hey practical coding first of all thank you fir this course I have learnt al to from this series and I am facing some issues in the backspacebutton backend logic
public void backspaceBTN(View view){
int cursorPos = display.getSelectionStart();
int textLen = display.getText().length();
if (cursorPos != 0 && textLen != 0) {
SpannableStringBuilder selection = (SpannableStringBuilder) display.getText();
selection.replace(cursorPos - 1, cursorPos, tb:"" );
display.setText(selection);
display.setSelection(cursorPos - 1);
}
}
in the above section there is this sixth line of selection.replace if I write the code it is showing ""cannot resolve syumbol''tb"
it is not recognising the
please help me with that
are you typing tb? if so dont... just type in the double quotes and whatever appears before the quotes gets put automatically in code.
6:29 just like a BookMark! ;-)
sir why when im typing public void, the word void suddenly changes to fun?
9:30 how did you do it?
Hi, this is one of the best tutorials I found.
I've a problem though. Whenever I click the parentheses button, my app crashes. Can you please help ??
Thanks! Glad you're liking the videos. Someone not too long ago had the same issue. Can you put the code you're using for the parentheses in a comment so I can take a look at it?
If anyone else is having an out of range error when adding parens using Kotlin, make sure your for loop reads "for (i in 0..cursorPos -1)" so the range is non-inclusive of the cursor's position index. :). Also thank you for these tutorials!!
@@paintmylittleworld4367 No problem, glad you like them!
Need help there's an error when i type the updateText(strToAdd: "0");
It says that ')' expected in the project errors
I already checked everything but i still got the errors
Thank you for the great and simple tutorial!👍 I've got just one thing to ask: how to remove ".0" after an integer value in a result view? Thanks in advance!
You'll need to add some extra logic in the calculate method for the button click. After the expression is returned from mXparser, you should be able to create a new string without the ".0". Or you can use a StringBuilder to "modify" the string and update the EditText with that value instead. I'd try making a private method that returns a string and takes in a string to "modify".
@@PracticalCoding thanks for your fast reply! I really appreciate your help! So I'll try to make it that way 👍
Great tutorial, really enjoyed it, I am just facing an issue where my buttons are not clickable when I run the program, any idea why?
There could be a ton of reasons for this. Could you paste the error message that's displayed in the run tab towards the bottom of Android Studio?
@@PracticalCoding there is literally no error, I just cant click the buttons.
@@oreki.1889 Okay. I just wanna make sure you did a few things. Are the methods you created for each of the buttons public and did you link those methods to the correct button? Some other things you might want to check for is in the updateText method. Make sure everything in there is written correctly.
Trying to solve something like this in the RUclips comment section is a little difficult so if you could join the Discord server and post some pictures or a video of what's happening that'll really help too
Here's the link
discord.gg/H2P89STbaS
how u used "strTOAdd" for public functions even when tht was the variable tht is used privately?
We can use a private method in a public method because they're both within the same class. All of the methods in our class where we created the private strToAdd method have access to it. A method created in a different class, for example, would not be able to use the strToAdd method.
while setting onclicklistener, single clicking on the edit text doesnt emptying the text instead need to click again. is that normal ?
It should clear right away if you're talking about the text that is set by default in our EditText (I think it was "Enter a Value"). What I would do is add the hint attribute to the EditText in our XML file. I'm not sure why I didn't use this to begin with, but if you add this line into the EditText
android:hint="@string/nameOfYourString"
you won't need any of the code that clears the EditText when the user clicks on it. I'm making an updated version of this series that uses the hint attribute. If you wanna watch that series instead, just follow this link:
ruclips.net/video/1ssYYy8Li48/видео.html
@@PracticalCoding hey thanks :)
paranthesis is not working properly....what could be the reason
Hi the androidstudio version I have is 4.1 and whenever I try to use edittext it shows me a rendering problem help please
Hey, so there's a few things you can do to fix this. Probably the best thing you could do would be to watch my updated video series on how to make a calculator. Here's the link to the If you want to check it out:
ruclips.net/p/PLcSIMAULmMycI309W6uMMaQX1ePy8_1iV
But you can also go into your themes folder and you should find 2 XML files in there. you need to change the parent attribute in the style tag to this
Theme.AppCompat.Light.NoActionBar
You'll have to do it for each XML file. If that's a little confusing, I go over how to do it in the updated series
Hello,I was facing this problem could someone help
public void zeroBTN(View view) {
updateText( strToAdd:"0");
}
public void oneBTN(View view) {
updateText(strToAdd :"1");
}
public void twoBTN(View view) {
updateText(strToAdd :"2");
}
In these functions I am getting an error (Cannot resolve symbol 'strToAdd') in all of them although I have written the "updateText" function as it is...
Error is like strToAdd is in redcolor and system is recomending to add a local variable
Hello! There's a problem with my btns, it says "Use databinding or explicit wiring of click listener in code". What should I do? :O
Hey! I've never seen that error message before. Could you join the discord server and send a picture of the error message there? ( If you're not already a part of the server. Your name looks familiar)
Here's the link:
discord.gg/H2P89STbaS
Hello. I've been following your tutorial since part 1 and all the way to minute 10:00 of this video where I got stuck. For some reason why code doesn't recognise the StrToAdd Function when i type it under zeroBTN. Please i would like to know how i can resolve this.
Actually no need I've figured out the issue. you just click the zero after typing updateText(" ") not typing StrToAdd then trying to type the character ( Did anyone else have that issue or am i just an idiot?)
@@hydarnasiru2158 Nope, I also struggled with it for an embarrassingly long time, so either other people struggled as well with it, or we can be idiots together :D
@@speedyslothmeh5432 Omg I was also stuck on this, thanks
@@hydarnasiru2158 No my friend I was also stuck there. I just used double quotes first inside bracket/parenthesis, and the function strToAdd automatically appeared, you don't have to explicitly write "strToAdd" inside the function updateText.
for some reason my text does not disappear, does anyone have any idea why
Sir in my case
Whenever I press button there is no output in edit text view
Hey, can you put the code you're using the updateText method into a comment so I can take a look at it?
I am facing an error .. Which is that i can't see image button (backspace) on my device however it is present on the design.. Tell me about it
Huh. Can you join this channel's Discord server and maybe upload a picture of what's happening? Oh, and what version of Android Studio are you using?
Here's the link to the Discord server:
discord.gg/evK6jwg4Xj
can I know what programming language you have used, because I am a beginner, i am learning now only
Yeah, I used Java throughout this entire series. If you end up watching any of the other app tutorials I made, they use Java too
@@PracticalCoding ok,thank you
hey im getting NaN as a result of every expression what is this ???
Well it could be a few things. If you pass in an equation mXparser doesn't know how to evaluate, uses the wrong symbols, or is incomplete it'll return NaN. Could you put the equations you're trying to evaluate in a comment so I can take a look at them?
Also, if you're using the fancy-looking math operators, make sure you're removing those before passing the equation into mXparser. That library is looking for the traditional multiplication symbol ( * ) and division symbol ( / ) I think in this video I used ÷ for division and x for multiplication which mXparser doesn't know how to work with
Hey!
I'm not sure if you're still reading these or not but for some reason my buttons don't seem to be registering on click, Ive got the function created and set properly in the activity_main.xml
private void updateText(String toAdd)
{
String oldStr = display.getText().toString();
int cursorPosition = display.getSelectionStart();
String leftHalf = oldStr.substring(0,cursorPosition);
String rightHalf = oldStr.substring(cursorPosition);
display.setText(String.format("%s%s%s", leftHalf, toAdd, rightHalf));
}
public void zero_btn (View view){
updateText("0");
}
and that's the function w/ a button that's not activating on press. Any thoughts?
nevermind! somehow I created a seperate v21\activity_main.xml file, no idea how it got there but It was referring to that file for everything.
So I deleted the extra one and it deleted both, which was fantastic -_-
@@PracticalCoding Yeah they were all set, the weird thing is that it somehow created a duplicate xml file that was (v21) and that file wasn't set. Once I set it in the new file everything worked fine. Any idea why that file would randomly appear?
@@PracticalCoding What's even weirder if I deleted the main file it deleted both lol
The only thing that is standing out to me is that you aren't moving the position of the cursor up one spot once you add a character.
It should be this bit of code here:
display.setSelection(cursorPosition + 1);
(I changed the variable name to the one you used)
But if the buttons are not doing anything when they're clicked, I wanna ask if you set them up in that OnClick dropdown in the attributes section when you have the XML file opened
same problem bro
i have a problems with view.onclick it's not in the list..how can i fix it..
@@PracticalCoding I have a similar problem view is not in the dropdown menu for public void zeroBTN
@@PracticalCoding I created a new file and tried it again and it worked thanks
@Aashutosh Kulakarni Good to hear. Glad you got it to work
Can you upload your github link for thsis project?
Here's the link to this project
github.com/Practical-Coding3/calculatorApp
I should have the rest on there too
Hi @Practical Coding, Thanks for another awesome video. I am facing a problem. When I write the follwing line
display.setSelection(cursorPos + 1); in the "if portion" and after running the app, it gets immediately close on tapping any key.
Can you please guide me what I am doing wrong. I am copying the updateText function code
private void updateText(String strToAdd){
String oldStr = display.getText().toString();
int cursorPos = display.getSelectionStart();
String leftStr = oldStr.substring(0, cursorPos);
String rightStr = oldStr.substring(cursorPos);
if(getString(R.string.display).equals(display.getText().toString())){
display.setText(strToAdd);
display.setSelection(cursorPos + 1);
}
else{
display.setText(String.format("%s%s%s", leftStr, strToAdd, rightStr));
display.setSelection(cursorPos + 1);
}
}
Hey so I went through your code and compared it to what I have and I don't see any major issues. Can you run the app again and copy the error message you're getting into a comment?
To see the error message, look at the very bottom of Android Studio for a button that says "Logcat". When you run the app, there should be a bunch of text that starts to appear. You're looking for the text that should be in red. Oh and I don't need all of the text, just the part where the error is occurring.
Let me know if you have any issues and hopefully, we can get this fixed for you.
@@PracticalCoding Following error code is appearing in red in the logcat
2020-12-10 14:27:05.678 25806-25806/com.example.calculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.calculator, PID: 25806
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:6291)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6291)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6291)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Caused by: java.lang.IndexOutOfBoundsException: setSpan (14 ... 14) ends beyond length 1
at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1313)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:684)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:676)
at android.text.Selection.setSelection(Selection.java:76)
at android.text.Selection.setSelection(Selection.java:87)
at android.widget.EditText.setSelection(EditText.java:127)
at com.example.calculator.MainActivity.updateText(MainActivity.java:45)
at com.example.calculator.MainActivity.btnNine(MainActivity.java:91)
@@areejaftab9334 I think I might have an idea of what is causing the error I just need to see the code you have in the onCreate method. I think you're missing something in there.
@@PracticalCoding This is my onCreate method code
private EditText display;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = findViewById(R.id.input);
display.setShowSoftInputOnFocus(false);
display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(getString(R.string.display).equals(display.getText().toString())){
display.setText("");
}
}
});
}
@Practical Coding Sir have you traced the error? Kindly assist me as I have not been able to trace it. Thank you.
I am getting error code B8 Execution failed for task ':app:compileDebugJavaWithJavac'. I would be really obliged for any help cause i am not able to find the solution for the problem. Also, wanted to thank you cause this video was really nice!
Can you tell me what buildToolsVersion and compileSdkVersion you're using? If you go over to the left-most panel in Android Studio, where the file tree is located, you should see a folder that says "Gradle Scripts". Expand that folder and click on one of the build.gradle files. For me, the file that has (Module: app) after build.gradle is the file that shows what version I'm using. Then, in that file, you're looking for something that looks like this
compileSdkVersion 29
buildToolsVersion "29.0.3"
It should be towards the top of the file.
as soon as I click on my backspace button my app crashes... I checked for any errors in my code but it's literally the same as the one showed by you... any suggestions?
When you run the app and let it crash, could you open up the LogCat or the Run tab (An error message will be in one of those) and paste it into a comment for me to look at? The tabs should be at the bottom of Android Studio
why does else if keep popping up on mine saying it's an illegal start of expression?
can you put the code you're using so I can take a look at it? And what is the else if code part of?
I am getting error with updateText(strToAdd:"0");
Where "strToAdd" turned into red colour and it's suggesting[💡] to either create local variable 'strToAdd' or create field 'strToAdd' in 'MainActivity'.
Someone please help me with it ....
Simply type "updatetext" and then put "updateText("")" it's automatically detect. This way to resolve the problem.
@@MajidAli-wx3px thanks
My updateText does not work I don't know why because am stuck when I try to input numbers the buttons don't work
Can you put the code you're using for the updateText method in a comment so I can take a look at it?
private void updateText(String strToAdd ) {
String oldStr= display. getText(). toString() ;
int cursorPos= display.getSelectionStart();
String rightStr= oldStr. subString(0,cursorPos);
String rightStr= oldStr. subString(cursorPos);
display.setTextString(String.formart("%s%s%s", leftStr, strToAdd,rightStr));
display.setSelection(cursorPos+1):
}
Hey, I think I found the issue. It looks like you have a small typo where you're splitting up the old string into the left and right portions. Here's what you have:
String rightStr= oldStr. subString(0,cursorPos);
String rightStr= oldStr. subString(cursorPos);
The first string variable should be defined as "leftStr" I believe. Other than that small typo, nothing else stands out to me. Let me know if that fixes the issue
public void updateText(String strToAdd){
String oldStr = display.getText().toString();
int cursorPos = display.getSelectionStart();
String leftStr = oldStr.substring(0,cursorPos);
String rightStr = oldStr.substring(cursorPos);
display.setText(String.format("%s%s%s", leftStr, strToAdd,rightStr));
}
this is wat i have and is not working bro
The updateText method is super complicated for me to understand, like I know what we're trying to do but I don't really understand the logic.
Okay, I'm gonna try and explain what's happening in that function the best I can. So, the first thing that we do is grab the whole string that's in the display and store whatever that value is in the variable "oldSTR". Then, we need to grab the position of the cursor and store that position in the variable "cursorPos". We do that because the user can place the cursor in the middle of an expression. Then with the next few lines we split the string that's stored in "oldStr" at the position of the cursor. So if we had the expression "1+2" (that is what we will say is stored in the "oldStr" variable) and had a cursor position of 1 stored in the variable "cursorPos" (this would mean the cursor is in between the 1 and +) we are going to split the string "1+2" at position 1. this will result in "1" being stored in the variable "leftStr" and "+2" being stored in the variable "rightStr". Now we reached the if else statement. What the if statement basically does is looks to see if the cursor is at the very end of the string (then you don't really need to mess with the "leftStr" and "rightStr"). looking back at this code I could have made this much simpler but it is what it is. I probably could have just used the code that's in the else statement. Too late now though. Then in the else statement, we are going to combine the left and right strings with the string that the user would like to insert at the cursor position. So going back to the example "1+2". If the users cursor position was again at position 1 so in between the 1 and + and clicked a 3 to make the equation "13+2" then in the setText line we combine the leftStr with the strToAdd (the number 3) and then add-in the rightStr. We then set the whole display to that new string that was constructed which will now read "13+2"
I hope that clears things up a bit. If you're still a little confused about what's happening just let me know
@@PracticalCoding okay, you've really cleared up things quite a bit. I must say I'm not really into developing a calculator. Just looking to understand how such an app works so I can grasp my head around basic concepts, I'm very very new to Java and app development.
I'll also say this, the fact that you took the time out to write all this and explain what is going on to someone who is a complete stranger to you, someone you will never ever meet. That is an incredible gesture. You may think I'm over exaggerating, but no, I really really respect someone who's willing to share knowledge with strangers and expecting nothing in return.
My man, I can tell you're a damn good human being, we need more people like you. You truly have my respect. I would love to see more android and Java stuff from you.
@@ChadEricCartman Thanks man it means a lot. Glad I could help you out!
at 19:40 can we also use char ch = display.getText().toString().charAt(i); and then use the if statement ?
Just from watching that part of my video, I'm not too sure. I haven't really looked at the code in this project for a while. The last time I went through the project, I saw a lot of simplifications that could have been made. Funny how much you can learn about something in a year😂 I would say it's fine as long as the app still works the way you expect it to. I'd try it out and see what happens. The worst that can happen is it doesn't work. In general, if your code works, is simpler, and easier to read then I would go with that.
@@PracticalCoding I tried it and it works thank you !
Sir all my coding correct when i press C button for clear my app crash. I dont know why?
Well, something's gotta be wrong with that method. If you want, you can join the Discord server for this channel and upload a few pictures of what's going wrong when you try to clear the screen. If you don't have Discord, you can post the error message into a comment and I can see if anything jumps out to me.
Here's the Discord link:
discord.gg/evK6jwg4Xj
this should solve it:
public void clearBtn (View view){
SpannableStringBuilder selection1 = (SpannableStringBuilder) display.getText();
selection1.clear();
display.setText(selection1);
Can't we leave the textView blank already to get rid of the problem?
Yeah you could do that too but an even better way to get rid of that default text would be using the hint attribute
android:hint="Enter a value"
When I made this I had no idea this attribute even existed but it'll display the "enter a value" text and when the user clicks the display it'll disappear. No need to write any of the logic we wrote to get rid of the default text
@@PracticalCoding but it's still the best tutorial I've seen on RUclips. Our teacher wanted us to create a simple calculator and this is helping a lot😊
My programs are working but when I click one of my buttons the display won't show
private void updateText(String strToAdd)
{
String oldstr = display.getText().toString();
int cursorPos = display.getSelectionStart();
String leftstr = oldstr.substring(0, cursorPos);
String rightstr = oldstr.substring(cursorPos);
display.setText(String.format("%s%s%s", leftstr, strToAdd, rightstr));
}
upload calculator videos in kotlin
the app crashes for some reason when I try to do closed parentheses
Could you put the error message you get in a comment? should be in the LogCat tab towards the bottom of Android Studio
Can you post the code for the parentheses...I'm having trouble
I should have the entire project out on my GitHub page. Here's the link to it if you wanna check out all of the project files
github.com/Practical-Coding3/calculatorApp
I'm not getting the same color set for the buttons on the phone screen.it turned out to be all blue
What version of Android Studio are you using?
@@PracticalCoding 4.1.2
@@drishyadinesh8842When Android Studio updated to version 4, they changed a few things around and now, to change the background for the buttons, you have to mess with the themes folder. There's a style tag in both the normal and night theme which has a parent attribute. I would try and change it to this
Theme.AppCompat.Light.NoActionBar
Right now, I'm working on a new calculator series to account for the update. I have two videos out already and I plan on getting the next posted this Monday. Here's the link to the first video if you wanna check it out (It'll show you how to change the parent attribute in your themes folder)
ruclips.net/video/1ssYYy8Li48/видео.html
Hope this helps you out! If it doesn't just let me know
@@drishyadinesh8842 Just select the button
set backgroundTint as white and backgroundTintMode as multiply
is there any way that you can provide your code for this? github etc.
Yeah I can post the project on GitHub. I'll let you now when it's up
@@PracticalCoding Thanks!
@@devynq3895 Just posted the project on GitHub. Heres the link
github.com/Practical-Coding3/calculatorApp
Am getting a warning (method 'updateText(java.lang.String)' is never used can't proceed with no errors from there
Can you paste what yo have for the updateText method in a comment so I can take a look at it
if i click on any number to displays with a comma, can u please help me out
@@PracticalCoding to all the butons
Here is my code:
package com.example.calculator;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText display;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display=findViewById(R.id.input);
display.setShowSoftInputOnFocus(false);
display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(getString(R.string.display).equals(display.getText().toString()))
{
display.setText(" ");
}
}
});
}
private void updateText(String strToAdd){
String oldStr=display.getText().toString();
int cursorPos=display.getSelectionStart();
String leftStr= oldStr.substring(0,cursorPos);
String rightStr=oldStr.substring(cursorPos);
if (getString(R.string.display).equals(display.getText().toString())){
display.setText(strToAdd);
}
else{
display.setText(String.format("%s,%s,%s",leftStr,strToAdd,rightStr));
display.setSelection(cursorPos+1);
}
}
public void zeroBTN(View view){
updateText("0");
}
public void oneBTN(View view){
updateText("1");
}
public void twoBTN(View view){
updateText("2");
}
public void threeBTN(View view){
updateText("3");
}
public void fourBTN(View view){
updateText("4");
}
public void fiveBTN(View view){
updateText("5");
}
public void sixBTN(View view){
updateText("6");
}
public void sevenBTN(View view){
updateText("7");
}
public void eightBTN(View view){
updateText("8");
}
public void nineBTN(View view){
updateText("9");
}
public void exponentBTN(View view){
updateText("^");
}
public void paranthesisBTN(View view){
}
public void clearBTN(View view){
display.setText("");
}
public void plus_minusBTN(View view){
updateText("+/-");
}
public void pointBTN(View view){
updateText(".");
}
public void addBTN(View view){
updateText("+");
}
public void subtractBTN(View view){
updateText("-");
}
public void multiplyBTN(View view){
updateText("*");
}
public void divideBTN(View view){
updateText("/");
}
public void backspaceBTN(View view){
int cursorPos=display.getSelectionStart();
int textLen=display.getText().length();
if(cursorPos!=0&&textLen!=0){
SpannableStringBuilder selection=(SpannableStringBuilder)display.getText();
selection.replace(cursorPos-1,cursorPos,"");
display.setText(selection);
display.setSelection(cursorPos-1);
}
}
public void equalsBTN(View view){
}
}
@@PracticalCoding Thank you so much.... For helping
Hoping for your upcoming videos ✌🏻
@@PracticalCoding Thank you for the correction it's working...
Moved my account to a brand account so my comments got deleted. Just putting some of them back
@Syed Atif I think I found the problem. So if you look in your updateText method, you have the following code in the else statement
display.setText(String.format("%s,%s,%s",leftStr,strToAdd,rightStr));
when you're using the format function, you have to make sure that the "%s" are right next to each other. Right now, you have them separated by commas so that's why they're showing up in the display. All you have to do is change that line of code to this
display.setText(String.format("%s%s%s",leftStr,strToAdd,rightStr));
and you should be good to go 👍
Let me know if this works. If not, I'll take another look at your code but I pretty sure that's the issue.
i am trying to compile the project and run on the emulator but it throws errors saying Android resource compilation failed and in the error box it shows
C:\Users\admin\AndroidStudioProjects\CalcyFinal\app\src\main
es\layout\activity_main.xml:3: AAPT: error: duplicate attribute.
C:\Users\admin\AndroidStudioProjects\CalcyFinal\app\src\main
es\layout\activity_main.xml: AAPT: error: file failed to compile.
can you suggest me what to do??
It looks like you might have written in two attributes for a view in the activity_main.xml file. Maybe you defined an ID for a button twice? I would check around for duplicate attributes like that.
Let me know how it goes
Thank you but when i updated android studio and emulator the problems were all gone.
By the way the way u reply to everyone's doubt made my day keep up the good work👌👌
@@yxd7 Okay cool glad you got it working!
Hi, thank you for your wonderful videos!!! My public buttons (zeroBTN) aren't able to connect to the private string strToAdd through the update text. (shows up red next to updateText and the row above has the error "illegal start of expression" Does anyone know the solution to this? Help is much appreciated T-T
Solved! I can't believe I've been holding on to this problem 2 days. All I had to do was to erase "strToAdd" that I typed manually so that android studio would do it automatically. Thank you!
@@sumins356 Good to hear you figured it out!
@@PracticalCoding I am having a similar issue when I try to add an updateText(strToAdd) underneath the public void for each button. It will not recognize strToAdd as a variable, as it tells me to define it as a local variable.
@@thomassabatino4338 I think I'm gonna need to see your code to help you out. You can paste some of the code in a comment and I can sift through it or you can join the Discord server I set up for the channel. Discode is probably going to be better since you can send pictures.
Here's the link if you wanna join the server
discord.gg/H2P89STbaS
How did u get intellij to automatically fill it in? im trying to press enter, tab, and double click the suggestion for strToadd but nothing works. ANd when i type it out manually it doesnt work
Why my strToadd function is showing error in the buttons definition. please reply at earlier if u can.
What's tb in the last it shows error
@@dharanik377 you should set up like updateText(""); once you put the quotes it pops up at once, stare at the video and take a peek while he is typing what he does he puts the quotes and it pops up per se
@@duncarnba thank you
@@dharanik377 you're welcome
@@duncarnba it did not work what i have to do ?
this is may code:
private void updateText(String strToAdd);
String oldstr = display.getText().toString();
int cursepos = display.getSelectionStart();
String leftstr = oldstr.substring(0, cursepos);
String rightstr = oldstr.substring(cursepos);
display.setText(String.format("%s%s%s", leftstr, strToAdd, rightstr));
Format string doesn't exit what we have to do
What? Could you explain the issue a little differently? I don't think I understand what the problem is
hi. in public void paranthesesBTN
in if (openPar == closePar || display.getText().toString().substring(textLen-1, textLen).equals("(")) we can add display.getText().toString().substring(textLen-1, textLen).equals("^"), display.getText().toString().substring(textLen-1, textLen).equals("/"), because we may want to write such expresions: (2+3/(9+4))
Thanks for sharing the code!
I wish you add lcode link with github
The code's on GitHub. Here's the link:
github.com/Practical-Coding3/calculatorApp
when i am typing (View view) the view shows error. it says "cannot resolve symbol 'View' ". what should i do?
That's weird. Do you have automatic imports set in Android Studio? I'll bet that's what it is. I have that set for me so when I type in "View" Android Studio automatically imports everything I need. Check to see if you have this import at the top of your file
import android.view.View;
Without that, Java has no idea what a "View" is. If you're missing that statement add it in. If you do have that import at the top of your Java file and the error is still there let me know
@@PracticalCoding Thank you so much for your help and time. Your tutorials really help me get through college 😊.
I will try out what you told me and get back to you.
@@prachikumar2246 That's great! Love to hear it. And sounds good to me. Let me know how it goes when you get a chance
@@PracticalCoding It worked!😊 Thank you
Sir please java file source code send link...
I have a error in strToAdd:"0"
i was not able to work th public void zero btn thing
like at the start
Are you having issues linking the button click methods to the correct button in the XML file?
After number when just tap on expression suddenly shows Nan plz reply someone how can I desable it
It sounds like the expression you're giving the mXparser is valid. Make sure you're replacing the multiplication and division symbols before passing the extracted text to the class
@@PracticalCoding ok thanks
I am getting error while taking view as parameter can any one tell me what should I do????
What method does this happen in? Is it for the button onClick methods?
why the number button doesn't work?
Can you put the code you're using to update your editText in a comment so I can take a look at it?
i have error at if statemnt for parantheses
Can you put the error message into a comment or join this channel's Discord server and upload a picture of the error message so I can take a look at it?
Here's the link to the Discord server
discord.gg/evK6jwg4Xj
Its amazing but I am getting some error how can I contact you are you in Instagram or Twitter😞
Yeah you can send me a message on Instagram. I have my account linked on this channels homepage but if I remember correctly, my username should be _jasonsubick
hello ,for me none of the button is working and my code is
public class MainActivity extends AppCompatActivity {
private EditText display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = findViewById(R.id.input);
display.setShowSoftInputOnFocus(false);
display.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
if(getString(R.string.display).equals(display.getText().toString())){
display.setText("");
}
}
});
}
private void updateText(String strToAdd){
String oldstring = display.getText().toString();
int cursorPos = display.getSelectionStart();
String leftstring = oldstring.substring(0,cursorPos);
String rightstring = oldstring.substring(cursorPos);
display.setText(String.format("%s%s%s",leftstring,strToAdd,rightstring));
display.setSelection(cursorPos+1);
}
public void zeroBTN(View view){
updateText("0");
}
just list for zero button i added updateText function for every button but when i click any number it is not working i mean it is not showing on the text field
can u please help me?
did you link each onClick method to the correct button in the XML file?
it's turing my voids into "fun"
It sounds like you're using the Kotlin programming language. In this video series, I wrote everything in Java. You're gonna have to swap over to Java if you want to directly follow along. By default, Android Studio has the language set to Kotlin. When you create a new project, make sure you swap that over so it says Java.
@@PracticalCoding Fixed. Works like a dream
@@PracticalCoding Is it too late to switch it now.
@@Beatboxbizboy Did you have your project in Kotlin? If you created the project to use Kotlin, I would say you would have to start over but I'm not 100% sure about that. Maybe there's a way to do it. I just don't know of one
The app doesnt work
On 13:45 , If i Press a Button, the App Crash, can anyone help me😁
@@PracticalCoding it only crashes when a button is supposed to remove the text, if I press clear beforehand, everything goes without a problem, sorry if i write something wrong, I come from Germany😅
@@PracticalCoding that one?
Oh so the backspace button is what's causing the problem. It could be a problem with grabbing the different parts of the string from the display. Can you put that code into a comment so I can take a look at it when I get home?
Sir in my case , whenever I press any button there is no output in edit text view
@@gautamseta4626 Hey can you put the code you're using the updateText method into a comment so I can take a look at it?
I tried that .. more errors appear 😔
What problem are you running into?
Kotlin mein chahiye code java Mein nhi 🙂
Coming error in strToAdd:
Please tell what to do?
@@user-pg7cl7vk1m you should set up like updateText(""); once you put the quotes it pops up at once, stare at the video and take a peek while he is typing what he does he puts the quotes and it pops up per se
@@duncarnba love you bro
why all the dance on the updatetext func? just do display.getText.insert(pos,string);
why is my app crashing? I've tried to check the logcat and it says
java.lang.IllegalStateException: Could not execute method of the activity.
Very happy if someone helps me.