سؤال

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;
    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
                        }
                    });
        }
    }

}

That Same kind of ArrayList error occured many lines in a code.In xml Coding Everything was fine.Anybody tell me how to solve it.

هل كانت مفيدة؟

المحلول

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.

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;
    }

Edit:

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>

Snap

enter image description here

نصائح أخرى

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:

public class WorldPopulation {  

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 = new Gson();
  ModelClass modelClass= new ModelClass();
  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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top