2013-10-15 29 views
0

我有以下代碼:如何正確顯示傳入的SMS發件人和日期?

Uri uriSMS = Uri.parse("content://sms"); 
Cursor cur = getContentResolver().query(uriSMS, 
     new String[] {"_id", "thread_id", "address", "person", "date", "body", "type"}, 
     null, null, null); 
startManagingCursor(cur); 

String[] from = new String[]{"address", "body", "date"}; 
int[] to = new int[]{R.id.sms_from, R.id.sms_body, R.id.sms_date}; 
adapter = new SimpleCursorAdapter(this, R.layout.sms_row, cur, from, to); 

setListAdapter(adapter); 

目前我使用address列中顯示SMS發送器,從而顯示電話號碼。我想用人名替換電話號碼。我期望person包含它,但它對於大多數SMS是空的。 然後,date字段包含long的值,當我想以DD.MM.YYYY的格式顯示它時。我想我可以覆蓋setViewValue()來修復它。但有沒有其他(更好的)解決方案&

我該如何解決這兩個問題?

回答

1

爲了解決日期問題,你可以做到這一點

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
    formatter.format(Long.parseLong(dateString)); 

和發送者的名字,試試這個

Cursor cs= context.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},condition,null,null); 
    cs.getString(cs.getColumnIndex(PhoneLookup.DISPLAY_NAME)); 
+0

謝謝。你的回覆沒有完全回答我的問題。所以,我已經用'setViewValue()'完成了我所需要的工作,但是你的回答很有幫助,所以我接受它。謝謝。 –

0

我認爲person對於聯繫人中不存在的數字是空的。

對於日期:

String strDateTime = (String) DateFormat.format("yyyy-MM-dd kk:mm", new Date(longValue)); 
+0

幾乎所有SMS的「人」都是空的。我不需要有一些額外的權限來使用它? –

+0

我不知道試一下:'<使用權限android:name =「android.permission.READ_CONTACTS」/>' – ramaral

-1

試試這個方法來顯示適當的日期和時間在短信。在此,您需要傳遞您從光標收到的日期

public String changeDate(long date) { 
     SimpleDateFormat sdf = new SimpleDateFormat(); 
     Date dt = new Date(date); 
     Date now = new Date(); 
     dt.setTime(date); 

     if (now.getYear()==dt.getYear() && now.getMonth()==dt.getMonth() && now.getDate()==dt.getDate()) 
      sdf.applyPattern("h:mm a"); 
     else if (now.getYear()==dt.getYear()) 
      sdf.applyPattern("d MMM" + " " + "h:mm a"); 
     else 
      sdf.applyPattern("d MMM yyyy" + " " + "h:mm a"); 

     return sdf.format(dt); 
    }