每次运行我的应用程序时,都会重复数组列表项

时间:2014-08-03 21:20:21

标签: android arraylist duplicates

嗨,我遇到一个问题,每当我运行app时,我的arraylist视图项都会重复。 我将arraylistview的所有项目存储在我的string.xml文件中

 public class Button_mak extends Activity implements OnClickListener{
final Context context = this;
public static ArrayList<Advertisement> ads = new ArrayList<Advertisement>();

private void populateAdsFromMetadata(){

            String [] titles = getResources().getStringArray(R.array.title);
            String [] detailedMessages = getResources().getStringArray(R.array.detailed_message);
            String [] ownerName = getResources().getStringArray(R.array.owner_name);
            String [] ownerEmail = getResources().getStringArray(R.array.owner_email);
            String [] price = getResources().getStringArray(R.array.price);
            String [] image = getResources().getStringArray(R.array.images);
            String [] id = getResources().getStringArray(R.array.id);

            for(int i = 0; i < titles.length; i++){
                Advertisement ad1 = new Advertisement(titles[i],
                        detailedMessages[i], ownerName[i], 
                        ownerEmail[i], image[i], Integer.parseInt(price[i]), Integer.parseInt(id[i]));  
                ads.add(ad1);
            }

        }

1 个答案:

答案 0 :(得分:0)

您可以保留public static ArrayList<Advertisement> ads以避免每次都重新创建列表。相反,您可以在添加新元素集之前清除列表。如下所示:

 ads.clear();
for(int i = 0; i < titles.length; i++){
            Advertisement ad1 = new Advertisement(titles[i],
                    detailedMessages[i], ownerName[i], 
                    ownerEmail[i], image[i], Integer.parseInt(price[i]),       Integer.parseInt(id[i]));  
            ads.add(ad1);
        }