0

I have an ArrayAdapter<String> Constructor inside of my Activitys onCreate. My problem is that each time the onCreate method of the Activity that contains the ArrayAdapter Constructer is called, the ArrayAdapter appends items to the items in the previous onCreate call, thus the same items are duplicated every time the onCreate method is called.

An example would be:
1st call to Activity - ArrayAdapter = blue, black, brown
2nd call to Activity - ArrayAdapter = blue, black, brown, blue, black, brown
3rd call to Activity - ArrayAdapter = blue, black, brown, blue, black, brown, blue, black, brown

My Constructor looks like this

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.adapter,colors);

Basically, I need the ArrayAdapter to remain constant on multiple calls to the Activity's onCreate.

4
  • Can you post your code where you fill out colors? Commented Feb 24, 2014 at 23:15
  • 1
    If you're doing that in the Activity's constructor, then you need to put it in onCreate() or call List#clear(). The system won't necessarily create a now Activity object reference. Commented Feb 24, 2014 at 23:21
  • My ArrayAdapter Constructor is inside the Activity onCreate(). If the Activity is destroyed and onCreate is called again. The ArrayAdapter list of items is duplicated. Commented Feb 24, 2014 at 23:29
  • As you said, your Activity is destroyed, then clear colors at the onDestroy(). That will solve the problem! Commented Feb 25, 2014 at 0:53

2 Answers 2

1

Since items are getting appended to the list each time Activity is created, so before adding the elements to the list follow one of these conditions.

First way

onCreate(){ 
        if(colors.size()==0){
    // add the elements there};
    }

And the Second way..

onCreate() {
  colors.clear();
//add the elements here.

Option 1 is preferred if you are adding the same items each and every time.

Option 2 is preferred if you are adding different items every time.

Sign up to request clarification or add additional context in comments.

Comments

0

The easiest way to solve this would be to include the ArrayAdapter setup and initialization to within the onCreate() method of the activity. This way, each time the activity is called, the ArrayAdapter is initialized as a new object and there won't be any previous values to hold on to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.