Search code examples
javaandroidspinnerandroid-spinneronitemselectedlistener

Java onItemSelectedListener and Spinner not returning Anything


I'm building a currency converter (get from API, dynamically fills lists to create available currencies, select two currencies and return the rate. It seems a right of passage exercise).

I've been trying to get a Spinner to work, but despite my best efforts I can't seem to get the listener to do anything when I select a value from the list. When I do click a value, the logs do return something (see below), but I don't know what it means, and why it's not returning the System.out.println("yay") call I want.

D/OpenGLRenderer: endAllActiveAnimators on 0xa7040980 (DropDownListView) with handle 0x95c21270".

The array adapter is properly filling the spinner list from an ArrayList<string> I get get from API and a JSON Object. The listener code looks correct based on the examples I found on S.O. so far.

I wonder if it's an ordering issue in my code? Or something else.

package com.timlee.currencymate;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

    public class MainActivity extends AppCompatActivity {

// public variables
    String uRLResultString = "";
    ArrayList <String> currencies = new ArrayList<String>();
    Spinner currencyOneSpinner;
    Spinner currencyTwoSpinner;

// get data from api
public class DownloadTask extends AsyncTask <String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {
        URL url;
        HttpURLConnection urlConnection = null;

        try {
            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection)url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();

            while (data != -1) {
                char current = (char) data;
                uRLResultString += current;
                data = reader.read();
            }

            return uRLResultString;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        //System.out.println(result);
        //if get current list then run this, else run something else
        getCurrencyList();

    }
}

//gets the list of currecies
public void getCurrencyList () {

    try {

        JSONObject jsonObject = new JSONObject(uRLResultString);
        String base = jsonObject.getString("base");
        String rates = jsonObject.getString("rates");
        currencies.add(base);
        System.out.println(rates);

        JSONObject jSonObj = new JSONObject(rates);

        Iterator<String> keys = jSonObj.keys();

        while (keys.hasNext()) {
            String key = (String)keys.next();
            currencies.add(key);
            if (jSonObj.get(key) instanceof JSONObject) {
            }
        }

        Collections.sort(currencies, String.CASE_INSENSITIVE_ORDER);

    } catch (JSONException e) {
        e.printStackTrace();
    }

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    currencies = new ArrayList<String>();

    String currencyURL = "http://api.fixer.io/latest?base=AUD";
    DownloadTask task = new DownloadTask();
    task.execute(currencyURL);

    // apply Array Adapter and listener
    currencyOneSpinner = (Spinner)findViewById(R.id.spinnerCurrencyOne);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,currencies);
    currencyOneSpinner.setAdapter(arrayAdapter);
    currencyOneSpinner.setOnItemSelectedListener (new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            System.out.println("yay");
            return;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            System.out.println("neyh");
            return;
        }
    });
}
}

Solution

  • You did not set a dropdown view for the adapter. Add this line above setOnItemCLickListener

    currencyOneSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    And Since you're using an AsyncTask don't forget to call the below line everytime you update the list.

    arrayAdapter.notifyDataSetChanged();

    NOTE: You have to initialize the adapter globally.