James Robert Singleton
James Robert Singleton

Reputation: 461

Populate Spinner WITHOUT Strings.xml file

So everything I have found is using the strings.xml file to populate a spinner. What I want to do is populate a spinner based on information I get back from a JSON response. I have the following code that I used to populate a table but modified it for this. However, my spinner is still blank and I get no errors besides D/ViewRootImpl: #3 mView = null

Here is the code to populate the spinner:

public class SecondFragment extends Fragment implements APIRequestsUtil.APIRequestResponseListener
{
    View myView;
    Map<String, Route> drives;
    private ArrayAdapter<Integer> adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.second_layout, container, false);
        APIRequestsUtil.setOnNetWorkListener(this);
        return myView;
    }

    private void populateView() {
        this.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                drives = APIRequestsUtil.getRoutes();

                Spinner spinner = (Spinner) myView.findViewById(R.id.spinner);
                int driveNum = 0;
                for (Map.Entry drive : drives.entrySet()) {
                    TableRow tr = new TableRow(getActivity());
                    Route route = (Route) drive.getValue();
                    tr.setId(driveNum++);
                    //tr.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));



                    spinner.setId(driveNum);

                }
            }
        });

    }

    //@Override
    public void onFailure(Request request, Throwable throwable) {

    }

    //@Override
    public void onResponse(Response response) {
        populateView();
    }
}

Here is my XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:id="@+id/spinner"/>
</RelativeLayout>

Upvotes: 0

Views: 416

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007321

So everything I have found is using the strings.xml file to populate a spinner.

Here is a sample app that demonstrates populating a Spinner with the contents of a Java array.

The documentation happens to use an array resource for populating the Spinner, but you could swap in some other ArrayAdapter for the one their sample code creates using createFromResource().

Here is the code to populate the spinner

There is no code in there that populates a Spinner. You retrieve a Spinner from your layout. You then call setId() on it in a loop — I am not completely clear why. You have an ArrayAdapter named adapter that holds promise, but you never set it up.

Here is the activity from the sample app that I linked to above:

/***
  Copyright (c) 2008-2012 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain   a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS,   WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    https://commonsware.com/Android
*/

package com.commonsware.android.selection;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class SpinnerDemo extends Activity
  implements AdapterView.OnItemSelectedListener {
  private TextView selection;
  private static final String[] items={"lorem", "ipsum", "dolor",
          "sit", "amet",
          "consectetuer", "adipiscing", "elit", "morbi", "vel",
          "ligula", "vitae", "arcu", "aliquet", "mollis",
          "etiam", "vel", "erat", "placerat", "ante",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    selection=(TextView)findViewById(R.id.selection);

    Spinner spin=(Spinner)findViewById(R.id.spinner);
    spin.setOnItemSelectedListener(this);

    ArrayAdapter<String> aa=new ArrayAdapter<String>(this,
                              android.R.layout.simple_spinner_item,
                              items);

    aa.setDropDownViewResource(
      android.R.layout.simple_spinner_dropdown_item);
    spin.setAdapter(aa);
  }

  @Override
  public void onItemSelected(AdapterView<?> parent,
                                View v, int position, long id) {
    selection.setText(items[position]);
  }

  @Override
  public void onNothingSelected(AdapterView<?> parent) {
    selection.setText("");
  }
}

It follow the same recipe as in the documentation. I happen to use a constructor to create the ArrayAdapter instance, wrapping it around the String[] that is my model data. It is unclear what you want to have in your Spinner, but you could have an ArrayAdapter<Integer> (as is shown in your code) or ArrayAdapter<Route> or whatever.

For more complex scenarios, look for ListView examples. Spinner works nearly identically, with only two substantial changes:

  • You need to provide two layout resources (see setDropDownViewResource() in the code above). And, if you override getView() in a custom subclass of ArrayAdapter, probably you also need to override getDropDownView().

  • Spinner fires selection events, not item click events

Upvotes: 3

Related Questions