Android Question How to read a blob field from firebird and store it on sqllite?

Gabino A. de la Gala

Well-Known Member
Licensed User
Longtime User
I'm trying read it like this:

B4X:
Dim ListOfMaps As List
                Dim b() As Byte
                Dim s As StringUtils
              
                ListOfMaps = parser.NextArray 'returns a list with maps
                If ListOfMaps.Size > 0 Then
                        ' Inicializo la copia de los datos locales...
                        InicializarTablaLocal(Main.LISTA_FOTOS)
                      
                        For i = 0 To ListOfMaps.Size -1
                            ProgressBar1.Progress=Round(ListOfMaps.Size / i+1)
                            Dim mapaAux As Map
                            mapaAux = ListOfMaps.Get(i)
                            b = s.DecodeBase64(mapaAux.Get("FOTO"))
                            mapaAux.Put("FOTO", BytesToString(b, 0, b.Length, "iso-8859-1"))
                        Next
                      
                        ' Inserto los datos obtenidos del servidor para la copia local
                        DBUtils.InsertMaps(Sql1, "FOTOS", ListOfMaps)
                        Label2.Text = ListOfMaps.Size
                        ToastMessageShow("FOTOS Insertadas: " & (ListOfMaps.Size), True)
                        MenuSincronizar.FotosImportadas = ListOfMaps.Size
                    Else
                        ToastMessageShow("Error: " & Job.ErrorMessage, True)
                        ToastMessageShow("Error: No se obtuvieron registros", True)
                End If

and y trying to store it like this:

B4X:
SqlQuery = "SELECT * FROM FOTOS"
ExecuteRemoteQuery(SqlQuery, Lista)

Sub ExecuteRemoteQuery(Query As String, JobName As String)
    Dim job As HttpJob
    job.Initialize(JobName, Me)
    job.PostString(Main.Url, Query)
End Sub

Sub JobDone(Job As HttpJob)
    If Job.Success Then
        Dim res As String
        res = Job.GetString
        Log("Response from server: " & res)
        Dim parser As JSONParser
        parser.Initialize(res)
        Select Job.JobName
            Case Main.LISTA_SERIALES
               ...
            Case Main.LISTA_CLIENTES
               ...
            Case Main.LISTA_ALMACEN
               ...
            Case Main.LISTA_CODIGOSAUX
               ...
            Case Main.LISTA_FOTOS
                Dim ListOfMaps As List
                Dim b() As Byte
                Dim s As StringUtils
                Dim Bitmap1 As Bitmap
               
                ListOfMaps = parser.NextArray 'returns a list with maps
                If ListOfMaps.Size > 0 Then
                        ' Inicializo la copia de los datos locales...
                        InicializarTablaLocal(Main.LISTA_FOTOS)
                       
                        For i = 0 To ListOfMaps.Size -1
                            ProgressBar1.Progress=Round(ListOfMaps.Size / i+1)
                            Dim mapaAux As Map
                            mapaAux = ListOfMaps.Get(i)
                            ' Intento hacer la conversión del valor obtenido en el JSON antes de meterlo en la tabla de SQLLite
                            b = s.DecodeBase64(mapaAux.Get("FOTO"))
                            mapaAux.Put("FOTO", BytesToString(b, 0, b.Length, "iso-8859-1"))
                            ListView1.AddSingleLine(mapaAux.GetValueAt(0))
                        Next
                       
                        ' Inserto los datos obtenidos del servidor para la copia local
                        DBUtils.InsertMaps(Sql1, "FOTOS", ListOfMaps)
                        Label2.Text = ListOfMaps.Size
                        ToastMessageShow("FOTOS Insertadas: " & (ListOfMaps.Size), True)
                        MenuSincronizar.FotosImportadas = ListOfMaps.Size
                    Else
                        ToastMessageShow("Error: " & Job.ErrorMessage, True)
                        ToastMessageShow("Error: No se obtuvieron registros", True)
                End If
        End Select
    Else
        ToastMessageShow("Error: " & Job.ErrorMessage, True)
        ToastMessageShow("Error: No se pudieron actualizar los datos", True)
    End If
    ProgressDialogHide
    Job.Release
    Activity.Finish
End Sub

After I try to obtain the data stored:

B4X:
 Sub ReadBlob(codigo As Int)
           
    Dim Cursor1 As Cursor
    Dim Buffer() As Byte
    Dim IpSt As InputStream
    Dim Bitmap1 As Bitmap
    Cursor1 = Sql1.ExecQuery("SELECT * FROM fotos WHERE codigo = '" & codigo & "' ;")

    If Cursor1.RowCount > 0 Then
       For i = 0 To Cursor1.RowCount - 1
           Cursor1.Position = i
       Next
     
       Buffer = Cursor1.GetBlob("FOTO")
       IpSt.InitializeFromBytesArray(Buffer, 0, Buffer.Length)
       Bitmap1.Initialize2(IpSt)
       IpSt.Close
       ImageView1.SetBackgroundImage(Bitmap1)
    End If
    Cursor1.Close
End Sub
But it doesn't work correctly. I obtain this error: Error loading Bitmap

The FOTO field stored is not recognized like valib Blob in database. Tipical [BLOB] in the result of the sql is not obtained. Is showed like a very long string...

Can anybody help me?

Thanks.

Sorry for my poor English. I'm Spanish.
 

Gabino A. de la Gala

Well-Known Member
Licensed User
Longtime User
try this how to read the blob , if you uploaded it correctly and your database field is on blob
had the same problem
http://www.b4x.com/android/forum/th...n-not-to-close-the-inputstream.32073/#content

correction up
sorry i missed you uploading it as a string , try to upload as bytes

see here
http://www.b4x.com/android/forum/threads/sql-tutorial.6736/#content

Thanks for your answer.

I think I've got it finally in two diferents ways. One saving in blob field and other saving in a .jpg file.

B4X:
Select Job.JobName
    Case Main.LISTA_FOTOS
                Dim ListOfMaps As List
                Dim buffer() As Byte
                Dim S As StringUtils
                Dim Bitmap1 As Bitmap
                Dim Ini As InputStream
             
                ListOfMaps = parser.NextArray 'returns a list with maps
                If ListOfMaps.Size > 0 Then
                        ' Inicializo la copia de los datos locales...
                        InicializarTablaLocal(Main.LISTA_FOTOS)
                     
                        For i = 0 To ListOfMaps.Size -1
                            ProgressBar1.Progress=Round(ListOfMaps.Size / i+1)
                            Dim mapaAux As Map
                            mapaAux = ListOfMaps.Get(i)
                            ' Decodifico los datos obtenidos mediante el json
                            buffer = S.DecodeBase64(mapaAux.Get("FOTO"))
                            ' Preparo un batch de sql's para que se realizen luego en segundo plano
                            Sql1.AddNonQueryToBatch( "INSERT INTO FOTOS VALUES("& mapaAux.Get("CODIGO") &", ?)", Array As Object(buffer))
                         
                            ' Prepara un InputStream con el contenido del array de bytes resultante de la decodificación
                              Ini.InitializeFromBytesArray(buffer,0,buffer.Length)
                            ' Inicializo el bitmap con el inputstream obtenido anteriormente
                            Bitmap1.Initialize2(Ini)
                            ' Grabo en disco el fichero correspondiente
                            SavePhoto(Bitmap1,mapaAux.Get("CODIGO")&".JPG")
                         
                            ' Ahora queda concretar como almacenarlo en la base de datos o trabajar con los ficheros físicos
                            mapaAux.Put("FOTO", BytesToString(buffer, 0, buffer.Length, "iso-8859-1"))
                         
                            ListView1.AddSingleLine(mapaAux.GetValueAt(0))
                            SavePhoto(Bitmap1,mapaAux.Get("CODIGO")&".JPG")
                        Next
                        ' Inserto los datos obtenidos del servidor para la copia local
                        ' Lanzo el batch de inserción
                        Sql1.ExecNonQueryBatch("SQL")
                     
                        Label2.Text = ListOfMaps.Size
                        ToastMessageShow("FOTOS Insertadas: " & (ListOfMaps.Size), True)
                        MenuSincronizar.FotosImportadas = ListOfMaps.Size
                    Else
                        ToastMessageShow("Error: " & Job.ErrorMessage, True)
                        ToastMessageShow("Error: No se obtuvieron registros", True)
                End If
End Select

Sub SavePhoto (Pt As Bitmap,NewFile As String)
  Dim Out As OutputStream
  Out = File.OpenOutput(File.DirRootExternal&"/Pedidroid", NewFile, False) 
  Pt.WriteToStream(Out, 100, "PNG")
  Out.Close
End Sub
 
Upvote 0
Top