unable to convert Edittext to int - android

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var X: EditText = findViewById(R.id.num12)
var Y: EditText = findViewById(R.id.num2)
var B: Button = findViewById(R.id.btn1)
var vir: TextView = findViewById(R.id.virw)
var X1: Int = X.text.toString().toInt()
var Y1: Int = Y.text.toString().toInt()
B.setOnClickListener() {
vir.text = "add new ${addtwonumber(X1, Y1)}"
}
}
private fun addtwonumber(a:Int,b:Int):Int{
return a+b
}
}
Error 2021-11-20 20:29:39.940 29733-29733/com.example.calibrate
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.calibrate, PID: 29733
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calibrate/com.example.calibrate.MainActivity}:
java.lang.NumberFormatException: For input string: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3528)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3703)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2152)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:250)
at android.app.ActivityThread.main(ActivityThread.java:7886)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:970)
Caused by: java.lang.NumberFormatException: For input string: ""
at java.lang.Integer.parseInt(Integer.java:627)
at java.lang.Integer.parseInt(Integer.java:650)
at com.example.calibrate.MainActivity.onCreate(MainActivity.kt:23)
at android.app.Activity.performCreate(Activity.java:8108)
at android.app.Activity.performCreate(Activity.java:8092)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3501)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3703) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2152) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:250) 
at android.app.ActivityThread.main(ActivityThread.java:7886) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:970) 
2021-11-20 20:29:39.957 29733-29733/com.example.calibrate I/Process:
Sending signal. PID: 29733 SIG: 9

Looks at this line of the error:
java.lang.NumberFormatException: For input string: ""
You have an empty string (because your EditText is empty initially) which your are trying to convert to an Int. That's why you are getting the NumberFormatException.
You can fix the error by using String.toIntOrNull(). This function returns null instead of throwing an exception if the string cannot be converted to an Int. Then you can maybe use the elvis operator(?:) to use a default value for the null Int.
val X1: Int = X.text.toString().toIntOrNull() ?: 0 // Use zero if string does not represent an Int
On a side note, please use vals instead of vars for properties that are not going to change and also give better names to them (X, Y, X1, Y2 don't look good)

At the beginning your EditTexts are empty, so the error is because it can't convert empty "" to integer, so you can check first if it is not empty or use toIntOrNull() function, but you also want to get the x and y when the user clicks on the button not at the beginning so the right way is to move your code from onCreate to onClickListener body
B.setOnClickListener() {
val X1: Int = X.text.toString().toInt()
val Y1: Int = Y.text.toString().toInt()
vir.text = "add new ${addtwonumber(X1, Y1)}"
}

Related

CameraX PreviewView to Bitmap instead of a File

I know there are other questions that was answered to many times and I tried to find the answer, but I couldn't understand of it most. I want to make the camera to take a photo, but instead of making a physical image file, I want it directly to make it into a bitmap and display it in an ImageView from a different activity, however I constantly getting the Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference, that's because of the viewFinder.bitmap is a null and decided to make a seperate function getBitmap(): Bitmap?. I don't know what it wants me to do honestly or any lead from this, all I want to do is to make the photo straight to ImageView as a bitmap. Thank you in advance.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.camerax5, PID: 5472
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.camerax5/com.example.camerax5.VirtualPreview}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3141)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3284)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1972)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7179)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:164)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:677)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:842)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:809)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:633)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
at com.example.camerax5.MainActivity.getBitmap(MainActivity.kt:118)
at com.example.camerax5.VirtualPreview.onCreate(VirtualPreview.kt:19)
at android.app.Activity.performCreate(Activity.java:7335)
at android.app.Activity.performCreate(Activity.java:7326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1275)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3121)
So the problem was occured on this line:
viewFinder = findViewById(R.id.previewView)
Here is the full code of what I was trying to do:
MainActivity.kt and underneath the MainActivity code is the other class with another activity to show the bitmap in the ImageView, I added this way is because I don't want to separate them and making them confusing:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewFinder = findViewById(R.id.previewView)
//Permissions
if (allPermissions()) {
startCamera()
} else {
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
}
//Capture button
val captureBtn: Button = findViewById(R.id.captureButton)
captureBtn.setOnClickListener {
takePhoto()
}
outputDirectory = outputDirectoryFolder()
cameraExecutor = Executors.newSingleThreadExecutor()
}
private fun takePhoto() {
Toast.makeText(baseContext, "Processing ..", Toast.LENGTH_SHORT).show()
//Directly to open the new Activity
val intent = Intent(this, VirtualPreview::class.java)
startActivity(intent)
}
fun getBitmap(): Bitmap? {
//Preview to Bitmap
viewFinder = findViewById(R.id.previewView)
val source = viewFinder.bitmap
val newWidth = 200
val newHeight = 200
val bitmapWidth = source?.width
val bitmapHeight = source?.height
//Matrix
val matrix = Matrix()
val scaleWidth = newWidth.toFloat() / bitmapWidth!!
val scaleHeight = newHeight.toFloat() / bitmapHeight!!
matrix.postScale(scaleWidth, scaleHeight)
return Bitmap.createBitmap(source, 0, 0, newWidth, newHeight, matrix, true)
}
}
class VirtualPreview : AppCompatActivity() {
private lateinit var acceptButton: Button
private lateinit var denyButton: Button
private lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_virtual_preview)
val bitmapPreview = MainActivity().getBitmap()
val drawableBitmap = BitmapDrawable(resources, bitmapPreview)
imageView = findViewById(R.id.imagePreview)
imageView.setImageDrawable(drawableBitmap)
acceptButton = findViewById(R.id.acceptButton)
acceptButton.setOnClickListener {
}
denyButton = findViewById(R.id.denyButton)
denyButton.setOnClickListener {
//delete the matrix and returns to the main activity
finish()
}
}
}
val bitmapPreview = MainActivity().getBitmap() - This way you are creating a new instance of MainActivity and the new instance do not have any thing in preview view, also this method is not recommended. Better store bitmap inside MainActivity and then pass that bitmap to VirtualPreview activity in constructor (in bundle it won't work). It won't be a problem for your case, as you're scaling the bitmap to 200x200. and for large bitmap, store in file, and use that file. And for your case, you can create another imageview in mainactivity and show the bitmap in that imageview instead of creating another activity.

How do I change the image?

I am trying to change the image when I click the button, but it doesn't work. Can anyone tell me how to fix this? I think there are something to do with the declaration
val afterEatingImage:ImageView="R.drawable.after_cookie"
and I tried = (R.drawable.after_cookie), R.drawable.after_cookie, after_cookie
Maybe I should not use Val for an image but I don't know what to use. So you can see this is a basic question and I am a beginner so pls help.
fun eating(view: View?) {
val afterEatingText:String="I am so full!!"
displayMessage(afterEatingText)
val afterEatingImage:ImageView="R.drawable.after_cookie"
displayImage(afterEatingImage)
}
private fun displayMessage(message: String) {
val afterEatingText = findViewById<View>(R.id.before_eating) as TextView
afterEatingText.text = message
}
private fun displayImage(image: ImageView){
val afterEatingImage: findViewById<View>(R.id.before_cookie) as ImageView
afterEatingImage.setImageResource(image)
}
}
The id of my ImageView is android:id="#+id/before_cookie"
The names of 2 imagefiles are before_cookie and after_cookie.
Red errors are as follows.
Another way to do this:
fun eatCookie(view: View?) {
// Find a reference to the ImageView in the layout. Change the image.
val imageView = findViewById<View>(R.id.before_eating) as ImageView
imageView.setImageResource(R.drawable.after_cookie)
// Find a reference to the TextView in the layout. Change the text.
val textView = findViewById<View>(R.id.before_eating) as TextView
textView.text = "I'm so full"
}
The crash result after I click the button.
Message from Logcat
05-17 12:22:11.216 3029-3029/com.example.afterclicking E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.afterclicking, PID: 3029
java.lang.IllegalStateException: Could not find method eating(View) in a parent or ancestor Context for android:onClick attribute defined on view class com.google.android.material.button.MaterialButton
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:447)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:405)
at android.view.View.performClick(View.java:4780)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
If I use val textView = findViewById<View>(R.id.before_eating)
then red alert appears.
If I use val textView = findViewById<View>(R.id.before_eating) as TextView then it will be fine, Why is that?
What you are doing is assigning the String R.drawable.after_cookie to your ImageView afterEatingImage. You pass this ImageView to your method and try to assign it as the image resource.
What you should do is the following
Pass the integer R.drawable.after_cookie to your method
Assign this parameter to your ImageView
This will become something like this
fun eating(view: View?) {
val afterEatingText:String="I am so full!!"
displayMessage(afterEatingText)
displayImage(R.drawable.after_cookie) //Change this
}
private fun displayMessage(message: String) {
val afterEatingText = findViewById<View>(R.id.before_eating) as TextView
afterEatingText.text = message
}
private fun displayImage(imageResource: Int) { //Change this
val afterEatingImage: ImageView = findViewById<ImageView>(R.id.before_cookie)
afterEatingImage.setImageResource(imageResource)
}
Note: I am assuming this is all done in your activity. In case you are doing this in your fragment, you need a reference of your view to find your ImageView

Error of java.lang.RuntimeException: Unable to instantiate activity ComponentInfo KOTLIN/AndroidStudio

I am trying to do a copy of Space Invaders with Kotlin and Android Studio to learn more about this kind of development but I have this error happening :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.spaceinvaders, PID: 3982
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.spaceinvaders/com.example.spaceinvaders.GameView}: java.lang.InstantiationException: java.lang.Class<com.example.spaceinvaders.GameView> has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2914)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3119)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.spaceinvaders.GameView> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1216)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3119) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1839) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6864) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
I have two activities: one for the menu and one for the game. When I try to pass from one menu to the other by clicking on a button, it crashes.
Here there are the other codes :
HomeScreen :
class HomeScreen : Activity(), View.OnClickListener{
lateinit var nbAliens : TextView
lateinit var SPACE_SHIP : Bitmap //L'image choisi par le joueur
var ALIENS_NUMBER : Int = 0 //Le nombre d'ennemi choisi par le joueur
var flagOK : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ecran_accueil)
nbAliens = findViewById(R.id.textViewNbEnnemis)
btnMinus.setOnClickListener(this)
btnPlus.setOnClickListener(this)
imgBtnSpaceShip1.setOnClickListener(this)
imgBtnSpaceShip2.setOnClickListener(this)
btnStart.setOnClickListener(this)
}
override fun onClick(v: View?) {
when (v){
btnMinus ->{
//Modify the textView et change ALIEN_NUMBER
var i = nbAliens.text.toString().toInt()
if (i > 7) i--
nbAliens.text = i.toString()
ALIENS_NUMBER = i
}
btnPlus ->{
var i = nbAliens.text.toString().toInt()
if (i < 21) i++
nbAliens.text = i.toString()
ALIENS_NUMBER = i
}
imgBtnSpaceShip1 ->{
/*When you click in the imageButton, you chose your SpaceShip Image
The first one's background goes green while the other becomes all grey
*/
val color = Color.argb(130,255,255,255)
imgBtnSpaceShip1.setColorFilter(Color.TRANSPARENT)
imgBtnSpaceShip2.setBackgroundColor(color)
imgBtnSpaceShip2.setColorFilter(color)
imgBtnSpaceShip1.setBackgroundColor(Color.GREEN)
SPACE_SHIP = BitmapFactory.decodeResource(resources, R.drawable.space_ship1)
flagOK = true
}
imgBtnSpaceShip2 ->{
val color = Color.argb(130,255,255,255)
imgBtnSpaceShip2.setColorFilter(Color.TRANSPARENT)
imgBtnSpaceShip1.setBackgroundColor(color)
imgBtnSpaceShip1.setColorFilter(color)
imgBtnSpaceShip2.setBackgroundColor(Color.GREEN)
SPACE_SHIP = BitmapFactory.decodeResource(resources, R.drawable.space_ship2)
flagOK = true
}
btnStart -> {
//Change from HomeScreen to GameView
if (flagOK) {
val intent: Intent =
Intent(applicationContext, GameView::class.java)
startActivity(intent)
finish()
}else {
Toast.makeText(this, "You have to pick a spaceship to start!", Toast.LENGTH_LONG).show()
}
}
}
}
}
GameView :
class GameView #JvmOverloads constructor (context: Context, var imgSpaceShip: Bitmap, attributes: AttributeSet? = null, defStyleAttr: Int = 0): View(context, attributes,defStyleAttr){
private lateinit var imgAlienGreen : Bitmap
private lateinit var imgAlienRed : Bitmap
private lateinit var imgAlienWhite : Bitmap
private var alien_margin by Delegates.notNull<Float>()
private var alien_side by Delegates.notNull<Float>()
val game : Game = Game()
val backgroundPaint = Paint()
//Load images and resize it
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
alien_margin = width*0.025f
alien_side = (width - (game.NB_ALIENS_COLUMNS+1)*alien_margin)/game.NB_ALIENS_COLUMNS
//There is another class Game for the logic of the game
try{
imgAlienGreen = BitmapFactory.decodeResource(resources, R.drawable.alien_green)
imgAlienGreen = Bitmap.createScaledBitmap(imgAlienGreen, alien_side.toInt(), alien_side.toInt(), true)
imgAlienRed = BitmapFactory.decodeResource(resources, R.drawable.alien_red)
imgAlienRed = Bitmap.createScaledBitmap(imgAlienRed, alien_side.toInt(), alien_side.toInt(), true)
imgAlienWhite = BitmapFactory.decodeResource(resources, R.drawable.alien_white)
imgAlienWhite = Bitmap.createScaledBitmap(imgAlienWhite, alien_side.toInt(), alien_side.toInt(), true)
imgSpaceShip = Bitmap.createScaledBitmap(imgSpaceShip, alien_side.toInt(), alien_side.toInt(), true)
}catch (exception : Exception) {
Log.e("ERROR", "Cannot load images");
}
}
//Build the rectangles where the images will be set on.
private fun alienRectF(index: Int) : RectF{
val x : Float = alien_margin + alien_side
val y : Float = height + 0.17f
return RectF(x, y, x+alien_side, y+alien_side)
}
//It finishes here but I will continue coding after resolving it
}
I have no idea of what is going on. Thanks for the help!
To use startActivity function, you should navigate from Activity to Activity, but GameView is not activity, it is a View (extends from View, but should be Activity)

My android app crashes when I use it, and Android studio shows "FATAL EXCEPTION"

I have been working on a tip calculator android app recently, and today I have been trying to add a way to divide a bill. However, my app is crashing upon use because of it. I have been trying to figure out what is making it crash, but I can't seem to find anything. Whenever I use my app now, I get this error:
Process: com.gradient.tiptime, PID: 6507
java.lang.NumberFormatException: For input string: "androidx.appcompat.widget.AppCompatEditText{2d3edb1 VFED..CL. .F...... 600,60-1080,196 #7f0700d1 app:id/split_num aid=1073741825}"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.gradient.tiptime.MainActivity.calculateTip(MainActivity.kt:26)
at com.gradient.tiptime.MainActivity$onCreate$1.onClick(MainActivity.kt:19)
at android.view.View.performClick(View.java:7192)
at android.view.View.performClickInternal(View.java:7166)
at android.view.View.access$3500(View.java:824)
at android.view.View$PerformClick.run(View.java:27592)
at android.os.Handler.handleCallback(Handler.java:888)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
And this is the function that my "calculate" button calls:
fun calculateTip() {
var mealCost: Double = cost_of_service.text.toString().toDouble()
var splitNum: Double = split_num.toString().toDouble()
val selectedId = tip_options.checkedRadioButtonId
val tipPercentage = when(selectedId) {
R.id.option_twenty_percent -> 0.20
R.id.option_eighteen_percent -> 0.18
else -> 0.15}
//some values
var tip = tipPercentage * mealCost
val addedCost = tip + mealCost
//finds the views
val switch: Switch = findViewById(R.id.round_up_switch)
val result: TextView = findViewById(R.id.tip_result)
val total: TextView = findViewById(R.id.total_cost)
val splitResult: TextView = findViewById(R.id.split_cost)
val roundUp = switch.isChecked
var split: Double = mealCost / splitNum
var splitString: String = split.toString()
//if roundup switch is checked, rounds tip up
if (roundUp) {
tip = kotlin.math.ceil(tip)}
//formats the tip to $
val formattedTip = NumberFormat.getCurrencyInstance().format(tip)
val formattedCost = NumberFormat.getCurrencyInstance().format(addedCost)
//changes the textViews in the app
result.text = getString(R.string.tip_amount, formattedTip)
total.text = getString(R.string.total_amount, formattedCost)
splitResult.text = getString(R.string.total_amount, splitString)
}
From the code and the error you have provided the error looks in the line
var splitNum: Double = split_num.toString().toDouble()
Change this line to
var splitNum: Double = split_num.text.toString().toDouble()
The error here seems that the compiler is having trouble converting the EditText field into Double type which is not possible and results in casting error.

How to get Tracking State in ArCore

I am building an AR Android app where I want to spawn an arrow whenever the position of the user changes. However I get a NotTrackingException when I try to create an anchor. How can I know that ARCore detected a plane so that I can add my anchor?
The only thing I found is this, but there is not much I could get out of it.
fun onLocationChanged(location: Location) {
val session = arFragment.arSceneView.session
var arrowViewRenderable:ViewRenderable
val pos = floatArrayOf(0f,0f,-1f)
val rotation = floatArrayOf(0f,0f,0f,1f)
val anchor = session!!.createAnchor(Pose(pos,rotation))
val anchorNode = AnchorNode(anchor)
anchorNode.setParent(arFragment.arSceneView.scene)
ViewRenderable.builder()
.setView(this, R.layout.arrow)
.setSizer(DpToMetersViewSizer(400 ))
.build()
.thenAccept { renderable -> arrowViewRenderable = renderable
anchorNode.renderable = arrowViewRenderable
}
}
status.cc:156 ArStatusErrorSpace::AR_ERROR_NOT_TRACKING: Cannot create anchors while the camera is not tracking.
2019-06-12 14:58:37.369 29685-29685/com.carmeq.carfind E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.carmeq.carfind, PID: 29685
com.google.ar.core.exceptions.NotTrackingException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at com.google.ar.core.Session.throwExceptionFromArStatus(Session.java:134)
at com.google.ar.core.Session.nativeCreateAnchor(Native Method)
at com.google.ar.core.Session.createAnchor(Session.java:93)
at com.carmeq.carfind.MainActivity.onLocationChanged(MainActivity.kt:282)
at com.carmeq.carfind.MainActivity$mLocationCallback$1.onLocationResult(MainActivity.kt:223)
at com.google.android.gms.internal.zzbzq.zzq(Unknown Source:4)
at com.google.android.gms.common.api.internal.zzcj.zzb(Unknown Source:8)
at com.google.android.gms.common.api.internal.zzck.handleMessage(Unknown Source:16)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6981)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
You can retrieve the TrackingState from the Camera of the current Frame.
val frame = session.update()
if (frame.camera.trackingState == TrackingState.tracking) {
// place anchor
}

Categories

Resources