Skip to content Skip to sidebar Skip to footer

Populating Spinner With Json

I done a populating spinner with JSON.But I got a Error in ArrayList: WorldPopulation cannot be resolved. public class MainActivity extends Activity { JSONObject jsonobject

Solution 1:

From the link posted it looks like a incomplete tutorial.

//JSON Functions cannot be resolved Error occured

So the tutorial is missing JSONFunctions class and WorldPopulation class.

Have the below and keep the rest of the code the same.

privateclassDownloadJSONextendsAsyncTask<Void, Void, Void> {
    {

        @Overrideprotected Void doInBackground(Void... params) {
             world = newArrayList<WorldPopulation>();
             worldlist = newArrayList<String>();
        try
        {
        HttpClienthttpclient=newDefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpGetrequest=newHttpGet("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");
        HttpResponseresponse= httpclient.execute(request);
        HttpEntityresEntity= response.getEntity();

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

                WorldPopulationworldpop=newWorldPopulation();

                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)
        {

        }
        returnnull;
    }

Edit:

publicclassMainActivityextendsActivity {

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

    privateclassDownloadJSONextendsAsyncTask<Void, Void, Void> 
        {

            @Overrideprotected Void doInBackground(Void... params) {
                 world = newArrayList<WorldPopulation>();
                 worldlist = newArrayList<String>();
            try
            {
            HttpClienthttpclient=newDefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpGetrequest=newHttpGet("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");
            HttpResponseresponse= httpclient.execute(request);
            HttpEntityresEntity= response.getEntity();

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

                    WorldPopulationworldpop=newWorldPopulation();

                    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)
            {

            }
            returnnull;

            }
            protectedvoidonPostExecute(Void args) {
                // Locate the spinner in activity_main.xmlSpinnermySpinner= (Spinner) findViewById(R.id.my_spinner);

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

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

                            @OverridepublicvoidonItemSelected(AdapterView<?> arg0,
                                    View arg1, int position, long arg3) {
                                // TODO Auto-generated method stub// Locate the textviews in activity_main.xmlTextViewtxtrank= (TextView) findViewById(R.id.rank);
                                TextViewtxtcountry= (TextView) findViewById(R.id.country);
                                TextViewtxtpopulation= (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());
                            }

                            @OverridepublicvoidonNothingSelected(AdapterView<?> arg0) {
                                // TODO Auto-generated method stub
                            }
                        });
            }
       }

}

WorldPopulation.java

publicclassWorldPopulation {

    String rank,country,population,flag;

    publicStringgetRank() {
        return rank;
    }

    publicvoidsetRank(String rank) {
        this.rank = rank;
    }

    publicStringgetCountry() {
        return country;
    }

    publicvoidsetCountry(String country) {
        this.country = country;
    }

    publicStringgetPopulation() {
        return population;
    }

    publicvoidsetPopulation(String population) {
        this.population = population;
    }

    publicStringgetFlag() {
        return flag;
    }

    publicvoidsetFlag(String flag) {
        this.flag = flag;
    }
}

activity_main.cml

<RelativeLayoutxmlns: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" ><Spinnerandroid:id="@+id/my_spinner"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/rank"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/my_spinner" /><TextViewandroid:id="@+id/country"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/rank" /><TextViewandroid:id="@+id/population"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/country" /></RelativeLayout>

Snap

enter image description here

Solution 2:

Not sure if there is no problem with your WorldPopulation class and its object. I just saw the link again, its not mentioned anywhere what WorldPopulation is,i think it should be a java class- WorldPopulation.java. If you add that, your code should run properly. It should be like:

publicclassWorldPopulation{  

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

// getter setters here//toString if you want

}

i would suggest use Gson instead of a Json Parser. You already have the model class of WorldPopulation, now.. (this will go for all json responses)

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

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

For Naming discrepancies(according to the variables in webservice), can use annotations like @SerializedName. (So no need to use Serializable)

In your case responseContent string can just be jObject.get("worldpopulation"), can also make a class containing ArrayList object which will act as a container for the actual response..no need of extracting jobject then

Post a Comment for "Populating Spinner With Json"