2 cairunbo cairunbo 于 2016.04.06 18:01 提问

求大神帮忙解答下,学习安卓的过程中,关于SampleAdapter的问题

package com.aa.cao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
private ListView listview;
private SimpleAdapter simp_adapter;
private List>datalist;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listview.setAdapter(simp_adapter);
    simp_adapter=new SimpleAdapter(this, getData(), R.layout.item, new String[]{"pic","text"}, new int[]{R.id.pic,R.id.text});
    datalist=new ArrayList<Map<String,Object>>();
}

private List<Map<String,Object>> getData(){
    for(int i=0;i<20;i++){
        Map<String,Object>map=new HashMap<String, Object>();
        map.put("pic", R.drawable.ic_launcher);
        map.put("text", "慕课网"+i);
        datalist.add(map);
    }
    return datalist;
}


@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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

不知道为什么,一运行就报错,实在找不出问题,求大神帮忙解答下,感谢!

4个回答

qq_34575250
qq_34575250   2016.04.07 17:13
已采纳
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listview.setAdapter(simp_adapter);
    simp_adapter=new SimpleAdapter(this, getData(), R.layout.item, new String[]{"pic","text"}, new int[]{R.id.pic,R.id.text});
    datalist=new ArrayList<Map<String,Object>>();
}
  1. listview要先实例化,如listview = (ListView)findViewById(R.id.xxx),xxx是listview的id
  2. 同样的道理simp_adapter也要在 listview.setAdapter之前实例化
cairunbo
cairunbo 感谢帮助!
一年多之前 回复
sinat_25404831
sinat_25404831   2016.04.07 17:14

listview没实例化,代码顺序也有问题吧

试试这样
listview = (ListView)findbyid(R.id.,,,);
datalist=new ArrayList>();
simp_adapter=new SimpleAdapter(this, getData(), R.layout.item, new String[]{"pic","text"}, new int[]{R.id.pic,R.id.text});
listview.setAdapter(simp_adapter);

cairunbo
cairunbo 感谢帮助!
一年多之前 回复
u012934325
u012934325   2016.04.06 18:26

报错你需要把错误贴出来啊,不然别人怎么知道是哪里的错误

baidu_15438619
baidu_15438619   2016.04.06 21:32

listview没实例化?

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!