2016-06-14 33 views
1

我在短信收件箱中使用此日期代碼,但它顯示01/01/70所有短信的錯誤日期我如何更改正確?短信收件箱中的日期格式

public void refreshSmsInbox() { 
    ContentResolver contentResolver = getActivity().getContentResolver(); 
    Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null); 

    int indexBody = smsInboxCursor.getColumnIndex("body"); 
    int indexAddress = smsInboxCursor.getColumnIndex("address"); 
    int timeMillis = smsInboxCursor.getColumnIndex("date"); 
    Date date = new Date(timeMillis); 
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy"); 
    String dateText = format.format(date); 

    if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return; 
    arrayAdapter.clear(); 
    do { 
     String str = smsInboxCursor.getString(indexAddress) +" "+ 
       "\n" + smsInboxCursor.getString(indexBody) +"\n"+ dateText+"\n"; 
     arrayAdapter.add(str); 
    } while (smsInboxCursor.moveToNext()); 
    smsInboxCursor.close(); 
} 
+0

有一個回覆預先感謝 –

+0

''date''列索引不是日期。 –

+0

評論變化 –

回答

0

這部分是錯誤的:

int timeMillis = smsInboxCursor.getColumnIndex("date"); 
Date date = new Date(timeMillis); 

getColumnIndex返回一個索引,而不是實際值。我想你想要這個,但我沒有自己測試:

int dateIndex = smsInboxCursor.getColumnIndex("date"); 
long timeMillis = smsInboxCursor.getLong(dateIndex); 
Date date = new Date(timeMillis); 
+0

不幸的是,應用程序現在停止了 –

+0

這是什麼錯誤? – smarx

+0

@ mgcaguioa的回答比我的回答更好......它也修正了您沒有在實際循環中獲取值的事實。 – smarx

1

@Mike M的評論是正確的。您正嘗試將日期列的索引轉換爲日期格式。你實際上並沒有轉換日期的值。試試這個:

public void refreshSmsInbox() { 

    ContentResolver contentResolver = getContentResolver(); 
    Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null); 

    // get the index of the column 
    int indexBody = smsInboxCursor.getColumnIndex("body"); 
    int indexAddress = smsInboxCursor.getColumnIndex("address"); 
    int indexDate = smsInboxCursor.getColumnIndex("date"); 

    if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return; 

    // loop through the messages in inbox 
    do { 
     // get the value based on the index of the column 
     String address = smsInboxCursor.getString(indexAddress); 
     String body = smsInboxCursor.getString(indexBody); 
     long date = smsInboxCursor.getLong(indexDate); 

     // convert millis value to proper format 
     Date dateVal = new Date(date); 
     SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy"); 
     String dateText = format.format(dateVal); 

     String str = address + "\n" + body + "\n" + dateText + "\n"; 
     System.out.println(str); 

    } while (smsInboxCursor.moveToNext()); 

    smsInboxCursor.close(); 
}