0

我有一个填充有JSON对象的微调器,但我想在第一个位置手动将一个项目添加到微调器,说“选择一个”类​​型的标题spinner,我该怎么做?这是我的代码

ArrayList<Empresa> Companhias = new ArrayList<Empresa>();                   
        try {

        JSONObject mainJson = new JSONObject(new String(buffer));



            JSONArray jsonArray = mainJson.getJSONArray("GetCompaniesResult");
            Log.i("mainjson234","" +  jsonArray);

            for (int i = 0; i < jsonArray.length(); i++) {

               JSONObject objJson = jsonArray.getJSONObject(i);

                int id = objJson.getInt("CompanyID");
                String name =objJson.getString("CompanyName"); 


                Empresa empresa = new Empresa();
                empresa.setId(id);
                empresa.setCompanyName(name);
                Companhias.add(empresa);


                Log.i("empresas", "" + empresa.toString());


            }



                Spinner mySpinner = (Spinner)findViewById(R.id.spinner);

                mySpinner.setAdapter(new ArrayAdapter<Empresa>(this, android.R.layout.simple_spinner_dropdown_item,  Companhias));

                 spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
4

2 回答 2

1
    Empresa empresa = new Empresa();
            empresa.setId(0);
            empresa.setCompanyName("name");
            Companhias.add(empresa);

在你的 for 循环之前添加这些行

for (int i = 0; i < jsonArray.length(); i++) {

           JSONObject objJson = jsonArray.getJSONObject(i);

            int id = objJson.getInt("CompanyID");
            String name =objJson.getString("CompanyName"); 


            Empresa empresa = new Empresa();
            empresa.setId(id);
            empresa.setCompanyName(name);
            Companhias.add(empresa);


            Log.i("empresas", "" + empresa.toString());


        }
于 2013-05-23T15:12:16.417 回答
0

在 for 循环之前添加代码中的前四行。并在 for 循环中进行更正,如下所示。

Empresa empresa = new Empresa();
        empresa.setId(0);
        empresa.setCompanyName("name");
        Companhias.add(empresa);

for (int i = 0; i < jsonArray.length(); i++) {

       JSONObject objJson = jsonArray.getJSONObject(i);

        int id = objJson.getInt("CompanyID");
        String name =objJson.getString("CompanyName"); 

        empresa.setId(id);
        empresa.setCompanyName(name);
        Companhias.add(empresa);


        Log.i("empresas", "" + empresa.toString());
    }
于 2013-05-23T15:16:02.227 回答