2012-02-19 79 views
0

我正在處理SMS應用程序,並且遇到了一些使用GROUP BY子句從ContentProvider中檢索數據的問題。Android - 從SMS ContentProvider檢索數據 - GROUP BY

我已經閱讀了很多類似問題的主題,但他們仍然沒有爲我提供工作解決方案。

我想要的是從每個線程獲取最新的短信。爲了達到這個目的,我必須選擇DATE列的最大值,並按THREAD_ID分組,我相信。

假設SMS表看起來是這樣的:

 
============================ 
THREAD_ID | MESSAGE | DATE | 
============================ 
1   | Hello | 555      
1   | Hi  | 666 
2   | Test | 333 
2   | Test 2 | 999 

,並將結果返回:

 
1 - Hi - 666 
2 - Test 2 999

這是我到目前爲止,但下面的代碼檢索最新短信從整個表中,而不是從特定的類別。它看起來像GROUP BY子句被忽略。

String CONTENT_URI = "content://sms/"; 
    Uri uri = Uri.parse(CONTENT_URI); 

    String selection = "date=(SELECT max(date) FROM sms)"; 
    selection+=") GROUP BY (thread_id"; 
    Cursor c = managedQuery(uri, null, selection, null, null); 
    if (c != null) { 
     while (c.moveToNext()) { 
      textView.append(c.getString(c.getColumnIndex(Column.THREAD_ID)) 
        + " - " + c.getString(c.getColumnIndex(Column.ADDRESS)) 
        + " - " + c.getString(c.getColumnIndex(Column.READ)) 
        + " - " + c.getString(c.getColumnIndex(Column.BODY)) 
        + " - " + c.getString(c.getColumnIndex(Column.DATE)) 
        + "\n"); 

     } 
     c.close(); 
    } else { 
     textView.setText("Cursor is null"); 
    } 

非常感謝您,如果您能幫我找到解決方案,我將非常感激。

回答

0

GROUP BY子句被忽略,因爲SELECT只給出1個值(在您的代碼中)。

我不很瞭解SQL,但我認爲這應該工作(SRY,我不知道確切的語法)

SELECT thread, message, MAX(date) 
FROM sms 
GROUP BY thread 
0

使用像CPH here圖書館做所有的樣板東西給你。示例代碼顯示了您需要的所有查詢內容。

0

實現如下

public Cursor query (SQLiteDatabase db, String[] projectionIn, String selection, String[] selectionArgs, String groupBy, String having, String sortOrder)

@Override 
public Cursor query(Uri uri, String[] projection, String selection, 
    String[] selectionArgs, String sortOrder) { 
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); 
final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); 
/* a String is a Object, so it can be null!*/ 
String groupBy = null; 
String having = null; 

switch (sUriMatcher.match(uri)) { 
... 
... 
... 
    case EPISODES_NEXT: 
    groupBy = "ShowID"; 
    queryBuilder.setTables(EpisodenTable.TableName); 
    break; 
default: 
    throw new IllegalArgumentException("Unknown URI " + uri); 
} 

Cursor c = queryBuilder.query(db, projection, selection, selectionArgs, 
     groupBy, having, sortOrder); 
c.setNotificationUri(getContext().getContentResolver(), uri); 
return c; 

}