Spanish SOLUCIONADO Error : java.lang.ClassCastException: b4c.example.main$_mymessage cannot be cast to b4c.example.prueba$_datos

elsanto

Member
Licensed User
Longtime User
Este error aparece cuando llega un texto enviado desde b4j , si en la app estoy en el main funciona pero cuando quiero recibir el texto desde prueba que es otra actividad
me tira el error java.lang.ClassCastException: b4c.example.main$_mymessage cannot be cast to b4c.example.prueba$_datos
Alguna sugerencia gracias
 

josejad

Expert
Licensed User
Longtime User
Parece que hay alguna asignación de tipos incompatibles, pero sin ver el código, me temo que poco podemos aventurar.

¿Puedes poner el código que muestra el texto en main y el que lo muestra en otra actividad?
 

elsanto

Member
Licensed User
Longtime User
Gracias Jose: he tomado el ejemplo de Erel
pq necesito enviar el nombre de unos archivos csv a b4a , entonces tome este ejemplo y solo envio un texto ,
Necesito recibir el nombre y archivos csv desde otra actividad que no sea el Main
Desde ya muchas gracias por tu ayuda

Actividad Main b4a

B4X:
Sub Process_Globals
    Private ser As B4XSerializator
    Type MyMessage (Name As String)
End Sub

Sub Globals
    Private edtIp As FloatLabeledEditText
    Private lblMyIp As Label
    Private btnConnect As Button
    Private lblStatus As Label
    Private edtAge As FloatLabeledEditText
    Private edtName As FloatLabeledEditText
    Private btnSend As Button
    Private cvs As Canvas
    Private pnlDrawing As Panel
    Private btnprueba As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    cvs.Initialize(pnlDrawing)
    edtIp.EditText.ForceDoneButton = True
    edtAge.EditText.InputType = edtAge.EditText.INPUT_TYPE_NUMBERS
    edtAge.Text = 10
End Sub

Sub Activity_Resume
    SetState
End Sub

Public Sub SetState
    btnSend.Enabled = Starter.connected
    If Starter.connected Then
        btnConnect.Text = "Disconnect"
        lblStatus.Text = "Connected"
    Else
        btnConnect.Text = "Connect"
        lblStatus.Text = "Disconnected"
    End If
    lblMyIp.Text = "My ip: " & Starter.server.GetMyWifiIP
End Sub

Sub btnSend_Click
    Dim mm As MyMessage
    mm.Initialize
    'mm.Age = edtAge.Text
    mm.Name = edtName.Text
    'convert the bitmap to bytes
'    Dim out As OutputStream
'    out.InitializeToBytesArray(0)
'    cvs.Bitmap.WriteToStream(out, 100, "PNG")
'    out.Close
'    mm.Image = out.ToBytesArray
    CallSub2(Starter, "SendData", ser.ConvertObjectToBytes(mm))
End Sub

Sub btnConnect_Click
    If Starter.connected = False Then
        If edtIp.Text.Length = 0 Then
            ToastMessageShow("Please enter the server ip address.", True)
            Return
        Else
            CallSub2(Starter, "ConnectToServer", edtIp.Text)
        End If
    Else
        CallSub(Starter, "Disconnect")
    End If
End Sub
Sub btnprueba_click
    StartActivity(prueba)
End Sub

Public Sub NewData (data() As Byte)
    Log("newdata main:")
    Dim mm As MyMessage = ser.ConvertBytesToObject(data)
'    edtAge.Text = mm.Age
    edtName.Text = mm.Name
'    'convert the array of bytes to image
'    Dim in As InputStream
'    in.InitializeFromBytesArray(mm.Image, 0, mm.Image.Length)
'    Dim bmp As Bitmap
'    bmp.Initialize2(in)
'    'draw the image
'    Dim dest As Rect
'    dest.Initialize(0, 0, pnlDrawing.Width, pnlDrawing.Height)
'    cvs.DrawBitmap(bmp, Null, dest)
'    pnlDrawing.Invalidate
End Sub
Actividad prueba b4a
B4X:
Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Private serial As B4XSerializator
    Private txtrecibido As EditText
    Private lblestado As Label
    Private lblip As Label
    Type datos (Nombre As String)
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("frmmuestra")

End Sub

Sub Activity_Resume
    SetState
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
Public Sub SetState
   
    If Starter.connected Then
       
        lblestado.Text = "Connected"
    Else
       
        lblestado.Text = "Disconnected"
    End If
    lblip.Text = "ip: " & Starter.server.GetMyWifiIP
End Sub
Public Sub NewData (data() As Byte)
    Log("newdata prueba:" )
    Dim str As datos = serial.ConvertBytesToObject(data)
    txtrecibido.Text = str.Nombre
   
   
End Sub
modulo starter
B4X:
Sub UpdateState (NewState As Boolean)
    Log("estado")
    connected = NewState
    CallSub(Main, "SetState")
    CallSub(prueba,"SetState")
End Sub
Sub AStream_NewData (Buffer() As Byte)
    Log("llego info")
   
    CallSub2(Main, "NewData", Buffer)
   
    CallSub2(prueba, "NewData", Buffer)
End Sub

Public Sub SendData (data() As Byte)
    If connected Then astream.Write(data)
End Sub
Y este es el Error
Registro conectado a: samsung SM-N950F
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
estado
estado
llego info
newdata main:
** Activity (main) Pause, UserClosed = false **
** Activity (prueba) Create, isFirst = true **
** Activity (prueba) Resume **
llego info
newdata prueba:
prueba_newdata (java line: 404)
java.lang.ClassCastException: b4c.example.main$_mymessage cannot be cast to b4c.example.prueba$_datos
at b4c.example.prueba._newdata(prueba.java:404)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:213)
at anywheresoftware.b4a.keywords.Common.CallSub4(Common.java:1082)
at anywheresoftware.b4a.keywords.Common.CallSubNew2(Common.java:1037)
at b4c.example.starter._astream_newdata(starter.java:157)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:213)
at anywheresoftware.b4a.BA$2.run(BA.java:387)
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:5305)
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)
--------- beginning of crash
Registro conectado a: samsung SM-N950F
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
estado
estado
llego info
newdata main:
** Activity (main) Pause, UserClosed = false **
** Activity (prueba) Create, isFirst = true **
** Activity (prueba) Resume **
llego info
newdata prueba:
prueba_newdata (java line: 404)
java.lang.ClassCastException: b4c.example.main$_mymessage cannot be cast to b4c.example.prueba$_datos
at b4c.example.prueba._newdata(prueba.java:404)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:213)
at anywheresoftware.b4a.keywords.Common.CallSub4(Common.java:1082)
at anywheresoftware.b4a.keywords.Common.CallSubNew2(Common.java:1037)
at b4c.example.starter._astream_newdata(starter.java:157)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:213)
at anywheresoftware.b4a.BA$2.run(BA.java:387)
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:5305)
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)
--------- beginning of crash
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
 
Last edited:

josejad

Expert
Licensed User
Longtime User
Si ejecutas en modo debug, en qué línea te lanza el error?
 

elsanto

Member
Licensed User
Longtime User
En modo debug , en la linea 50
B4X:
txtrecibido.Text = str.Nombre
 

elsanto

Member
Licensed User
Longtime User
Puse un log(str) y el valor llega ej hola cuando lo
Paso al edittext en
Txtrecibido.text = str.nombre se rompe
 

drgottjr

Expert
Licensed User
Longtime User
es posible que el objeto generado por ConvertBytesToObject() mantenga una referencia al objeto mismo. o sea, aunque mymessage y datos son efectivamente la misma cosa (un "custom type" con un solo campo de tipo string) son declarados como tipos distintos. como ya tienes MyMessage as process global, a ver si
logras cambiar:
B4X:
    Log("newdata prueba:" )
    Dim str As datos = serial.ConvertBytesToObject(data)
    txtrecibido.Text = str.Nombre

a
B4X:
    Log("newdata prueba:" )
    Dim str As main.MyMessage = serial.ConvertBytesToObject(data)
    txtrecibido.Text = str.name

y, de menor importancia, cambia el nombre "str" a otra cosa, ya que "str" suele sugerir string.

la documentacion referente a convertbytestoobject() me da la impresion de que aunque se trate de "objeto", el objecto tiene algun concocimiento de si mismo, y objeto 1 no puede convertirse (cast) forzosamente a objeto 2 si no son del mismo data type.

lee:
"Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. "

en ingles, pero facil de comprender. se mantiene el tipo del objeto cuando se conviete.
 
Last edited:

elsanto

Member
Licensed User
Longtime User
SOLUCIONADO drgottjr gracias esto funciono , el objeto solo se declara en el Main ,Type MyMessage (Name As String)

B4X:
Public Sub NewData (data() As Byte)
    Log("newdata prueba:" )
    'Dim str As datos = serial.ConvertBytesToObject(data)
    Dim str As MyMessage = serial.ConvertBytesToObject(data)
    'Log ("dato:" & str)
    txtrecibido.Text = str.Name
 
 
End Sub
 
Last edited:
Cookies are required to use this site. You must accept them to continue using the site. Learn more…