Representing an ArrayList in a TextView

52
January 11, 2019, at 6:40 PM

I have created an ArrayList in an Android.

//creating an `ArrayList` of string type named words
ArrayList<String> words = new ArrayList<String>();
    words.add("one");
    words.add("two");
    words.add("three");
    words.add("four");
    words.add("five");
    words.add("six");
    words.add("seven");
    words.add("eight");
    words.add("nine");
    words.add("ten");

Now the elements of this ArrayList are to be displayed in a TextView. I have declared a LinearLayout named rootView-

LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);

This is the code to display the first element of the ArrayList in the TextView -

TextView wordView = new TextView(this);
        wordView.setText(words.get(i));
        rootView.addView(wordView);

Now my question is: To display all the elements of this ArrayList, we will create individual TextViewss (with all TextViewss having a different name). If the name of any declared TextViewss matches with any another TextViews then an error occurs.

But when we use loops to display the elements of this ArrayList then we write something like this -

    for (int i = 0;i<words.size();i++){
        TextView wordView = new TextView(this);
        wordView.setText(words.get(i));
        rootView.addView(wordView);
    }

This gives no error. So inside loops, we have declared a single TextViews named wordView. Every time the loop runs, a new TextView with same name wordView is created, why does it not show any errors? Whenever we manually create TextViews there is a error whenever the name matches. Why this is so?

Answer 1

The variable wordView is no longer available once it goes out of scope.

When your loop runs for the next time, compiler doesn't see this variable and allow you to create a new variable with same name.

READ ALSO
CMake Error:Error occurred while communicating with CMake server

CMake Error:Error occurred while communicating with CMake server

When I new a CMake project by the Android Studio,it occures a problem when I open it by the first time:

96
How to prevent double items but also prevent entire list from refreshing?

How to prevent double items but also prevent entire list from refreshing?

I am getting a JSON Array of user ids strings from a database:

34