我正在尝试为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;
}
}
有什么想法吗?
答案 0 :(得分:0)
尝试更改getView
的return语句。除非你需要,否则你也可以尝试ArrayAdapter
而不是重新发明轮子。
DavidGSola在他的回答中说,你没有正确初始化你的ArrayList。
答案 1 :(得分:0)
在创建适配器之前,您需要调用ArrayList<NewsArray> listaArray
的构造函数:
listaArray = new ArrayList<NewsArray>();
这是因为如果你传递ArrayList
作为参数,那么你只传递一个引用。您应该复制BaseAdapter构造函数中的内容:
this.list = new ArrayList<NewsArray>(list);