读取Android中存储在SIM卡中的短信时出现空指针异常

时间:2015-11-24 05:37:41

标签: android nullpointerexception sms

我正在尝试阅读存储在SIM卡中的短信。这就是我编写以下功能的原因。

void read_sms()
    {
        Cursor cursor = getContentResolver().query(Uri.parse("content://sms/icc"), null, null, null, null);
        int indexBody = cursor.getColumnIndex("body");
        int indexAddress = cursor.getColumnIndex("address"); 
        if (indexBody < 0 || !cursor.moveToFirst())
            return;
        String fromNumber,smsMessageId;
        try{
            do {
                SMSItem smsItem = new SMSItem();
                String sms = cursor.getString(indexBody);
                String str = "SMS From: " + cursor.getString(indexAddress)
                        + "\n" + sms + " \n";
                fromNumber = cursor.getString(indexAddress); 
                // arrayAdapter.add(str);
                smsItem.sms = sms;
                smsItem.status = false;
                long millis = cursor.getLong(cursor
                        .getColumnIndexOrThrow("date"));
                Date date = new Date(millis);
                Calendar c = Calendar.getInstance();

                // set the calendar to start of today
                c.set(Calendar.HOUR_OF_DAY, 0);
                c.set(Calendar.MINUTE, 0);
                c.set(Calendar.SECOND, 0);
                c.set(Calendar.MILLISECOND, 0);

                // and get that as a Date
                Date today = c.getTime();
                String smsDate;
                if (date.before(today)) {
                    smsDate = (String) DateFormat.format(" MMMM dd ", new Date(
                            millis));
                } else {
                    smsDate = (String) DateFormat.format("  h:mm ",
                            new Date(millis));
                }
                smsItem.time = smsDate;
                smsMessageId = cursor.getString(cursor.getColumnIndex("_id"));
                smsItem.ID = smsMessageId;

                // Toast.makeText(this, "The id is "+smsMessageId,
                // Toast.LENGTH_LONG).show();
                smsBody.add(smsItem);
                Toast.makeText(this, " "+smsItem.sms, Toast.LENGTH_LONG).show();

            } while (cursor.moveToNext());
        }
        catch(Exception e)
        {
            Toast.makeText(this, "Message: "+e.getMessage(), Toast.LENGTH_LONG).show();
        }
        cursor.close();

    }

但我得到空指针异常。为什么我得到空指针异常?我怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

我尝试将您的代码放在测试应用程序中,并且还获得了NPE(Null Pointer Exception)。跟踪告诉我,以下行有问题并返回NPE。

        Cursor cursor = getContentResolver().query(Uri.parse("content://sms/icc"), null, null, null, null);

当我用以下更改替换行时,事情开始正常。

        Cursor cursor = managedQuery(Uri.parse("content://sms"), null, null, null, null);