Showing posts with label ArrayList. Show all posts
Showing posts with label ArrayList. Show all posts

Add a Dynamic ListView, Step-By-Step

How to Add a Dynamic ListView to your Android Project, Step-By-Step

After each step you should be able to compile and test, with no errors.

A "Dynamic ListView" is a ListView where items can be added.
A "Static ListView" is a ListView where the items in the ListView will not be changed.

1. Create a List with an ArrayList.

2. Link your ArrayAdapter to the ListView named myListView.

3. Compile and run!

Next Recommended Article: Do Action on ListView Item Click


Solution for: error: local variable myList is accessed from within inner class; needs to be declared final


Problem:

    [javac] Compiling 3 source files to C:\XXX\Workspace\MyApp\bin\classes
    [javac] C:\XXX\Workspace\MyApp\src\com\akp\MyAPp\MainActivity.java:74: error: local variable myList is accessed from within inner class; needs to be declared final
    [javac] myList.add(strEditText);
    [javac] ^
    [javac] 1 error

Solution: 

1. Make sure you are linking your List to ArrayList correctly. 


How to Link ArrayList to a List

An ArrayList is dynamic.

1. If you don't already have an Android project created, create an Android project.

2. In MainActivity.java, add the below line of code to the imports section.

     import java.util.ArrayList;

3. Create a List with an ArrayList called myList.

4. Initialize myList with ArrayList by adding the below code in the onCreate method.

myList = newArrayList<ArrayList<String>();

5. Compile and run!

Resources:

How to Create an ArrayList

ArrayList was added in API Level 1

1. Open the MainActivity.java file and add the below line to the imports section.

import java.util.List;
import java.util.ArrayList;


2. In the onCreate method, add the following line to create String List Array. This will declare a List variable called myList.

    List<String> myList;

3. Add the bold line below to the onCreate method.

myList = new ArrayList<String>();

4. Compile and run!

Resources:

Solution: error: cannot find symbol "ArrayList"

Problem

    [javac] Compiling 3 source files to C:\xxxx\Workspace\MyApp\bin\classes
    [javac] C:\xxxx\Workspace\MyApp\src\com\akp\MyApp\MainActivity.java:18: error: cannot find symbol
    [javac]     ArrayList<String> listItems=new ArrayList<String>();
    [javac]     ^
    [javac]   symbol:   class ArrayList
    [javac]   location: class MainActivity

Solution:
1. Open the MainActivity.java file and add the below line to the imports section

import java.util.ArrayList;

2. Compile and test your app.