2010-03-05 8 views
7

Il mio oggetto ContentValues ​​ha chiavi di stringa e vorrei ottenere un risultato String [] con tutte le chiavi in ​​esso contenute?Come ottenere le chiavi da ContentValues?

Come si esegue un iterazione di un oggetto ContentValues?

EDIT 1

Dopo aver ottenuto due risposte sono arrivato fino a questo, vedete problemi con esso?

 ArrayList<String> ar = new ArrayList<String>(); 
     ContentValues cv=data; 
     Set<Entry<String, Object>> s=cv.valueSet(); 
     for (Entry<String, Object> entry : s) { 
      ar.add(entry.getKey()); 
     } 
     String[] projection=new String[ar.size()]; 
     ar.toArray(projection); 
+0

nulla salta fuori, non funziona? – RickNotFred

+0

Si può popolare anche l'array direttamente dal Set, piuttosto che tramite ArrayList, ma a parte questo, sembra buono. –

risposta

3

In base al documento, il metodo "valoreSet()" restituisce un insieme di tutte le chiavi e valori. È quindi possibile utilizzare un iteratore sul set risultante e su getKey() su ciascuno degli elementi di voce iterati da raccogliere in un array di stringhe.

18

Prova questo codice. Basta passare il tuo ContentValues nel metodo.

public void printContentValues(ContentValues vals) 
{ 
    Set<Entry<String, Object>> s=vals.valueSet(); 
    Iterator itr = s.iterator(); 

    Log.d("DatabaseSync", "ContentValue Length :: " +vals.size()); 

    while(itr.hasNext()) 
    { 
     Map.Entry me = (Map.Entry)itr.next(); 
     String key = me.getKey().toString(); 
     Object value = me.getValue(); 

     Log.d("DatabaseSync", "Key:"+key+", values:"+(String)(value == null?null:value.toString())); 
    } 
} 
+0

+1 per dare il codice di esempio – lalitm

+0

Qualche motivo specifico per cui hai usato prima "Entry" e successivamente "Map.Entry"? Sono entrambi diversi in questo contesto? – faizal

2

Si può provare anche questo:

String ar [] = {}; 
    ContentValues cv=new ContentValues(); 
    int i=0; 
    for(String key: cv.keySet()){ 
     ar[i] = key; 
    } 
Problemi correlati