Skip to content Skip to sidebar Skip to footer

Populate Spinner From Csv File Using Scanner

Using Android (Eclipse) I am trying to read a .csv file and dynamically populate a Spinner using Scanner. Have tried many methods with the same result. Emulator shows Spinner but o

Solution 1:

If you want to display each row of your CSV on one row in the spinner, try this:

List<String> list = newArrayList<String>();
while (scanner.hasNext()) {
    list.add(scanner.next());
}

array_spinner = (Spinner)findViewById(R.id.spinner1);         
ArrayAdapter<String> adapter = newArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
array_spinner.setAdapter(adapter); 

Though has poor readability for the ordinary user, perhaps you only want to display the description and price:

List<String> list = newArrayList<String>();
while (scanner.hasNext()) {
    String data = scanner.next();
    String [] values = data.split(",");
    list.add(values[1] + "  $" + values[2]);
}       

Your posted method only showed the last CSV line, because you were creating a new ArrayAdapter for each line in the CSV and overriding the previous adapter that you had created.

By storing the Scanner's results in a List and moving the adapter's definition out of the Scanner loop, you should be able to see results like you had hope.

Addition from comments

An OutOfBounds exception with length=2, index=2 suggests that at least one row in your real CSV only has two values (one comma). To help you find that row try this:

if(values.length !=3)
    Log.v("Example", "Malformed row: " + data);
else
    list.add(values[1] + "  $" +values[2]);

Also, I neglected to mention that you are not setting a drop down layout for your Spinner. This will not cause the app to crash, but this creates the standard user interface:

ArrayAdapter<String> adapter = newArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Post a Comment for "Populate Spinner From Csv File Using Scanner"