简体   繁体   中英

Data from server is not coming in spinner in android?

I am trying to get server data into my spinner , but when i tried with this code , i am not getting anything, its not showing any data in spinner. here is my Home.java file:

   public class Home extends AppCompatActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {

    private Spinner countrySpinner, locationSpinner, citySpinner;
    private TextView cityCodeTextView;
    private Button submitButton;
    private ArrayList<String> country_list, location_list, city_list;
    private JSONArray result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        countrySpinner = (Spinner) findViewById(Country);
        //citySpinner = (Spinner) findViewById(City);
        //locationSpinner = (Spinner) findViewById(R.id.Location);
        countrySpinner.setOnItemSelectedListener(this);

        country_list = new ArrayList<String>();
        //location_list = new ArrayList<String>();
        // city_list = new ArrayList<String>();

        getData();
    }
    private void getData(){
        StringRequest
                stringRequest = new StringRequest(Config.DATA_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        JSONObject j = null;
                        try {
                            Log.d("Test",response);
                            j = new JSONObject(response);

                            //Storing the Array of JSON String to our JSON Array
                            result = j.getJSONArray(Config.JSON_ARRAY);

                            //Calling method getStudents to get the students from the JSON Array
                            getCountry(result);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
                RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

    private void   getCountry(JSONArray  jsonArrayCountry){
        //Traversing through all the items in the json array
        List<Country> countries = new ArrayList<>();

        try {

            String country_name, country_code;
            JSONObject countries_object;


            for (int i = 0; i < jsonArrayCountry.length(); i++) {
                countries_object = jsonArrayCountry.getJSONObject(i);
                country_code = countries_object.getString("id");
                country_name = countries_object.getString("country");
                countries.add(new Country(country_code, country_name));
            }
            ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries);
            countrySpinner.setAdapter(countryAdapter);
            countrySpinner.setOnItemSelectedListener(this);
        } catch (JSONException e) {
            Log.e("Home", e.getLocalizedMessage(), e);
        }



    }

    //Method to get student name of a particular position

    //Doing the same with this method as we did with getName()


    //Doing the same with this method as we did with getName()



    //this method will execute when we pic an item from the spinner
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        //Setting the values to textviews for a selected item
        //textViewName.setText(getName(position));
        //textViewCourse.setText(getCourse(position));
        //textViewSession.setText(getSession(position));
    }

    //When no item is selected this method would execute
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
       // textViewName.setText("");
      //  textViewCourse.setText("");
        //textViewSession.setText("");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }
}

this is congig.java file:

public class Config {
    //JSON URL
    public static final String DATA_URL = "http://..../get_country.php";


    //JSON array name
    public static final String JSON_ARRAY = "result";
}

this is my json:

[
  {
    "id": "1",
    "country": "UAE"
  },
  {
    "id": "2",
    "country": "UK"
  },
  {
    "id": "3",
    "country": "SAUDI ARABIA"
  },
  {
    "id": "4",
    "country": "OMAN"
  },
  {
    "id": "5",
    "country": "BAHRAIN"
  }
]

i am not getting any error in logcat...i dont know why its not showing??

According to your Attached JSON your JSON Array don't have any name and you are trying to parse like

result = j.getJSONArray(Config.JSON_ARRAY); // Config.JSON_ARRAY = "results";

Your parsing seems to be incorrect.

you have to parse JSON array like this -

JSONArray result = new JSONArray(response);

Also remove

j = new JSONObject(response);

Hi Can you try like this

for (int i = 0; i < jsonArrayCountry.length(); i++) {
           countries_object = jsonArrayCountry.getJSONObject(i);
           country_code = countries_object.getString("id");
           country_name = countries_object.getString("country");
           countries.add(new Country(country_code, country_name));
         }
ArrayAdapter countryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, countries);
countrySpinner.setAdapter(countryAdapter);

When you working with API First step is to check if API work Properly or not for that purpose you can use REST_CLIENT and POSTMAN Chekc - https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en

Put your URL , Header you want than check if response is perfect or not
If response is correct than you can move to android side

I suggest you to use Gson Liabrary for parsing gson - https://stackoverflow.com/a/41616005/4741746

And you will get ArrayList directly that you need to set for Spinner

在此处输入图片说明

In the Responce section you will get your json than at android side parse it using Gson Lib BEST OF LUCK

put this dependencies in app build.gradle file

dependencies {
  compile 'com.google.code.gson:gson:2.6.2'
} 




public class Responce implements Serializable {

    @SerializedName("result")
    public ArrayList<Data>  result;

    public class Data implements Serializable {

     /*{
       "id": "1",
       "country": "UAE"
     },*/
    @SerializedName("country")
    public String  country;

    @SerializedName("id")
    public String  id;
    }
} 

Slightly change your response this is proper way to do this

{
    "result": [
        {
            "id": "1",
            "country": "UAE"
        },
        {
            "id": "2",
            "country": "UK"
        },
        {
            "id": "3",
            "country": "SAUDI ARABIA"
        },
        {
            "id": "4",
            "country": "OMAN"
        },
        {
            "id": "5",
            "country": "BAHRAIN"
        }
    ]
}

And now you can access it like

             @Override
                public void onResponse(String response) {


                  Gson gson = new GsonBuilder().create();
                  Responce movie = gson.fromJson(response, Responce.class);
                  ArrayList<Data>  mCountryList=movie.result;

                }
            } 

Second Way But not proper way

@Override
   public void onResponse(String response) {


    try {
                    ArrayList<String> mStrings = new ArrayList<>();
                    JSONArray myArray = new JSONArray(response);
                    for(int i=0 ;i< myArray.length();i++){
                        JSONObject mObject = (JSONObject) myArray.get(i);
                        String id=  mObject.getString("id");
                        String country=  mObject.getString("country");
                        mStrings.add(country);
                    }
                    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mStrings); //selected item will look like a spinner set from XML
                    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinner.setAdapter(spinnerArrayAdapter);
                }catch (Exception e){

                }
      }
  } 

First, you need to check if the json is parsed correctly. For this, put a Log inside the for loop where you are getting the country code and name.

if the JSON that you posted is the same as you got from Log.d("Test",response); , then you need to change
From:

j = new JSONObject(response);
 //Storing the Array of JSON String to our JSON Array 
result = j.getJSONArray(Config.JSON_ARRAY);`

To:
result = new JSONArray(response);

Or else, if the response is like {result:[...]} , Then you are correct, you will get the json parsed.

Next, if you got the correct values inside the for loop Log, then the issue is with your Adapter. For simplify, use a custom adapter extending the BaseAdapter instead of ArrayAdapter.

Add

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

before setAdapter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM