2016-08-04 5 views
0

特定の日付に特定の携帯電話番号から受信した最後の5 SMSを読み取る方法が不思議です。特定の日付に特定の番号から受信した最後の5 SMSを読む

特定の送信者からすべてのSMSを読み取る方法、最後のSMSを読み取る方法は知っていますが、最後のSMSをフェッチして読み取ることができません。私は私のコードは

Uri mSmsinboxQueryUri = Uri.parse("content://sms/inbox"); 
String[] projection = {"address", "body"}; 
Cursor cursor1 = MainActivity.this.getContentResolver().query(mSmsinboxQueryUri, 
                   null, 
                   "address = ?", 
                   new String[]{phoneNumber}, 
                   "date DESC LIMIT 5"); 

if (cursor1 != null && cursor1.moveToFirst()) { 
    body = cursor1.getString(cursor1.getColumnIndex("body")); 
    totalBody = totalBody + body; 
    Log.d("Registration", totalBody); 
} 

しかし、それは唯一の最後のメッセージを示していますたびに以下のようなものです

"date DESC LIMIT 5" 

を使用して、それらを読み取ろうとしました。

答えて

0

コードでは、返されたCursorの最初のレコードのみが処理されているため、1つのメッセージしか表示されません。残りの部分を処理するには、Cursorをループする必要があります。たとえば:あなたは1日にクエリを制限したい場合は

if (cursor != null && cursor.moveToFirst()) { 
    do { 
     body = cursor1.getString(cursor1.getColumnIndex("body")); 
     totalBody = totalBody + body; 
     Log.d("Registration", totalBody); 
    } while (cursor.moveToNext()); 
} 

また、あなたはミリ秒単位でその日の開始時刻と終了時刻を把握するCalendarを使用することができます - それは日付が中に保存されている方法であるとして、 SMSテーブル - 適切な比較をwhere句に追加します。例:

private static final int DAY_MILLISECONDS = 24 * 60 * 60 * 1000; 
private static final Uri inboxUri = Uri.parse("content://sms/inbox"); 

// Months are zero-based; i.e., JANUARY == 0 
// Phone number must be exact in this example 
private void listMessages(String phoneNumber, int year, int month, int day) { 
    Calendar cal = Calendar.getInstance(); 
    cal.set(Calendar.YEAR, year); 
    cal.set(Calendar.MONTH, month); 
    cal.set(Calendar.DATE, day); 
    cal.set(Calendar.HOUR_OF_DAY, 0); 
    cal.set(Calendar.MINUTE, 0); 
    cal.set(Calendar.SECOND, 0); 
    cal.set(Calendar.MILLISECOND, 0); 

    String[] projection = {"address", "body"}; 
    String whereAddress = "address = ?"; 
    String whereDate = "date BETWEEN " + cal.getTimeInMillis() + 
         " AND " + (cal.getTimeInMillis() + DAY_MILLISECONDS); 
    String where = DatabaseUtils.concatenateWhere(whereAddress, whereDate); 

    Cursor cursor = null; 
    try { 
     cursor = getContentResolver().query(inboxUri, 
              projection, 
              where, 
              new String[]{phoneNumber}, 
              "date DESC LIMIT 5"); 

     if (cursor != null && cursor.moveToFirst()) { 
      do { 
       Log.d("Message", cursor.getString(cursor.getColumnIndex("body"))); 
      } while (cursor.moveToNext()); 
     } 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    finally { 
     if (cursor != null) { 
      cursor.close(); 
     } 
    } 
} 
関連する問題