Vector只从Member获取最后一个值

时间:2013-01-20 01:44:37

标签: android arrays listview vector

我正在尝试使用Vector从文本文件中添加textviews 但我遇到了一个问题。 当设置我的数组,使用Tokenizer获取信息时,我打印的值为 “mName”,它从文本文件中获取所有值。 但是当我向文本视图分配“mName”时,我只从列表中获取最后一个名字..

这是代码:

Array和TextFile初始化 - :

AssetManager assets = mContext.getAssets();

    try {
        br = new BufferedReader(new InputStreamReader(
                assets.open("country_list")));
        while ((sCurrentLine = br.readLine()) != null) {
            StringTokenizer tokenizer = new StringTokenizer(sCurrentLine,
                    ",");
            int count = 0;

            String[] stringArr = new String[3];

            while (tokenizer.hasMoreTokens()) {
                String tokenOrginizer = tokenizer.nextToken();
                stringArr[count] = tokenOrginizer;
                count++;
                mVector = new Vector<Country>();

            }

            Country country = new Country(stringArr[0],
                    Integer.parseInt(stringArr[1]),
                    Integer.parseInt(stringArr[2]));
            mVector.add(country);
            System.out.println(stringArr[0]);
            for (int i = 0; i < mVector.size(); i++) {
                System.out.println("Vector : " + mVector.get(i).getmName());  
                //here i see all the values when printing
            }

GetView方法 - :

public int getCount() {
    // TODO Auto-generated method stub
    return mVector.size();
}

@Override
public Object getItem(int item) {
    // TODO Auto-generated method stub
    return null;
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView tv;
    if (convertView == null) {
        tv = new TextView(mContext);
    } else {
        tv = (TextView) convertView;
    }

    for (int i = 0; i < mVector.size(); i++) {
        tv.setText(mVector.get(i).getmName());
        // i have a feeling that this is where i do something wrong

    }

    return tv;
}

}

1 个答案:

答案 0 :(得分:1)

通常情况下,您只看到Vector中的最后一项,因为每次调用getView方法时,您都会在for循环中设置文本,迭代所有< / strong> mVector中的值(以及您为TextView设置的最后一个文本是Vector中的最后一个值)。所以,而不是:

for (int i = 0; i < mVector.size(); i++) {
        tv.setText(mVector.get(i).getmName());
        // i have a feeling that this is where i do something wrong
        // your feeling is right, why the loop?!?  
}

你想要的:

//...
if (convertView == null) {
    tv = new TextView(mContext);
} else {
    tv = (TextView) convertView;
} 
tv.setText(mVector.get(position).getmName());
return tv;

另外,请使用ArrayList代替Vector