我正在阅读一个 HTML 页面并从一个由two colums
. 我需要将这些值插入到ListView
.
我很难掌握Arrays
, 和的概念ArrayAdapter
,所以我尝试通过阅读各种代码示例来说明一些内容。
当我静态填充我的 ArrayAdapter(在 Java 代码中)时,我的代码运行良好,但我需要使用循环(或其他什么?)用我从 HTML 页面获得的内容填充数组的内容(所有这些代码都有效并且是到位)。
这就是我正在使用的:
排名.java
public class Ranking {
public String month;
public String rank;
public Ranking() {
super();
}
public Ranking(String month, String rank) {
super();
this.month = month;
this.rank = rank;
}
}
此代码有效:
Ranking ranking_data[] = new Ranking[] {
new Ranking("January 2013", "67"),
new Ranking("February 2013", "45"),
}
然后我ranking_data
用我自己的 RankingAdapter 引用;
RankingAdapter adapter = new RankingAdapter(this, R.layout.listview_item_row, ranking_data);
所以我的问题是;
如何动态填充ranking_data?
例如,这似乎不适用于循环填充;
Ranking ranking_data[] = null;
String mVal1, mVal2;
while (myIterator1.hasNext() && myIterator2.hasNext()) {
mVal1 = myIterator1.next().text();
mVal2 = myIterator2.next().text();
new Ranking(mVal1, mVal2);
}
这给了我NullPointerException
对 的调用RankingAdapter adapter = new RankingAdapter(this, R.layout.listview_item_row, ranking_data);
,也许是因为我的初始化ranking_data
将它设置为null
,但是我应该如何初始化它?
编辑
我RankingAdapter
的声明如下:
public class RankingAdapter extends ArrayAdapter<Ranking>
如果有帮助?
编辑 2
添加了RankingAdapter.java的代码
public class RankingAdapter extends ArrayAdapter<Ranking> {
Context context;
int layoutResourceId;
Ranking data[] = null;
public RankingAdapter(Context context, int layoutResourceId, Ranking[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RankingHolder holder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RankingHolder();
holder.txtMonth = (TextView)row.findViewById(R.id.item_month);
holder.txtRank = (TextView)row.findViewById(R.id.item_rank);
row.setTag(holder);
} else {
holder = (RankingHolder)row.getTag();
}
Ranking ranking = data[position];
holder.txtMonth.setText(ranking.month);
holder.txtRank.setText(ranking.rank);
return row;
}
static class RankingHolder {
TextView txtMonth;
TextView txtRank;
}
}