BaseAdapter android getCount()方法

时间:2014-12-02 23:09:25

标签: android arraylist baseadapter


我正在尝试为ListView设置BaseAdapter,但我在运行时有错误。错误在getCount方法的NewsAdapter.java文件中:如果我写"返回0"我没有错误,但如果写"返回list.size()"我在运行时有错误。
这是所有文件:

News.java

public class News extends Activity {

TextView txt1;
ArrayList<NewsArray> listaArray;
NewsAdapter baseAdapter;
ListView lista;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news);

    txt1=(TextView) findViewById(R.id.textView1);
    lista= (ListView) findViewById(R.id.listView1);

    baseAdapter= new NewsAdapter(this, R.layout.newsframe, listaArray);
    lista.setAdapter(baseAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.news, 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);
    }
    }


NewsAdapter.java

public class NewsAdapter extends BaseAdapter {

ArrayList<NewsArray> list=new ArrayList<NewsArray>();
Context c;
int layoutResourceId;

public NewsAdapter(Context c, int layoutResourceId, ArrayList<NewsArray> list) {
    // TODO Auto-generated constructor stub
    this.layoutResourceId = layoutResourceId;
    this.c = c;
    this.list = list;

}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return list.size();
    //return 0;
}

@Override
public Object getItem(int arg0) {
    // TODO Auto-generated method stub
    return list.get(arg0);

}

@Override
public long getItemId(int arg0) {
    // TODO Auto-generated method stub
    return arg0;

}

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
    // TODO Auto-generated method stub

    return null;
}
}


NewsArray.java

public class NewsArray  {
String  name, nickname, date, description, ncomment, nlike;

public NewsArray(String name, String nickname, String date, String description, String ncoment, String nlike) {
    // TODO Auto-generated constructor stub
    this.name=name;
    this.nickname=nickname;
    this.date=date;
    this.description=description;
    this.ncomment=ncoment;
    this.nlike=nlike;
}
}


有什么想法吗?

2 个答案:

答案 0 :(得分:0)

尝试更改getView的return语句。除非你需要,否则你也可以尝试ArrayAdapter而不是重新发明轮子。

DavidGSola在他的回答中说,你没有正确初始化你的ArrayList。

答案 1 :(得分:0)

在创建适配器之前,您需要调用ArrayList<NewsArray> listaArray的构造函数:

listaArray = new ArrayList<NewsArray>();

这是因为如果你传递ArrayList作为参数,那么你只传递一个引用。您应该复制BaseAdapter构造函数中的内容:

this.list = new ArrayList<NewsArray>(list);