使用JSON填充Spinner

时间:2014-02-06 13:00:27

标签: android android-layout android-xml

我用JSON做了一个填充的微调器。但是我在ArrayList中遇到了错误:WorldPopulation无法解析。

    public class MainActivity extends Activity {
    JSONObject jsonobject;
    JSONArray jsonarray;
    ProgressDialog mProgressDialog;
    ArrayList<String> worldlist;
    ArrayList<WorldPopulation> world;

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

        new DownloadJSON().execute();

    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            world = new ArrayList<WorldPopulation>();
            worldlist = new ArrayList<String>();
            jsonobject = JSONfunctions
                    .getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"); //JSON Functions cannot be resolved Error occured

            try {

                jsonarray = jsonobject.getJSONArray("worldpopulation");
                for (int i = 0; i < jsonarray.length(); i++) {
                    jsonobject = jsonarray.getJSONObject(i);

                    WorldPopulation worldpop = new WorldPopulation();

                    worldpop.setRank(jsonobject.optString("rank"));
                    worldpop.setCountry(jsonobject.optString("country"));
                    worldpop.setPopulation(jsonobject.optString("population"));
                    worldpop.setFlag(jsonobject.optString("flag"));
                    world.add(worldpop);

                    worldlist.add(jsonobject.optString("country"));

                }
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

            mySpinner
                    .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                            android.R.layout.simple_spinner_dropdown_item,
                            worldlist));

            mySpinner
                    .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> arg0,
                                View arg1, int position, long arg3) {
                            TextView txtrank = (TextView) findViewById(R.id.rank);
                            TextView txtcountry = (TextView) findViewById(R.id.country);
                            TextView txtpopulation = (TextView) findViewById(R.id.population);

                            txtrank.setText("Rank : "
                                    + world.get(position).getRank());
                            txtcountry.setText("Country : "
                                    + world.get(position).getCountry());
                            txtpopulation.setText("Population : "
                                    + world.get(position).getPopulation());
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {
                            // TODO Auto-generated method stub
                        }
                    });
        }
    }

}

同样类型的ArrayList错误在代码中出现了很多行。在xml中编码一切都很好。任何人都告诉我如何解决它。

2 个答案:

答案 0 :(得分:0)

不确定您的WorldPopulation类及其对象是否存在问题。我刚看到这个链接,它没有提到WorldPopulation是什么,我认为它应该是一个java类 - WorldPopulation.java。如果添加它,您的代码应该正常运行。 应该是这样的:

public class WorldPopulation {  

String rank;
String country;
String population;
String flag;

// getter setters here

//toString if you want

}

我建议使用Gson而不是Json Parser。你已经有了WorldPopulation的模型类,现在......(这将适用于所有json响应)

  Gson gson = new Gson();
  ModelClass modelClass= new ModelClass();
  modelClass= gson.fromJson(responseContent,ModelClass.class);  

https://code.google.com/p/google-gson/

对于命名差异(根据webservice中的变量),可以使用@SerializedName等注释。 (所以不需要使用Serializable)

在你的情况下,responseContent字符串可以只是jObject.get(“worldpopulation”),也可以创建一个包含ArrayList对象的类,它将作为实际响应的容器..不需要提取jobject然后

答案 1 :(得分:0)

从发布的链接看起来它似乎是一个不完整的教程。

//JSON Functions cannot be resolved Error occured

因此教程缺少JSONFunctions类和WorldPopulation类。

使用以下内容并保持其余代码相同。

private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    {

        @Override
        protected Void doInBackground(Void... params) {
             world = new ArrayList<WorldPopulation>();
             worldlist = new ArrayList<String>();
        try
        {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpGet request = new HttpGet("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");
        HttpResponse response = httpclient.execute(request);
        HttpEntity resEntity = response.getEntity();

        String _response=EntityUtils.toString(resEntity); 
        Log.i("Response is......................",""+_response);
        jsonobject = new JSONObject(_response); 
        jsonarray = jsonobject.getJSONArray("worldpopulation");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);

                WorldPopulation worldpop = new WorldPopulation();

                worldpop.setRank(jsonobject.optString("rank"));
                worldpop.setCountry(jsonobject.optString("country"));
                worldpop.setPopulation(jsonobject.optString("population"));
                worldpop.setFlag(jsonobject.optString("flag"));
                world.add(worldpop);

                worldlist.add(jsonobject.optString("country"));         
        }catch(Exception e)
        {

        }
        return null;
    }

编辑:

public class MainActivity extends Activity {

    JSONObject jsonobject;
    JSONArray jsonarray;
    ProgressDialog mProgressDialog;
    ArrayList<String> worldlist;
    ArrayList<WorldPopulation> world;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new DownloadJSON().execute();
    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> 
        {

            @Override
            protected Void doInBackground(Void... params) {
                 world = new ArrayList<WorldPopulation>();
                 worldlist = new ArrayList<String>();
            try
            {
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpGet request = new HttpGet("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");
            HttpResponse response = httpclient.execute(request);
            HttpEntity resEntity = response.getEntity();

            String _response=EntityUtils.toString(resEntity); 
            Log.i("Response is......................",""+_response);
            jsonobject = new JSONObject(_response); 
            jsonarray = jsonobject.getJSONArray("worldpopulation");
                for (int i = 0; i < jsonarray.length(); i++) {
                    jsonobject = jsonarray.getJSONObject(i);

                    WorldPopulation worldpop = new WorldPopulation();

                    worldpop.setRank(jsonobject.optString("rank"));
                    worldpop.setCountry(jsonobject.optString("country"));
                    worldpop.setPopulation(jsonobject.optString("population"));
                    worldpop.setFlag(jsonobject.optString("flag"));
                    world.add(worldpop);

                    worldlist.add(jsonobject.optString("country"));  
                }
            }catch(Exception e)
            {

            }
            return null;

            }
            protected void onPostExecute(Void args) {
                // Locate the spinner in activity_main.xml
                Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);

                // Spinner adapter
                mySpinner
                        .setAdapter(new ArrayAdapter<String>(MainActivity.this,
                                android.R.layout.simple_spinner_dropdown_item,
                                worldlist));

                // Spinner on item click listener
                mySpinner
                        .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                            @Override
                            public void onItemSelected(AdapterView<?> arg0,
                                    View arg1, int position, long arg3) {
                                // TODO Auto-generated method stub
                                // Locate the textviews in activity_main.xml
                                TextView txtrank = (TextView) findViewById(R.id.rank);
                                TextView txtcountry = (TextView) findViewById(R.id.country);
                                TextView txtpopulation = (TextView) findViewById(R.id.population);

                                // Set the text followed by the position 
                                txtrank.setText("Rank : "
                                        + world.get(position).getRank());
                                txtcountry.setText("Country : "
                                        + world.get(position).getCountry());
                                txtpopulation.setText("Population : "
                                        + world.get(position).getPopulation());
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> arg0) {
                                // TODO Auto-generated method stub
                            }
                        });
            }
       }

}

WorldPopulation.java

public class WorldPopulation {

    String rank,country,population,flag;

    public String getRank() {
        return rank;
    }

    public void setRank(String rank) {
        this.rank = rank;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getPopulation() {
        return population;
    }

    public void setPopulation(String population) {
        this.population = population;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }
}

activity_main.cml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Spinner
        android:id="@+id/my_spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/rank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/my_spinner" />

    <TextView
        android:id="@+id/country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rank" />

    <TextView
        android:id="@+id/population"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/country" />

</RelativeLayout>

对齐

enter image description here