Spinner没有显示所选项目,spinner从arraylist加载

时间:2014-05-01 02:51:14

标签: android

我遇到了一个我无法找到解决方案的问题。我已经查看并尝试了多种不同的解决方案,以确定旋转器为什么不能显示所选项目。它在使用硬编码数组时工作正常,但与我在onCreate中加载的ArrayList无关。微调器已填充,但它不会显示所选项目,微调器的空白区域会变宽。

public class MainActivity extends ActionBarActivity {

String[] test = new String[] {"1", "2", "3"};
ArrayList<String> routes = new ArrayList<String>();
Spinner sp;
String[] routesArray;
ArrayAdapter<String> adapter1;
final static String routeURL = "http://www.ctabustracker.com/bustime/api/v1/getroutes?key=";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, routes);
    sp = (Spinner) findViewById(R.id.spnRoute);
    loadRoutes();
    adapter1.notifyDataSetChanged();
//        routesArray = routes.toArray(new String[routes.size()]);
//        sp.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, routesArray));
//        routesArray = routes.toArray(new String[routes.size()]);
//        sp.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, routesArray));
//        sp.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, test));
}


public void loadRoutes() {
    new RequestTask().execute(routeURL);
//        routesArray = routes.toArray(new String[routes.size()]);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp.setAdapter(adapter1);
    adapter1.notifyDataSetChanged();
}

class RequestTask extends AsyncTask<String, String[], Void> {
    @Override
    protected Void doInBackground(String... strings) {
        try {
            URL routesURL = new URL(strings[0]);
            BufferedReader in = new BufferedReader(new InputStreamReader(routesURL.openStream()));
            String line;
            while((line = in.readLine()) != null) {
                if(line.contains("<rt>")) {
                    int firstPos = line.indexOf("<rt>");
                    String tempNum = line.substring(firstPos);
                    tempNum = tempNum.replace("<rt>", "");
                    int lastPos = tempNum.indexOf("</rt>");
                    routes.add(tempNum.substring(0, lastPos));
                }
            }
            in.close();
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
}

1 个答案:

答案 0 :(得分:0)

AsyncTask是异步的,这意味着它将与其他代码一起运行。因此,执行任务后的代码将继续运行,这意味着您的Adapter尚未填充,因为routes尚未包含任何数据。

<强>解决方案

将以下代码放入onPostExecute()

AsyncTask
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter1);
adapter1.notifyDataSetChanged();