Spanish Cómo insertar una foto recién tomada en un Imageview que está en Customlistview

jalvarez

Member
Licensed User
Longtime User
Hola a todos!
recién ayer puse un post en inglés pero no ha sido respondido, ojalá tenga más suerte por aquí. Tengo un CustomListView que tiene un layout con 3 objetos, (1 imageview, 1 checkbox y un textlabel) he insertado 102 conceptos diferentes en cada textlabel del listview, puedo activar/desactivar el checkbox pero cuando intento agregar una foto desde la cámara hacia el control imageview1 desde donde hice click para insertarlo, lo coloca en cada uno de los paneles. Por favor indíquenme el camino correcto; les agrego la parte del código para que me ayude alguién con más experiencia en esta pieza de software.

Gracias por su soporte.

B4X:
#Region Module Attributes
    #FullScreen: False
    #IncludeTitle: False
    #ApplicationLabel: Checklist
    #VersionCode: 1
    #VersionName:
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: true
#End Region

'Activity module
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Public SQL1 As SQL
    Public ccursor As Cursor
    Public mtda As String, msuper As String, mcity As String, medo As String, mfolio As String, mdate As String, meval As Int
    Private ion As Object
    Private const tempImageFile As String = "tempimage.jpg"
    Public imageFolder As String
    Public lastPicture As Bitmap
End Sub

Sub Globals
    Dim sm As SlideMenu
   
    Private cp As ListView
    Private Edita As Button
    Private Guarda As Button
    Private Panel1 As Panel
    Private Panel2 As Panel
    Dim p As Panel
   
    Private Ciudad As Label
    Private Tienda As Label
    Private Supervisor As Label
    Private NuevaTda As Button
    Private LblFinEval As Label
   
    Public EditCity As EditText
    Public EditEstado As EditText
    Public EditTda As EditText
    Public LblFecha As Label
    Public LblFolio As Label
    Public EditSuper As EditText
   
    Public LblEvFinVal As Label
    Private Checklist As Button
   
    Public clv2 As CustomListView
    Private CheckBox1 As CheckBox
    Private Label1 As Label
    Private Button1 As Button
   
    Public ImageView1 As ImageView
    Dim line As String
    Public uri As Uri
   
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
   
    If FirstTime Then
        'Log(File.DirRootExternal)
        'Fijo la carpeta de las imagenes para luego recuperarlas.
        imageFolder = Starter.rp.GetSafeDirDefaultExternal("")
       
         If File.Exists(File.DirRootExternal,  "Checklist.db") = False Then
            SQL1.Initialize(File.DirRootExternal, "Checklist.db",True)
            CreateTables
        Else
            SQL1.Initialize(File.DirRootExternal, "Checklist.db",True)
           
        End If
       
    End If
   
    'ImageViews.Initialize   
    sm.Initialize(Activity, Me, "SlideMenu", 42dip, 180dip)
   
    sm.AddItem("Item #1", LoadBitmap(File.DirAssets, "bomb.png"), 1)
    sm.AddItem("Item #2", LoadBitmap(File.DirAssets, "book_add.png"), 2)
    sm.AddItem("Item #3", LoadBitmap(File.DirAssets, "book_open.png"), 3)
    sm.AddItem("Item #4", LoadBitmap(File.DirAssets, "wrench.png"), 4)
    sm.AddItem("Item #5", LoadBitmap(File.DirAssets, "wrench_orange.png"), 5)
    sm.AddItem("Item #6", Null, 6)
    sm.AddItem("Item #7", Null, 7)
    
    End Sub
   
Sub CreateTables
    'SQL1.ExecNonQuery("DROP TABLE IF EXISTS Tiendas")
    SQL1.ExecNonQuery("CREATE TABLE Chklist (ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,Tienda INTEGER,Concepto TEXT,Estatus INTEGER,Imagen1 TEXT, Imagen2 TEXT, Imagen3 TEXT, Notas TEXT)")
    SQL1.ExecNonQuery("CREATE TABLE Tiendas (ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,Tienda INTEGER,Supervisor TEXT,Ciudad    TEXT,Estado    TEXT,Folio TEXT,Fecha TEXT,EvalFinal INTEGER)")
   
End Sub
Sub LlenaDatos
               
    ccursor=SQL1.ExecQuery("Select * from Tiendas")
    If ccursor.RowCount > 0 Then
       
        ccursor.Position = 1
            mtda = ccursor.GetInt("Tienda")
            msuper = ccursor.GetString("Supervisor")
            mcity= ccursor.GetString("Ciudad")
            medo= ccursor.GetString("Estado")
            mdate = ccursor.GetString("Fecha")
            mfolio = ccursor.GetString("Folio")
            meval = ccursor.GetInt("EvalFinal")
            'NuevaTda_Click
            EditTda.Text = mtda
            EditSuper.Text = msuper
            EditCity.Text = mcity
            EditEstado.Text = medo
            LblFecha.Text = mdate
            LblFolio.Text = mfolio & mdate
            LblEvFinVal.Text = meval
           
            Panel1.Visible=True
           
    End If
End Sub

Sub Activity_Resume
    If SQL1.IsInitialized = False Then
        SQL1.Initialize(File.DirRootExternal, "Checklist.db",True)
    End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
If UserClosed Then
        SQL1.Close 'if the user closes the program we close the database
End If
End Sub

'We capture the menu and back keys
Sub Activity_KeyPress (KeyCode As Int) As Boolean
    'Pressing the back key while the slidemenu is open will close it
    If KeyCode = KeyCodes.KEYCODE_BACK And sm.isVisible Then
        sm.Hide
        Return True
    End If

    'Pressing the menu key will open/close the slidemenu
    If KeyCode = KeyCodes.KEYCODE_MENU Then
        If sm.isVisible Then sm.Hide Else sm.Show
        Return True
    End If
End Sub

'Show the slidemenu
Sub btnShow_Click
    sm.Show
End Sub

'Event sub which is called when an item in the slidemenu is clicked
Sub SlideMenu_Click(Item As Object)
    'ToastMessageShow("Item clicked: " & Item, False)
   
    Select Item
    Case 1
        Activity.LoadLayout("lytpanel1")
        If Panel2.IsInitialized Then
            Panel2.Visible = False
        End If
        LlenaDatos
    Case 2
        Activity.LoadLayout("lytpanel2")
        If Panel1.IsInitialized Then
            Panel1.Visible=False
        End If
        Checklist_Click
    End Select
   
End Sub

'Sub RemoveAllViews
'    Dim i As Int
'   
'    For i = Activity.NumberOfViews - 1 To 0 Step -1
'        Activity.RemoveViewAt(i)
'    Next
'End Sub

Sub Guarda_Click
    mtda = EditTda.Text
    msuper = EditSuper.Text
    mcity = EditCity.Text
    medo = EditEstado.Text
    mfolio = LblFecha.Text
    mdate = LblFecha.Text
    meval = 0
    SQL1.ExecNonQuery2("INSERT INTO Tiendas values (?,?,?,?,?,?,?,?)" , Array As Object(Null,mtda,msuper,mcity,medo,mfolio,mdate,meval))
    Msgbox("Datos guardados correctamente...","Aviso")
    NuevaTda_Click
End Sub

Sub EditTda_TextChanged (Old As String, New As String)
    LblFecha.Text = DateTime.Date(DateTime.Now) 'pongo la fecha en el campo de label de fecha
End Sub

Sub NuevaTda_Click
    EditTda.Text = ""
    EditSuper.Text = ""
    EditCity.Text = ""
    EditEstado.Text = ""
    LblFecha.Text = ""
    LblFolio.Text = ""
    LblEvFinVal.Text = ""
End Sub

Sub Checklist_Click
    If Panel1.IsInitialized Then
            Panel1.Visible=False
    End If
    FillConceptos
    Activity.LoadLayout("lytpanel2")
    Dim TextReader1 As TextReader
'    p.Initialize("")
    'CheckBox1.Initialize("Checkbox1")
    clv2.Initialize(Me,"clv2")
   
    Activity.AddView(clv2.AsView, 5, 10%y, 100%x, 60%y) ' aquí cambio el tamaño del customlistview
    TextReader1.Initialize(File.OpenInput(File.DirRootExternal, "Conceptos.txt"))
   
    For i=1 To 102
    Do While line <> Null
         line = TextReader1.ReadLine
        
        'clv2.AddTextItem(line,"")
            clv2.Add(CreateListItem($"Item #${i}"$, clv2.AsView.Width, 70dip), 115dip, $"Item #${i}"$)
        'Log(line) 'write the line to LogCat
    Loop
    Next
    TextReader1.Close   
   
End Sub
' aqui se integran los elementos del CustomListview
Sub CreateListItem(Text As String, Width As Int, Height As Int) As Panel
    Dim p As Panel
    p.Initialize("")
    'lastPicture = LoadBitmapSample(imageFolder, tempImageFile, ImageView1.Width, ImageView1.Height)
   
    'we need to add the panel to a parent to set its dimensions. It will be removed after the layout is loaded.
    Activity.AddView(p, 0, 0, Width, Height)
    p.LoadLayout("CelItem")
    p.RemoveView
    'If lastPicture.IsInitialized Then ImageView1.Bitmap = lastPicture
    'label1 and button1 will point to the last added views.
    Label1.Text = line
    'ImageView1.Bitmap = lastPicture
    'ImageView1.Bitmap = LoadBitmapSample(imageFolder,tempImageFile,100,100)
    Return p
End Sub


Sub CheckBox1_CheckedChange(Checked As Boolean)
    Dim index As Int= clv2.GetItemFromView(Sender)
    Dim pnl As Panel = clv2.GetPanel(index)
    Dim chk As CheckBox = pnl.GetView(1)

'    Msgbox($"Item value: ${clv2.GetValue(index)}
'     Check value: ${chk.Checked}"$, "")
End Sub

'aqui se llena la etiqueta Label1 con los conceptos del archivo de texto Conceptos
Sub FillConceptos
   
    ccursor=SQL1.ExecQuery("Select * from Chklist")
    If ccursor.RowCount = 0 Then
        ReadTextReader
    End If
    If ccursor.RowCount > 0 Then
        ccursor.Position = 1
       
    End If
End Sub

'Sub que llena el campo con cada concepto del lector de textos que lee al archivo conceptos.txt
Sub ReadTextReader
    Dim TextReader1 As TextReader
    TextReader1.Initialize(File.OpenInput(File.DirRootExternal, "Conceptos.txt"))
    Dim mtienda, status As Int
    Dim imagen1 As String
    Dim imagen2 As String
    Dim imagen3 As String
    Dim line, notas As String
    mtienda = 0
    status= 0
    imagen1 = ""
    imagen2 = ""
    imagen3 = ""
    notas = ""
    line = TextReader1.ReadLine   
    Do While line <> Null
        SQL1.ExecNonQuery2("INSERT INTO Chklist VALUES (?,?,?,?,?,?,?,?)", Array As Object(Null,mtienda,line,status,imagen1,imagen2,imagen3,notas))
        'Log(line) 'write the line to LogCat
        line = TextReader1.ReadLine
    Loop
    TextReader1.Close
End Sub

'Sub LoadImages
'    Bitmaps.Initialize
'    Dim files As List
'    Dim imagesFolder As String
'    imagesFolder = File.DirAssets
'
'    If File.Exists(imagesFolder, "") = False Then
'        ToastMessageShow("Images folder not found: " & CRLF & imagesFolder, True)
'        Return
'    End If
'    files = File.ListFiles(imagesFolder) 'get all files in this folder
'    For i = 0 To files.Size - 1
'        DoEvents 'required for the ProgressDialog animation
'        Dim f As String
'        f = files.Get(i)
'        If f.ToLowerCase.EndsWith(".jpg") Then
'            Dim b As Bitmap
'            b.InitializeSample(imagesFolder, f, 200dip, 200dip) 'load the jpeg file and subsample it if it is too large.
'            Bitmaps.Add(b) 'add the bitmap to the bitmaps list.
'            If Bitmaps.Size > 150 Then Exit 'limit it to 50 images
'        End If
'    Next
'    ToastMessageShow("Found " & Bitmaps.Size & " images", True)
'End Sub

Sub ImageView1_Click
    Dim index As Int = clv2.GetItemFromView(Sender)
    Dim pnl As Panel = clv2.GetPanel(index)
    ImageView1.Initialize("Imageview1")
    TakePicture
    ImageView1.Bitmap = LoadBitmapSample(imageFolder,tempImageFile,100,100)
   
End Sub

Sub TakePicture
    Dim i As Intent
    i.Initialize("android.media.action.IMAGE_CAPTURE", "")
    Dim uri As Uri
    File.Delete(imageFolder, tempImageFile)
    uri.Parse("file://" & File.Combine(imageFolder, tempImageFile))
    i.PutExtra("output", uri) 'the image will be saved to this path
    Try
        StartActivityForResult(i)
    Catch
        ToastMessageShow("La cámara no está disponible.", True)
        Log(LastException)
    End Try
End Sub

'result arrives here
Sub ion_Event (MethodName As String, Args() As Object) As Object
    If Args(0) = -1 Then
        Try
            Dim in As Intent = Args(1)
            If File.Exists(imageFolder, tempImageFile) Then
                lastPicture = LoadBitmapSample(imageFolder, tempImageFile, 100, 100)
                ImageView1.Bitmap = lastPicture
            Else If in.HasExtra("data") Then 'try to get thumbnail instead
                Dim jo As JavaObject = in
                lastPicture = jo.RunMethodJO("getExtras", Null).RunMethod("get", Array("data"))
            End If
        Catch
            Log(LastException)
        End Try
    End If
    If lastPicture.IsInitialized Then ImageView1.Bitmap = lastPicture
    Return Null
End Sub
'Sub TomaFoto
'    Dim i As Intent
'    i.Initialize("android.media.action.IMAGE_CAPTURE", "")
'    If File.Exists(imageFolder,tempImageFile) Then      
'     lastPicture = LoadBitmapSample(imageFolder, tempImageFile, ImageView1.Width, ImageView1.Height)
'                ImageView1.Bitmap = lastPicture  'ImageView1.Initialize("iv1")
'    Else If in.HasExtra("data") Then 'try to get thumbnail instead
'                Dim jo As JavaObject = in
'                lastPicture = jo.RunMethodJO("getExtras", Null).RunMethod("get", Array("data"))
'    End If
'       'File.Delete(imageFolder, tempImageFile)
'        'ImageView1.Bitmap =  LoadBitmapSample(imageFolder,tempImageFile,100,100)
'   
'    uri.Parse("file://" & File.Combine(imageFolder, tempImageFile))
'    i.PutExtra("output", uri) 'the image will be saved to this path
'    Try
'        StartActivityForResult(i)
'    Catch
'        ToastMessageShow("La Cámara no está disponible.", True)
'        Log(LastException)
'    End Try
'End Sub

Sub StartActivityForResult(i As Intent)
   Dim jo As JavaObject = GetBA
   ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
   jo.RunMethod("startActivityForResult", Array As Object(ion, i))
End Sub

Sub GetBA As Object
   Dim jo As JavaObject
   Dim cls As String = Me
   cls = cls.SubString("class ".Length)
   jo.InitializeStatic(cls)
   Return jo.GetField("processBA")
End Sub
 

bgsoft

Well-Known Member
Licensed User
Longtime User
Hola jalvarez

Acabo de llegar de las vacaciones y es un poco duro leer todo ese codigo, le he pegado un vistazo por encima, creo que tendrias menos problemas si utilizaras la libreria de la cámara y su wraps: https://www.b4x.com/android/forum/t...e-camera-library-functionality.23801/#content

Cuando hagas la captura irá al evento:

B4X:
Sub EventoCamara_PictureTaken (Data() As Byte)

Luego ahí con una simple linea la grabas:

B4X:
camEx.SavePictureToFile(Data, DirFoto, NombreImagen)

Te aconnsejo que le des el nombre a la imagen de la fecha y la hora actual en un formato algo asi: aaaammddhhmmss de esa forma no tendras dos imagenes iguales que posiblemente es lo que te esté pasando.

Saludos
 

bgsoft

Well-Known Member
Licensed User
Longtime User
Hola

Si ya lo solucionaste, podrias añadir a la cabecera [SOLUCIONADO], gracias.

Saludos
 
Top