简体   繁体   English

来自服务器的数据没有进入 android 中的微调器?

[英]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:这是我的 Home.java 文件:

   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:这是 conig.java 文件:

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:这是我的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??我在 logcat 中没有收到任何错误...我不知道为什么它不显示??

According to your Attached JSON your JSON Array don't have any name and you are trying to parse like根据您的附加 JSON,您的 JSON 数组没有任何名称,您正在尝试解析

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

Your parsing seems to be incorrect.您的解析似乎不正确。

you have to parse JSON array like this -你必须像这样解析 JSON 数组 -

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当您使用 API 时,第一步是检查 API 是否正常工作,您可以使用REST_CLIENTPOSTMAN 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输入您想要的 URL 和标题,然后检查响应是否完美
If response is correct than you can move to android side如果响应正确,则可以移至 android 端

I suggest you to use Gson Liabrary for parsing gson - https://stackoverflow.com/a/41616005/4741746我建议你使用 Gson Liabrary 来解析 gson - https://stackoverflow.com/a/41616005/4741746

And you will get ArrayList directly that you need to set for Spinner您将直接获得需要为 Spinner 设置的 ArrayList

在此处输入图片说明

In the Responce section you will get your json than at android side parse it using Gson Lib BEST OF LUCK在响应部分你会得到你的 json 而不是在 android 端使用 Gson Lib BEST OF LUCK解析它

put this dependencies in app build.gradle file将此依赖项放在 app build.gradle 文件中

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.首先,您需要检查 json 是否正确解析。 For this, put a Log inside the for loop where you are getting the country code and name.为此,在获取国家代码和名称的 for 循环中放置一个Log

if the JSON that you posted is the same as you got from Log.d("Test",response);如果您发布的 JSON 与您从Log.d("Test",response);获得的相同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.否则,如果响应类似于{result:[...]} ,那么您是对的,您将解析 json。

Next, if you got the correct values inside the for loop Log, then the issue is with your Adapter.接下来,如果您在 for 循环日志中获得了正确的值,则问题出在您的适配器上。 For simplify, use a custom adapter extending the BaseAdapter instead of ArrayAdapter.为简化起见,请使用扩展BaseAdapter而不是 ArrayAdapter 的自定义适配器。

Add添加

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

before setAdapter在 setAdapter 之前

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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