在synctask类android中显示listview

时间:2013-09-02 04:58:38

标签: android

我是初学者。我想在asyncTask中显示一个listview,所以我有这个代码,但我不知道下面这行中有多少错误:

ListAdapter adapter =new SimpleAdapter(this, result,android.R.layout.simple_list_item_1, new String[] {"planet"}, new int[] {android.R.id.text1});
你可以帮我解决一下吗?

我的代码:

 public class MainActivity extends Activity {
    List<Map<String, String>> planetsList;
    ListAdapter simpleAdpt;
    ListView lv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=(ListView) this.findViewById(R.id.listView1);
        planetsList = new ArrayList<Map<String,String>>();

        initList();
        simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"planet"}, new int[] {android.R.id.text1});

        lv.setAdapter(simpleAdpt);
    }


     private void initList() {
            // We populate the planets into planetslist

            planetsList.add(createPlanet("planet", "Mercury"));
            planetsList.add(createPlanet("planet", "Venus"));
            planetsList.add(createPlanet("planet", "Mars"));
            planetsList.add(createPlanet("planet", "Jupiter"));
            planetsList.add(createPlanet("planet", "Saturn"));
            planetsList.add(createPlanet("planet", "Uranus"));
            planetsList.add(createPlanet("planet", "Neptune"));

    }

     private HashMap<String, String> createPlanet(String key, String name) {
            HashMap<String, String> planet = new HashMap<String, String>();
            planet.put(key, name);

            return planet;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

1 个答案:

答案 0 :(得分:0)

我猜你正在使用AsyncTask中的“this”来引用你的Activity。试试这个:

ListAdapter adapter =new SimpleAdapter(MainActivity.this, result,android.R.layout.simple_list_item_1, new String[] {"planet"}, new int[] {android.R.id.text1});