Search code examples
androidandroid-listviewsmsmanager

Sms Messages not Loading into ListView


I am working on an android project and I am stuck getting the SMS messages to load into the app. This is thew error I am encountering: enter image description here

I am trying to setup a list view and using an Array Adapter in this piece of code:

SMS INBOX

    private fun fetchInbox(): ArrayList<String> {
    val sms: ArrayList<String> = ArrayList()
    val uri: Uri = Uri.parse("contact://sms/inbox")
    val cursor: Cursor = contentResolver.query(uri, arrayOf("id", "address", "date", "body"), null, null, null)

    while (cursor.moveToNext()){

        val address: String = cursor.getString(1)
        val body: String = cursor.getString(3)

        sms.add("Address: $address" + "Message: $body")
    }

    return sms


}

And then I am calling it in my MainActivity like this:

        val listView = text_Messages

    if(fetchInbox() != null) {

        val adapter: ArrayAdapter<String> = ArrayAdapter(this, android.R.layout.activity_list_item, fetchInbox())
        listView.adapter = adapter


    }

I just don't understand why this error would occur


Solution

  •      ListView lViewSMS = (ListView) findViewById(R.id.listViewSMS);
    
                if(fetchInbox()!=null)
                {
                    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, fetchInbox());
                    lViewSMS.setAdapter(adapter);
                }
    //put the above part in oncreateview()
            public ArrayList fetchInbox()
            {
                ArrayList sms = new ArrayList();
    
                Uri uriSms = Uri.parse("content://sms/inbox");
                Cursor cursor = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body","" + "person"},null,null,null);
    
                cursor.moveToFirst();
                while  (cursor.moveToNext())
                {
                    String match="is created";
                    String address = cursor.getString(1);
                    String body = cursor.getString(3);
                   // String title = cursor.getString(3);
                    String tdata=body;
           sms.add(""+""+body);
    
    
    
    
    
    
                }
                return sms;
    
            }