Android Question MeasureStringWidth: Cannot compile

ktlua

Member
Licensed User
I run the sample code:

Dim Canvas1 As Canvas
Dim width As Float
Dim t As String
t = "Text to write"
width = Canvas1.MeasureStringWidth(t, Typeface.DEFAULT, 14)

The error is:java.lang.NullPointerException

May I know where is my error?

Thanks.
 

DonManfred

Expert
Licensed User
Longtime User
you did not initialize the canvas?
 
Upvote 0

Widget

Well-Known Member
Licensed User
Longtime User
I run the sample code:

Dim Canvas1 As Canvas
Dim width As Float
Dim t As String
t = "Text to write"
width = Canvas1.MeasureStringWidth(t, Typeface.DEFAULT, 14)

The error is:java.lang.NullPointerException

May I know where is my error?

Thanks.

Sure. Your Canvas1 hasn't been initialized so it is still NULL.

Canvas1 would normally be the canvas of the view you are going to write to.

Canvas1.Initialize(Panel1)
width = Canvas1.MeasureStringWidth(t, Typeface.DEFAULT, 14)​

or you can use a Bitmap

Private MyBitmap as Bitmap
MyBitmap.InitializeMutable(1,1) 'Ignore
Canvas1.Initialize(MyBitmap)
width = Canvas1.MeasureStringWidth(t, Typeface.DEFAULT, 14)​
 
Upvote 0

ktlua

Member
Licensed User
Sure. Your Canvas1 hasn't been initialized so it is still NULL.

Canvas1 would normally be the canvas of the view you are going to write to.

Canvas1.Initialize(Panel1)
width = Canvas1.MeasureStringWidth(t, Typeface.DEFAULT, 14)​

or you can use a Bitmap

Private MyBitmap as Bitmap
MyBitmap.InitializeMutable(1,1) 'Ignore
Canvas1.Initialize(MyBitmap)
width = Canvas1.MeasureStringWidth(t, Typeface.DEFAULT, 14)​

Yes, I tried to initialize it with a label generated from codes. But it does not work.

Dim Canvas1 as Canvas
Dim lbl as Label
Dim width as Float
Label.Initialize("Label")
Canvas1.Initialize(lbl)
width = Canvas1.MeasureStringWidth(t, Typeface.DEFAULT, 14)

I can initialize Canvas by a Label from Designer but not from codes.

Pleaes help. Thank you!
 
Upvote 0

Widget

Well-Known Member
Licensed User
Longtime User
Yes, I tried to initialize it with a label generated from codes. But it does not work.

Dim Canvas1 as Canvas
Dim lbl as Label
Dim width as Float
Label.Initialize("Label")
Canvas1.Initialize(lbl)
width = Canvas1.MeasureStringWidth(t, Typeface.DEFAULT, 14)

I can initialize Canvas by a Label from Designer but not from codes.

Pleaes help. Thank you!

Don is Correct. Your local label is not owned by anything (it is not added to Activity).
The Label (or panel) has to be added to Activity before you can use the Label's canvas.
You may find it easier to use a bitmap if your view has not already been added to the activity.
 
Upvote 0
Top