2010-02-09 102 views
5

我读了一篇教程,它使用SQLlite和“SimpleCursorAdapter”来填充项目列表。 这是教程教给我的代码。如何用XML或JSON数据填充ListView(在Android中)?

private void fillData() { 
     // Get all of the notes from the database and create the item list 
     Cursor c = mDbHelper.fetchAllNotes(); 
     startManagingCursor(c); 

     String[] from = new String[] { NotesDbAdapter.KEY_TITLE }; 
     int[] to = new int[] { R.id.text1 }; 

     // Now create an array adapter and set it to display using our row 
     SimpleCursorAdapter notes = 
      new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to); 
     setListAdapter(notes); 
    } 

但是......如果我想填充XML数据呢?这是同样的方法吗?有人能给我一个例子(在代码中)?谢谢。

回答

8

该示例使用的是CursorAdapter,因为NotesDbAdapter(如果我没记错的话)会返回Cursor对象fetchAllNotes方法。我不知道是否有办法通过原始XML来创建列表,但是您可以使用名称/值对在HashMap中使用SimplelistAdapter创建列表。

你可以解析你的xml和or json,并用它构建一个哈希表并用它来填充一个列表。以下示例不使用xml,实际上它不是动态的,但它确实演示了如何在运行时组装列表。它来自延伸ListActivity的活动的onCreate方法。全部大写值是在类的顶部定义的静态常量字符串,并用作键。

// -- container for all of our list items 
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>(); 

// -- list item hash re-used 
Map<String, String> group; 

// -- create record 
group = new HashMap<String, String>(); 

group.put(KEY_LABEL, getString(R.string.option_create)); 
group.put(KEY_HELP, getString(R.string.option_create_help)); 
group.put(KEY_ACTION, ACTION_CREATE_RECORD); 

groupData.add(group); 

// -- geo locate 
group = new HashMap<String, String>(); 

group.put(KEY_LABEL, getString(R.string.option_geo_locate)); 
group.put(KEY_HELP, getString(R.string.option_geo_locate_help)) 
group.put(KEY_ACTION, ACTION_GEO_LOCATE); 

groupData.add(group); 

// -- take photo 
group = new HashMap<String, String>(); 

group.put(KEY_LABEL, getString(R.string.option_take_photo)); 
group.put(KEY_HELP, getString(R.string.option_take_photo_help)); 
group.put(KEY_ACTION, ACTION_TAKE_PHOTO); 

groupData.add(group); 

// -- create an adapter, takes care of binding hash objects in our list to actual row views 
SimpleAdapter adapter = new SimpleAdapter(this, groupData, android.R.layout.simple_list_item_2, 
                new String[] { KEY_LABEL, KEY_HELP }, 
                new int[]{ android.R.id.text1, android.R.id.text2 }); 
setListAdapter(adapter);