Android Question Error messages for ContactsUtils library

Eric H

Active Member
Licensed User
Longtime User
I am using the contactutils library to create contacts.

I am using a line like this to create the contact. It works perfectly on my Galaxy Nexus, Galaxy S4, my wife's Galaxy S3, all the emulator variations that I have tried (android versions 2.2 to version 4.3):
B4X:
cu.InsertContact("name" , "1234567890")

Two of my friends have HTC Rhyme phones and they both get this error when they press the button in my app that would fire off the cu.InsertContact code:
B4X:
An error has occurred in sub: contactsutils_ww3(java line:574) java.Lang.NullPointerException. Continue?

I have no idea what would be causing this, and have spent quite a few hours trying different variation of ways of doing things...

Does anyone have any idea of what could be going on here?

Also, does anyone have an HTC Rhyme that they would like to try the code on to see if things are acting the same, or to try and assist (I don't own that device).

Thanks B4A folks,
Eric H
 

Eric H

Active Member
Licensed User
Longtime User
line 564 is the error line

B4X:
545  public com.dice.with.benefits.contactsutils._cucontact  _vvvv3(String _name,String _phone) throws Exception{
546  anywheresoftware.b4a.objects.ContentResolverWrapper.ContentValuesWrapper _values = null;
547  anywheresoftware.b4a.objects.ContentResolverWrapper.UriWrapper _rawuri = null;
548  long _rawcontactid = 0L;
549  com.dice.with.benefits.contactsutils._cucontact _cu = null;
550  anywheresoftware.b4a.sql.SQL.CursorWrapper _crsr = null;
551  //BA.debugLineNum = 280;BA.debugLine="Public Sub InsertContact(Name As String, Phone As String) As cuContact";
552  //BA.debugLineNum = 281;BA.debugLine="Dim values As ContentValues";
553  _values = new anywheresoftware.b4a.objects.ContentResolverWrapper.ContentValuesWrapper();
554  //BA.debugLineNum = 282;BA.debugLine="values.Initialize";
555  _values.Initialize();
556  //BA.debugLineNum = 283;BA.debugLine="values.PutNull(\"account_name\")";
557  _values.PutNull("account_name");
558  //BA.debugLineNum = 284;BA.debugLine="values.PutNull(\"account_type\")";
559  _values.PutNull("account_type");
560  //BA.debugLineNum = 285;BA.debugLine="Dim rawUri As Uri = cr.Insert(rawContactUri, values)";
561  _rawuri = new anywheresoftware.b4a.objects.ContentResolverWrapper.UriWrapper();
562  _rawuri = _vvvvv2.Insert(_vvvvv5,(android.content.ContentValues)(_values.getObject()));
563  //BA.debugLineNum = 286;BA.debugLine="Dim rawContactId As Long = rawUri.ParseId";
**564  _rawcontactid = _rawuri.ParseId();
565  //BA.debugLineNum = 288;BA.debugLine="values.Initialize";
566  _values.Initialize();
567  //BA.debugLineNum = 289;BA.debugLine="values.PutLong(\"raw_contact_id\", rawContactId)";
568  _values.PutLong("raw_contact_id",_rawcontactid);
569  //BA.debugLineNum = 290;BA.debugLine="values.PutString(\"mimetype\", \"vnd.android.cursor.item/phone_v2\")";
570  _values.PutString("mimetype","vnd.android.cursor.item/phone_v2");
571  //BA.debugLineNum = 291;BA.debugLine="values.PutInteger(\"data2\", 12) 'phone type main";
572  _values.PutInteger("data2",(int)(12));
573  //BA.debugLineNum = 292;BA.debugLine="values.PutString(\"data1\", Phone)";
574  _values.PutString("data1",_phone);
575  //BA.debugLineNum = 293;BA.debugLine="cr.Insert(dataUri, values)";
576  _vvvvv2.Insert(_vvvvv3,(android.content.ContentValues)(_values.getObject()));
577  //BA.debugLineNum = 295;BA.debugLine="values.Initialize";
578  _values.Initialize();
579  //BA.debugLineNum = 296;BA.debugLine="values.PutLong(\"raw_contact_id\", rawContactId)";
580  _values.PutLong("raw_contact_id",_rawcontactid);
581  //BA.debugLineNum = 297;BA.debugLine="values.PutString(\"mimetype\", \"vnd.android.cursor.item/name\")";
582  _values.PutString("mimetype","vnd.android.cursor.item/name");
583  //BA.debugLineNum = 298;BA.debugLine="values.PutString(\"data1\", Name)";
584  _values.PutString("data1",_name);
585  //BA.debugLineNum = 299;BA.debugLine="cr.Insert(dataUri, values)";
586  _vvvvv2.Insert(_vvvvv3,(android.content.ContentValues)(_values.getObject()));
587  //BA.debugLineNum = 300;BA.debugLine="Dim cu As cuContact";
588  _cu = new com.dice.with.benefits.contactsutils._cucontact();
589  //BA.debugLineNum = 301;BA.debugLine="cu.Initialize";
590  _cu.Initialize();
591  //BA.debugLineNum = 302;BA.debugLine="Dim crsr As Cursor = cr.Query(dataUri, Array As String(\"contact_id\", \"display_name\"),  \"raw_contact_id = ?\", _         Array As String(rawContactId), \"\")";
592  _crsr = new anywheresoftware.b4a.sql.SQL.CursorWrapper();
593  _crsr = _vvvvv2.Query(_vvvvv3,new String[]{"contact_id","display_name"},"raw_contact_id = ?",new String[]{BA.NumberToString(_rawcontactid)},"");
594  //BA.debugLineNum = 304;BA.debugLine="crsr.Position = 0";
595  _crsr.setPosition((int)(0));
596  //BA.debugLineNum = 305;BA.debugLine="cu.DisplayName = crsr.GetString(\"display_name\")";
597  _cu.DisplayName = _crsr.GetString("display_name");
598  //BA.debugLineNum = 306;BA.debugLine="cu.Id = crsr.GetLong(\"contact_id\")";
599  _cu.Id = _crsr.GetLong("contact_id");
600  //BA.debugLineNum = 307;BA.debugLine="Return cu";
601  if (true) return _cu;
602  //BA.debugLineNum = 308;BA.debugLine="End Sub";
603  return null;
604  }


O-Map
B4X:
v5=cu
v6=addemail
v7=addphone
v0=deletecontact
vv1=deletedata
vv2=deleteemail
vv3=deletephone
vv4=findallcontacts
vv5=findcontactsbymail
vv6=findcontactsbyname
vv7=findcontactsbynotes
vv0=findcontactsbyphone
vvv1=findcontactsbystarred
vvv2=findcontactsidfromdata
vvv3=findcontactswithphotos
vvv4=getdata
vvv5=getemails
vvv6=getkeyfromvalue
vvv7=getnote
vvv0=getphones
vvvv1=getphoto
vvvv2=getstarred
vvvv3=insertcontact
vvvv4=printcursor
vvvv5=setdata
vvvv6=setnote
vvvv7=setstarred
vvvv0=mailtypes
vvvvv1=phonetypes
vvvvv2=cr
vvvvv3=datauri
vvvvv4=contacturi
vvvvv5=rawcontacturi
vvvvv6=main
vvvvv7=youtube
vvvvv0=stayawake
vvvvvv1=quant
vvvvvv2=ph
 
Upvote 0

Eric H

Active Member
Licensed User
Longtime User
I'm still not able to figure out the error he is getting:
An error has occurred in sub:
contactsutils_vvvv3 (java line: 564)
java.lang.RuntimeException:
Object should first be initialized (Uri).
Continue?


(vvvv3=insertcontact)

I am going to post a stripped down version of my code here:
B4X:
Sub Process_Globals
    Dim cu As ContactsUtils
End Sub

Sub Globals
    Dim btnAdd As Button
    Dim btnRemove As Button
    Dim etxQuantity As EditText
    Dim quant As Int
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("1")
    cu.Initialize
    quant = 0
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub etxQuantity_TextChanged (Old As String, New As String)
    quant = etxQuantity.Text
End Sub

Sub btnAdd_Click
    If quant > 0 Then
        ProgressDialogShow("Creating " & quant & " fake contacts" & CRLF & "(please be patient)")
        For i = 1 To quant
            DoEvents
            cu.InsertContact("#!$" & DateTime.Now, "")
        Next
        ProgressDialogHide
    Else
        Msgbox("Enter a quantity first.", "")
    End If
End Sub

Sub btnRemove_Click
    ProgressDialogShow("Deleting all fake contacts" & CRLF & "(please be patient)")
    Dim deleteTheseContacts As List = cu.FindContactsByName("#!$", False, False)
    For Each c As cuContact In deleteTheseContacts
        DoEvents
        cu.DeleteContact(c.Id)
    Next
    ProgressDialogHide
End Sub

Here is the code for ContactsUtils:
B4X:
'version: 1.05
'Class module
Sub Class_Globals
    Type cuContact (Id As Long, DisplayName As String)
    Type cuEmail (Email As String, EmailType As String)
    Type cuPhone (Number As String, PhoneType As String)
    Private mailTypes, phoneTypes As Map
    Private cr As ContentResolver
    Private dataUri, contactUri, rawContactUri As Uri
End Sub

Public Sub Initialize
    dataUri.Parse("content://com.android.contacts/data")
    contactUri.Parse("content://com.android.contacts/contacts")
    rawContactUri.Parse("content://com.android.contacts/raw_contacts")
    cr.Initialize("cr")
    mailTypes.Initialize
    mailTypes.Put("1", "home")
    mailTypes.Put("2", "work")
    mailTypes.Put("3", "other")
    mailTypes.Put("4", "mobile")

    phoneTypes.Initialize
    phoneTypes.Put("1", "home")
    phoneTypes.Put("2", "mobile")
    phoneTypes.Put("3", "work")
    phoneTypes.Put("4", "fax_work")
    phoneTypes.Put("5", "fax_home")
    phoneTypes.Put("6", "pager")
    phoneTypes.Put("7", "other")
    phoneTypes.Put("8", "callback")
    phoneTypes.Put("9", "car")
    phoneTypes.Put("10", "company_main")
    phoneTypes.Put("11", "isdn")
    phoneTypes.Put("12", "main")
    phoneTypes.Put("13", "other_fax")
    phoneTypes.Put("14", "radio")
    phoneTypes.Put("15", "telex")
    phoneTypes.Put("16", "tty_tdd")
    phoneTypes.Put("17", "work_mobile")
    phoneTypes.Put("18", "work_pager")
    phoneTypes.Put("19", "assistant")
    phoneTypes.Put("20", "mms")
End Sub

'Returns a List with cuContact items based on the given name.
'Name - Name to look for.
'Exact - Whether to search for the exact name or to search for names that contain the given value.
'VisibleOnly - Whether to return only visible contacts.
Public Sub FindContactsByName(Name As String, Exact As Boolean, VisibleOnly As Boolean) As List
    Return FindContactsIdFromData("vnd.android.cursor.item/name", "data1", Name, "=", Exact, VisibleOnly)
End Sub

'Similar to FindContactsByName. Finds contacts based on the mail address.
Public Sub FindContactsByMail(Mail As String, Exact As Boolean, VisibleOnly As Boolean) As List
    Return FindContactsIdFromData("vnd.android.cursor.item/email_v2", "data1", Mail, "=", Exact, VisibleOnly)
End Sub

'Similar to FindContactsByName. Finds contacts based on the notes field.
Public Sub FindContactsByNotes(Note As String, Exact As Boolean, VisibleOnly As Boolean) As List
    Return FindContactsIdFromData("vnd.android.cursor.item/note", "data1", Note, "=", Exact, VisibleOnly)
End Sub

'Similar to FindContactsByName. Finds contacts based on the phone number.
Public Sub FindContactsByPhone(PhoneNumber As String, Exact As Boolean, VisibleOnly As Boolean) As List
    Return FindContactsIdFromData("vnd.android.cursor.item/phone_v2", "data1", PhoneNumber, "=", Exact, VisibleOnly)
End Sub

'Returns the starred contacts.
Public Sub FindContactsByStarred(Starred As Boolean) As List
    Dim value As String
    If Starred Then value = "1" Else value = "0"
    Return FindContactsIdFromData("vnd.android.cursor.item/name", "starred", value,"=", True, True)
End Sub
'Returns all contacts.
Public Sub FindAllContacts(VisibleOnly As Boolean) As List
    Return FindContactsIdFromData("vnd.android.cursor.item/name", "data1", "null", "<>", True, VisibleOnly)
End Sub
'Returns all contacts with a photo.
Public Sub FindContactsWithPhotos As List
    Return FindContactsIdFromData("vnd.android.cursor.item/photo", "data15", "null", "<>", True, False)
End Sub

Private Sub FindContactsIdFromData (Mime As String, DataColumn As String, Value As String, Operator As String, _
    Exact As Boolean, VisibleOnly As Boolean) As List
    If Not(Exact) Then
        Operator = "LIKE"
        Value = "%" & Value & "%"
    End If
    Dim selection As String = "mimetype = ? AND " & DataColumn & " " & Operator & " ? "
    If VisibleOnly Then selection = selection & " AND in_visible_group = 1"
    Dim crsr As Cursor = cr.Query(dataUri, Array As String("contact_id", "display_name"), selection, _
        Array As String(Mime, Value), "")
    Dim res As List
    res.Initialize
    Dim m As Map
    m.Initialize
    For i = 0 To crsr.RowCount - 1
        crsr.Position = i
        Dim cu As cuContact
        cu.Initialize
        cu.Id = crsr.GetLong("contact_id")
        cu.DisplayName = crsr.GetString("display_name")
        If m.ContainsKey(cu.Id) Then Continue
        m.Put(cu.Id, Null)
        res.Add(cu)
    Next
    crsr.Close
    Return res
End Sub

'Returns a List with cuEmail items.
Public Sub GetEmails(Id As Long) As List
    Dim res As List
    res.Initialize
    For Each obj() As Object In GetData("vnd.android.cursor.item/email_v2", Array As String("data1", "data2"), Id, Null)
        Dim e As cuEmail
        e.Initialize
        e.Email = obj(0)
        e.EmailType = mailTypes.Get(obj(1))
        res.Add(e)
    Next
    Return res
End Sub

'Returns a List with cuPhone items.
Public Sub GetPhones(id As Long) As List
    Dim res As List
    res.Initialize
    For Each obj() As Object In GetData("vnd.android.cursor.item/phone_v2", Array As String("data1", "data2"), id, Null)
        Dim p As cuPhone
        p.Initialize
        p.Number = obj(0)
        p.PhoneType = phoneTypes.Get(obj(1))
        res.Add(p)
    Next
    Return res
End Sub

'Returns the note field.
Public Sub GetNote(id As Long) As String
    Dim raw As List = GetData("vnd.android.cursor.item/note", Array As String("data1"), id, Null)
    If raw.Size = 0 Then Return ""
    Dim obj() As Object = raw.Get(0)
    Return obj(0)
End Sub

'Returns the thumbnail photo of the given contact. Returns an uninitialized bitmap if no photo is available.
Public Sub GetPhoto(Id As Long) As Bitmap
    Dim raw As List = GetData("vnd.android.cursor.item/photo", Array As String("data15"), Id, Array As Boolean(True))
    Dim bmp As Bitmap
    If raw.Size > 0 Then
        Dim obj() As Object = raw.Get(0)
        Dim bytes() As Byte = obj(0)
        If bytes <> Null Then
            Dim In As InputStream
            In.InitializeFromBytesArray(bytes, 0, bytes.Length)
            bmp.Initialize2(In)
            In.Close
        End If
    End If
    Return bmp
End Sub

'Gets whether the contact is "starred".
Public Sub GetStarred(Id As Long) As Boolean
    Dim crsr As Cursor = cr.Query(contactUri, Array As String("starred"), "_id = ?", Array As String(Id), "")
    crsr.Position = 0
    Dim starred As Boolean = crsr.GetInt("starred") = 1
    crsr.Close
    Return starred
End Sub


Private Sub GetData(Mime As String, DataColumns() As String, Id As Long, Blobs() As Boolean) As List
    Dim crsr As Cursor = cr.Query(dataUri, DataColumns, "mimetype = ? AND contact_id = ?", _
        Array As String(Mime, Id), "")
    Dim res As List
    res.Initialize
    For i = 0 To crsr.RowCount - 1
        crsr.Position = i
        Dim row(DataColumns.Length) As Object
        For c = 0 To DataColumns.Length - 1
            If Blobs <> Null AND Blobs(c) = True Then
                row(c) = crsr.GetBlob2(c)
            Else
                row(c) = crsr.GetString2(c)
            End If
        Next
        res.Add(row)
    Next
    crsr.Close
    Return res
End Sub
'Sets the note field of the given id.
Public Sub SetNote(Id As Long, Note As String)
    Dim v As ContentValues
    v.Initialize
    v.PutString("data1", Note)
    SetData("vnd.android.cursor.item/note", v, Id, True)
End Sub

'Adds an email field to the given contact id.
'EmailType - One of the email types strings (see Initialize method).
Public Sub AddEmail(Id As Long, Email As String, EmailType As String)
    Dim v As ContentValues
    v.Initialize
    v.PutString("data1", Email)
    v.PutInteger("data2", GetKeyFromValue(mailTypes, EmailType, 3))
    SetData("vnd.android.cursor.item/email_v2", v, Id, False)
End Sub

'Adds a phone field to the given contact id.
'PhoneType - One of the phone types strings (see Initialize method).
Public Sub AddPhone(Id As Long, PhoneNumber As String, PhoneType As String)
    Dim v As ContentValues
    v.Initialize
    v.PutString("data1", PhoneNumber)
    v.PutInteger("data2", GetKeyFromValue(phoneTypes, PhoneType, 7))
    SetData("vnd.android.cursor.item/phone_v2", v, Id, False)
End Sub

'Deletes the given phone number.
Public Sub DeletePhone(Id As Long, PhoneNumber As String)
    DeleteData("vnd.android.cursor.item/phone_v2", PhoneNumber, Id)
End Sub
'Deletes the given email address.
Public Sub DeleteEmail(Id As Long,Email As String)
    DeleteData("vnd.android.cursor.item/email_v2", Email, Id)
End Sub

'Small utility to find the type integer value from the type name
Private Sub GetKeyFromValue(m As Map, v As String, defaultValue As Int) As Int
    Dim t As Int = defaultValue
    For i = 0 To m.Size - 1
        If m.GetValueAt(i) = v Then
            t = m.GetKeyAt(i)
            Exit
        End If
    Next
    Return t
End Sub

Private Sub DeleteData(Mime As String, Data1Value As String, Id As Long)
    cr.Delete(dataUri, "mimetype = ? AND data1 = ? AND contact_id = ?", Array As String(Mime, Data1Value, Id))
End Sub
Private Sub SetData(Mime As String, Values As ContentValues, Id As Long, Update As Boolean)
    If Update Then
        cr.Update(dataUri, Values, "mimetype = ? AND contact_id = ?", Array As String(Mime, Id))
    Else
        Dim crsr As Cursor = cr.Query(contactUri, Array As String("name_raw_contact_id"), _
            "_id = ?", Array As String(Id), "")
        If crsr.RowCount = 0 Then
            Log("Error getting raw_contact_id")
            crsr.Close
            Return
        End If
        crsr.Position = 0
        Values.PutString("raw_contact_id", crsr.GetString("name_raw_contact_id"))
        crsr.Close
        Values.PutString("mimetype", Mime)
        cr.Insert(dataUri, Values)
    End If
End Sub

'Sets the starred state of the given id.
Public Sub SetStarred (Id As Long, Starred As Boolean)
    Dim values As ContentValues
    values.Initialize
    values.PutBoolean("starred", Starred)
    cr.Update(contactUri, values, "_id = ?", Array As String(Id))
End Sub

'Deletes the contact with the given Id.
Public Sub DeleteContact(Id As Long)
    cr.Delete(rawContactUri, "contact_id = ?", Array As String(Id))
End Sub

'Inserts a new contact and returns the cuContact object of this contact.
Public Sub InsertContact(Name As String, Phone As String) As cuContact
    Dim values As ContentValues
    values.Initialize
    values.PutNull("account_name")
    values.PutNull("account_type")
    Dim rawUri As Uri = cr.Insert(rawContactUri, values)
    Dim rawContactId As Long = rawUri.ParseId

    values.Initialize
    values.PutLong("raw_contact_id", rawContactId)
    values.PutString("mimetype", "vnd.android.cursor.item/phone_v2")
    values.PutInteger("data2", 12) 'phone type main
    values.PutString("data1", Phone)
    cr.Insert(dataUri, values)

    values.Initialize
    values.PutLong("raw_contact_id", rawContactId)
    values.PutString("mimetype", "vnd.android.cursor.item/name")
    values.PutString("data1", Name)
    cr.Insert(dataUri, values)
    Dim cu As cuContact
    cu.Initialize
    Dim crsr As Cursor = cr.Query(dataUri, Array As String("contact_id", "display_name"), "raw_contact_id = ?", _
        Array As String(rawContactId), "")
    crsr.Position = 0
    cu.DisplayName = crsr.GetString("display_name")
    cu.Id = crsr.GetLong("contact_id")
    Return cu
End Sub

'useful for debugging
Private Sub printCursor(c As Cursor) 'ignore
    For r = 0 To c.RowCount - 1
        c.Position = r
        For col = 0 To c.ColumnCount - 1
            Try
                Log(c.GetColumnName(col) & ": " & c.GetString2(col))
            Catch
                Log(c.GetColumnName(col) & ": " & LastException)
            End Try
        Next
        Log("***************")
    Next
End Sub
 
Last edited:
Upvote 0

Eric H

Active Member
Licensed User
Longtime User
Any ideas on this error that one of my users is getting?

An error has occurred in sub:
contactsutils_vvvv3 (java line: 564)
java.lang.RuntimeException:
Object should first be initialized (Uri).
Continue?


(vvvv3=insertcontact)
 
Upvote 0
Top