How do I fill a ListView (in Android) with XML or JSON data?

后端 未结 1 493
别跟我提以往
别跟我提以往 2021-02-06 14:09

I read a tutorial, and it uses SQLlite and \"SimpleCursorAdapter\" to fill the list with items. This is the code the tutorial taught me.

private void fillData()          


        
1条回答
  •  心在旅途
    2021-02-06 14:52

    The example is using a CursorAdapter because a Cursor object is returned by the NotesDbAdapter (if i remember correctly ) fetchAllNotes method. I don't know if there is a way to pass in raw XML to create a list but you can use name/value pairs in a HashMap to create a list using the SimplelistAdapter.

    You can parse your xml and or json and build a hash table with it and use that to populate a list. The following example doesn't use xml, in fact it's not dynamic at all, but it does demonstrate how to assemble a list at runtime. It's taken from the onCreate method of an activity that extends ListActivity. The all uppercase values are static constant strings defined at the top of the class, and are used as the keys.

    // -- container for all of our list items
    List> groupData = new ArrayList>();
    
    // -- list item hash re-used
    Map group;
    
    // -- create record
    group = new HashMap();
    
    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();
    
    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();
    
    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 );
    

    0 讨论(0)
提交回复
热议问题