Reshmin
Reshmin

Reputation: 95

How to stop adding items to the arraylist?

There are 2 tabs expense and income. Expense tab and Income tab contains different listviews. When starting the activity with expense tab, list shows the database string array items. If there are 3 items in list, after switching the tab to Income tab and back to expense tab It will show 6 items. Adding again the same values into list. How to override this? Here is my code..

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);

    }

Upvotes: 0

Views: 1727

Answers (4)

kluz88
kluz88

Reputation: 1

Or another option would be

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

Upvotes: 0

H4SN
H4SN

Reputation: 1708

Clear list before adding items.

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);

    }

Upvotes: 1

Rathan Kumar
Rathan Kumar

Reputation: 2577

check before adding:

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));
        }
    }
}

Upvotes: 0

hareesh J
hareesh J

Reputation: 530

write method to for validating weather strings are available or not

you also use

list.clear();

Before for loop

Upvotes: 0

Related Questions