2013-05-13 39 views
1

我是Android開發新手。 我正在做一個簡單的應用程序來閱讀手機的短信。 我知道內容提供商內容存在多少問題://短信但是...對於我來說編寫自定義內容太困難,所以我現在就要使用它。沒有從內容重複聯繫://短信/收件箱

問題:當我查詢內容時:// sms/inbox我得到所有的消息,所以當我嘗試在ListActivity中列出它們時,我有相同的聯繫人重複他/她擁有的每條消息。基本上這是正確的,我瞭解它,但我需要別的東西,「更專業」的東西。 首先是因爲: 1-一個查詢如此之大需要很長時間在手機上 2-顯然它不會使任何感官都以這種方式列出所有消息。

最簡單的事情就是使用DISTINCT或...如果不是,但非常糟糕,因爲它再次查詢所有消息,一個GROUP BY。問題是:GROUP BY無法識別,因爲正確地說,內容提供者背後的內容可能與數據庫不同。顯然,DISTINCT是可以接受的,但如果它被使用,它不會有任何區別。 我已經嚇了三天,找到一個解決方案,沒有自己過濾消息後,得到他們的查詢。

這是我的一小段簡單的代碼,我嘗試執行查詢: List smsList = new ArrayList();

 Uri uri = Uri.parse("content://sms/inbox"); 
     String order = new String("date DESC"); 
     String[] projection = new String[]{"DISTINCT thread_id, address, body, _id"}; 
     String selection = new String("GROUP BY address"); //this doesn't work 
     Cursor c = getContentResolver().query(uri, projection, null, null, order); 

     // Read the sms data and store it in the list 
     if(c.moveToFirst()) { 
      for(i=0; i < c.getCount(); i++) { 
       SMSData sms = new SMSData(); 
       sms.setBody(c.getString(c.getColumnIndexOrThrow("body")).toString()); 
       sms.setNumber(c.getString(c.getColumnIndexOrThrow("address")).toString()); 
       sms.setId(c.getString(c.getColumnIndexOrThrow("_id")).toString()); 
       sms.setPersonName(getContactNameFromNumber(sms.getNumber())); 
       smsList.add(sms); 
       //Log.v(TAG,"il nome è: "+smsList.get(i).getPersonName()+" e il numero è: "+smsList.get(i).getNumber()); 
       c.moveToNext(); 
      } 
     } 

     c.close(); 

我希望有人能幫助我! 在此先感謝。

+0

無法無人接聽? – KKyK 2013-05-16 13:37:51

回答

0

必須使用GROUP BY thread_id,看到我的github倉庫SmsMessenger更多詳情,您可以通過下面的查詢得到它:

cursor = MyApplication.getContext().getContentResolver().query(Uri.parse("content://sms") 
      , null 
      , "address IS NOT NULL) GROUP BY (thread_id" 
      , null 
      , null);