【问题标题】:How to stop adding items to the arraylist?如何停止向数组列表添加项目?
【发布时间】:2014-12-18 10:04:43
【问题描述】:

有 2 个标签费用和收入。费用选项卡和收入选项卡包含不同的列表视图。使用费用选项卡启动活动时,列表显示数据库字符串数组项。如果列表中有 3 项,则在将选项卡切换到收入选项卡并返回费用选项卡后,它将显示 6 项。再次将相同的值添加到列表中。如何覆盖这个?这是我的代码..

String[] theCategory;
String[] theMoneyType;
String[] theDescp;
String[] theDate;
String[] theAmount;

AllDataClass allData;

ListView exList;
private ArrayList<String> kId = new ArrayList<String>();           
private ArrayList<String> t_category = new ArrayList<String>();
private ArrayList<String> t_date = new ArrayList<String>();
private ArrayList<String> t_amount=new ArrayList<String>();
private ArrayList<String> t_moneytype=new ArrayList<String>();
private ArrayList<String> t_description=new ArrayList<String>();     <<< these array list values getting from SQlite database 

ArrayList<AllExpense> list=new ArrayList<AllExpense>();

theCategory=t_category.toArray(new String[t_category.size()]);

    theDate=t_date.toArray(new String[t_date.size()]);

    theAmount=t_amount.toArray(new String[t_amount.size()]);
    theMoneyType=t_moneytype.toArray(new String[t_moneytype.size()]);

    theDescp=t_description.toArray(new String[t_description.size()]);

    for(int i=0;i<theDate.length;i++) <<<<<< //this loop running again after switching the tab. I need this loop only one time.>>>>>>>>>>>
    {

        AllExpense ae=new AllExpense(theCategory[i],theDate[i],theAmount[i],theMoneyType[i],theDescp[i]);

        list.add(ae);

    }

【问题讨论】:

  • 要么清空数组,要么检查array.contains(value);
  • 不要对两者使用相同的数组?创建一个名为 Transaction 的类或您喜欢的用于跟踪数组的类,为其提供您现在定义的所有方法,并使用该类的两个单独实例来跟踪费用和收入。
  • 我的解决方案成功了吗?

标签: android listview items


【解决方案1】:

在添加项目之前清除列表。

list.clear();

for(int i=0;i<theDate.length;i++) <<<<<< //this loop running again after switching the tab. I need this loop only one time.>>>>>>>>>>>
    {

        AllExpense ae=new AllExpense(theCategory[i],theDate[i],theAmount[i],theMoneyType[i],theDescp[i]);

        list.add(ae);

    }

【讨论】:

  • 是的..这就是我要找的..非常感谢@H4SN
【解决方案2】:

用于验证天气字符串的写入方法是否可用

你也使用

list.clear();

for循环之前

【讨论】:

    【解决方案3】:

    添加前检查:

    private void test() {
        ArrayList<String> names=new ArrayList<String>();
        ArrayList<String> totalNames=db.getAllNames();
        for (int i = 0; i < totalNames.size(); i++) {
            if(!names.contains(totalNames.get(i))){
                names.add(totalNames.get(i));
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      或者另一种选择是

      if(!list.IsEmpty()) {
          for(int i=0;i<theDate.length;i++)
          {
           ......
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-06-12
        • 2022-06-29
        • 1970-01-01
        • 1970-01-01
        • 2015-01-02
        • 1970-01-01
        • 1970-01-01
        • 2020-04-06
        • 1970-01-01
        相关资源
        最近更新 更多