Android Question Getting sequence in my subs

m643

Member
Licensed User
Longtime User
Hi All,

I'm reading records from a Mysql database and store it locally in the sqlite database. Then I want to add from my local db the items into the custom listview.
The problem is that reading from the sqlite db is not working well because it needs first getting the records from the mysql db.

So my quetion is how can I getting a sequence in my subs, so it will first getting the mysql records and when that is done its needs to read from the sqllite and add the items into the listview?

Thank you.
 

m643

Member
Licensed User
Longtime User
Hi erel, thank you for your reply.
I tried to follow the logical flow from the JobDone sub, but I still having problems that the job is running while the sub is ended (after job.release). I tried to implement a pause after job.release but that's also not the ultimate solution.
 
Upvote 0

m643

Member
Licensed User
Longtime User
In the jobdone sub I'm inserting the records and the downloaded images into the local database. After inserting, I want to call a sub to read the local records into the custom listview. Problem is that reading the local records starts to early, the result is that the custom listview is empty. I'm calling the reading sub after job.release.
 
Upvote 0

m643

Member
Licensed User
Longtime User
B4X:
Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("design")
    SQL1.Initialize(File.DirDefaultExternal, "testdb", True)
    ImageViews.Initialize
    ListviewSpotsCustom.Initialize(Me, "ListviewSpotsCustom")
    PanelItems.AddView(ListviewSpotsCustom.AsView, 0, 0, 100%x, 90%y)
    CreateTables        'create tables when it not exists
`  getnewitems        'call sub to getting items from mysql server
       
End Sub

Sub Getnewspots           
    ExecuteRemoteQuery("SELECT * FROM movies ORDER BY title ASC", SPOT_LIST)       
End Sub

Sub ExecuteRemoteQuery(Query As String, JobName As String)
    Dim job As HttpJob
    job.Initialize(JobName, Me)
    job.PostString("http://****/android.php", 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 MOVIE_LIST
                Dim movies As List
                Dim job1 As HttpJob
                movies = parser.NextArray 'returns a list with maps
                For i = 0 To movies.Size - 1
                    Dim m As Map
                    m = movies.Get(i)
                        id = m.Get("id")
                    Dim actorstemp = m.Get("actors")
                    Dim actors = actorstemp.Replace("'","''")
                    Dim titletemp = m.Get("title")
                    Dim title = titletemp.Replace("'","''")
                   
                    Dim Cursor1 As Cursor
                    Cursor1 = SQL1.ExecQuery("SELECT * FROM movies WHERE id='" & m.Get("id") & "'")
                    Cursor1.Position = 0
                    SQL1.ExecNonQuery("INSERT INTO movies (id,title,actors,thumbnail) VALUES('" & m.Get("id") & "','" & title & "','" & actors & "','" & m.Get("thumbnail") &"')")           
                    Dim ImageJob As HttpJob
                    ImageJob.Initialize("ImageJob", Me)
                    ImageJob.Download(m.Get("thumbnail"))
                    ImageJob.Tag = m.Get("id")
                Next
                myProgressDialog.Hide               
            Case "ImageJob"
                Dim InputStream1 As InputStream
                InputStream1 = Job.GetInputStream
                Dim OutputStream1 As OutputStream
                OutputStream1.InitializeToBytesArray(1000)
                File.Copy2(InputStream1, OutputStream1)
                Dim Buffer() As Byte 'declares an empty array
                Buffer = OutputStream1.ToBytesArray
                'write the image To the database
                    SQL1.ExecNonQuery2("INSERT INTO images VALUES('" & Job.Tag & "', ?)", Array As Object(Buffer))               
       
        End Select
    Else
        ToastMessageShow("Error: " & Job.ErrorMessage, True)
    End If
   
    Job.Release
    Readspots 'This is the problem, it calls to early the readspots url while the job is not complete
End Sub

Sub Readspots
    Dim Cursor2 As Cursor
    Dim Buffer() As Byte 'declare an empty byte array
    Cursor2 = SQL1.ExecQuery("SELECT * FROM movies,images WHERE movies.id=images.id")
    For i = 0 To Cursor2.RowCount - 1
        Cursor2.Position = i
        Buffer = Cursor2.GetBlob("image")
        Dim InputStream1 As InputStream
        InputStream1.InitializeFromBytesArray(Buffer, 0, Buffer.Length)
        Dim Bitmap1 As Bitmap
        Bitmap1.Initialize2(InputStream1)
       
        Dim p As Panel
        p.Initialize("")
        ListviewSpotsCustom.Add(p, 75dip, Cursor2.GetString("title"))
        p.LoadLayout("listItem")

        Dim richlinea As RichString
        richlinea.initialize("{BI}" & Cursor2.GetString("title") & "{BI}" & " (" & Cursor2.GetString("year") & ")" & CRLF & "{IT}" & Cursor2.GetString("actors") & "{IT}" & CRLF & "{R}" & "{R}" )
        richlinea.color2(Colors.Yellow,"{C}")
        richlinea.Style2(richlinea.STYLE_BOLD, "{BI}")
        richlinea.Style2(richlinea.STYLE_ITALIC, "{IT}")
        richlinea.RelativeSize2(0.8, "{R}")
        richlinea.Typeface2("serif", "{T}")
        Label2.text=richlinea  'Where lbl1 is a label view

        ImageViews.Add(ImageView1)
        ImageView1.SetBackgroundImage(Bitmap1)
       
        InputStream1.Close
    Next
    Cursor2.Close   
End Sub
 
Upvote 0

m643

Member
Licensed User
Longtime User
Hi Erel,

I did some tests and I find out that when I just insert the items without downloading the images, the readspots sub is going fine.
So I think that the problem is in downloading all the thumbnails for about 80 items. That the delay in this job.

Do you know an other good way to download thumbnails and insert it into a table before I added it into the customlistview?
 
Upvote 0

m643

Member
Licensed User
Longtime User
Oke Erel, but can you help me how I can put the image into a blob table?
I tried this but I get a Java nullpointer exception:

B4X:
Sub JobDone(Job As HttpJob)
    ongoingTasks.Remove(Job.JobName)
    If Job.Success Then
        Dim bmp As Bitmap = Job.GetBitmap
        cache.Put(Job.JobName, bmp)
        If tasks.IsInitialized Then
            For i = 0 To tasks.Size - 1
                Dim link As String = tasks.GetValueAt(i)
                If link = Job.JobName Then
                    'Dim iv As ImageView = tasks.GetKeyAt(i)
                    'iv.SetBackgroundImage(bmp)
                    Dim InputStream1 As InputStream
                    InputStream1 = Job.GetInputStream
                    Dim OutputStream1 As OutputStream
                    OutputStream1.InitializeToBytesArray(1000)
                    File.Copy2(InputStream1, OutputStream1)
                    Dim Buffer() As Byte 'declares an empty array
                    Buffer = OutputStream1.ToBytesArray
                    SQL1.ExecNonQuery2("INSERT INTO images VALUES('test', ?)", Array As Object(Buffer))

                End If
            Next
        End If
    Else
        Log("Error downloading image: " & Job.JobName & CRLF & Job.ErrorMessage)
    End If
    Job.Release
End Sub
 
Upvote 0

m643

Member
Licensed User
Longtime User
Hi Erel, thank you for your support. It is in line 61 which is:
B4X:
SQL1.ExecNonQuery2("INSERT INTO images VALUES('test', ?)", Array As Object(Buffer))

Full error:
B4X:
imagedownloader_jobdone (B4A line: 61)
SQL1.ExecNonQuery2("INSERT INTO images VALUES('test', ?)", Array As Object(Buffer))
java.lang.NullPointerException
    at anywheresoftware.b4a.sql.SQL.ExecNonQuery2(SQL.java:78)
    at b4a.example.imagedownloader._jobdone(imagedownloader.java:231)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:169)
    at anywheresoftware.b4a.keywords.Common$4.run(Common.java:930)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:158)
    at android.app.ActivityThread.main(ActivityThread.java:5777)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
    at dalvik.system.NativeStart.main(Native Method)
 
Upvote 0

m643

Member
Licensed User
Longtime User
Hi Erel,

I still have problems with downloading a lot of images with the Imagedownloader service.
When I defined all the Image urls before like this then everything goes well:

B4X:
Dim links As Map
links.Initialize
links.Put("id1", "Image1")
links.Put("id2", "Image1")
links.Put("id3", "Image1")
links.Put("id4", "Image1")
links.Put("id5", "Image1")
CallSubDelayed2(ImageDownloader, "Download", links)

I can download over the 600 images and everything is going fine. But when I fill the map links from an array that contains more than 60 times, it will only download like 8 images, other times it is 4. I can't find a line in that. The code for the for loop:

B4X:
Dim links As Map
links.Initialize

For i = 0 To ImageDownloader.Thumbnails.Size - 1
        links.Put(ImageDownloader.Thumbnails.GetKeyAt(i), ImageDownloader.Thumbnails.GetValueAt(i))
Next
CallSubDelayed2(ImageDownloader, "Download", links)

I hope you can help me
 
Upvote 0

m643

Member
Licensed User
Longtime User
Activity Main:

B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim SQL1 As SQL
End Sub

Sub Globals
End Sub

Sub Activity_Create(FirstTime As Boolean)
    SQL1.Initialize(File.DirDefaultExternal, "testdb", True)
    SQL1.ExecNonQuery("DROP TABLE IF EXISTS images")
    SQL1.ExecNonQuery("CREATE TABLE IF NOT EXISTS images (imdb_id TEXT PRIMARY KEY, image BLOB)")
 
    If FirstTime=True Then
        getnew
    End If

End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub getnew

    CallSubDelayed3(SQLrecorddownloader, "ExecuteRemoteQuery", "SELECT * FROM Table", "RetrieveRecords")

End Sub

Sub DownloadImages
    Dim links As Map
    links.Initialize
 
    For i = 0 To SQLrecorddownloader.Thumbnails.Size - 1
        links.Put(SQLrecorddownloader.Thumbnails.GetKeyAt(i), SQLrecorddownloader.Thumbnails.GetValueAt(i))
    Next

    CallSubDelayed2(ImageDownloader, "Download", links)
End Sub

SQLrecorddownloader
B4X:
#Region  Service Attributes
    #StartAtBoot: False
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim SQL1 As SQL
    Dim Thumbnails As Map
End Sub
Sub Service_Create

End Sub

Sub Service_Start (StartingIntent As Intent)

End Sub

Sub Service_Destroy

End Sub

Sub ExecuteRemoteQuery(Query As String, JobName As String)
    Dim job As HttpJob
    job.Initialize(JobName, Me)
    job.PostString("http://xxx/basic4android.php", Query)
End Sub

Sub JobDone(Job As HttpJob)
    If Job.Success Then
        Dim res As String
        res = Job.GetString
        'Log("Response from server2: " & res)
        Dim parser As JSONParser
        parser.Initialize(res)
     
        Select Job.JobName
            Case "RetrieveRecords"
                Thumbnails.Initialize
                Dim links As Map
                links.Initialize
                Dim COUNTRIES As List
                Dim job1 As HttpJob
                COUNTRIES = parser.NextArray 'returns a list with maps
                'ListViewSpots.Initialize("ListViewSpots")
                For i = 0 To COUNTRIES.Size - 1
                    Dim m As Map
                    m = COUNTRIES.Get(i)
                    Thumbnails.Put(m.Get("id"),m.Get("thumbnail"))
                Next
         
            CallSubDelayed(Main,"DownloadImages")
        End Select
    Else
        Log("Error downloading image: " & Job.JobName & CRLF & Job.ErrorMessage)
    End If
 
    Job.Release
    ProgressDialogHide
End Sub

Imagedownloader service
B4X:
#Region  Service Attributes
    #StartAtBoot: False
#End Region

Sub Process_Globals
    Private cache As Map
    Private tasks As Map
    Private ongoingTasks As Map
    Dim SQL1 As SQL
End Sub

Sub Service_Create
    tasks.Initialize
    cache.Initialize
    ongoingTasks.Initialize
End Sub

Sub Service_Start (StartingIntent As Intent)
    SQL1.Initialize(File.DirDefaultExternal, "testdb", True)
End Sub

Sub Service_Destroy

End Sub

Sub Download (ImageViewsMap As Map)
    For i = 0 To ImageViewsMap.Size - 1
        tasks.Put(ImageViewsMap.GetKeyAt(i), ImageViewsMap.GetValueAt(i))
        Dim link As String = ImageViewsMap.GetValueAt(i)
        If cache.ContainsKey(link) Then
            'Dim iv As ImageView = ImageViewsMap.GetKeyAt(i)
            'iv.SetBackgroundImage(cache.Get(link))
        Else If ongoingTasks.ContainsKey(link) = False Then
            ongoingTasks.Put(link, "")
            Dim j As HttpJob
            j.Initialize(link, Me)
            j.Download(link)
        End If
    Next
End Sub

Sub JobDone(Job As HttpJob)
    ongoingTasks.Remove(Job.JobName)
    If Job.Success Then
        Dim bmp As Bitmap = Job.GetBitmap
        cache.Put(Job.JobName, bmp)
        If tasks.IsInitialized Then
            For i = 0 To tasks.Size - 1
                Dim link As String = tasks.GetValueAt(i)
                If link = Job.JobName Then
                    Dim InputStream1 As InputStream
                    InputStream1 = Job.GetInputStream
                    Dim OutputStream1 As OutputStream
                    OutputStream1.InitializeToBytesArray(1000)
                    File.Copy2(InputStream1, OutputStream1)
                    Dim Buffer() As Byte 'declares an empty array
                    Buffer = OutputStream1.ToBytesArray

                    SQL1.ExecNonQuery2("INSERT INTO images VALUES('" & tasks.GetKeyAt(i) & "', ?)", Array As Object(Buffer))
                End If
            Next
        End If
    Else
        Log("Error downloading image: " & Job.JobName & CRLF & Job.ErrorMessage)
    End If
    Job.Release
End Sub

Sub ActivityIsPaused
    tasks.Clear
End Sub
 
Upvote 0
Top