[英]Data from server is not coming in spinner in android?
我正在尝试将服务器数据放入我的微调器中,但是当我尝试使用此代码时,我什么也没得到,它没有在微调器中显示任何数据。 这是我的 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) {
}
}
这是 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";
}
这是我的json:
[
{
"id": "1",
"country": "UAE"
},
{
"id": "2",
"country": "UK"
},
{
"id": "3",
"country": "SAUDI ARABIA"
},
{
"id": "4",
"country": "OMAN"
},
{
"id": "5",
"country": "BAHRAIN"
}
]
我在 logcat 中没有收到任何错误...我不知道为什么它不显示??
根据您的附加 JSON,您的 JSON 数组没有任何名称,您正在尝试解析
result = j.getJSONArray(Config.JSON_ARRAY); // Config.JSON_ARRAY = "results";
您的解析似乎不正确。
你必须像这样解析 JSON 数组 -
JSONArray result = new JSONArray(response);
也删除
j = new JSONObject(response);
嗨你能试试这样吗
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);
当您使用 API 时,第一步是检查 API 是否正常工作,您可以使用REST_CLIENT和POSTMAN Chekc - https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
输入您想要的 URL 和标题,然后检查响应是否完美
如果响应正确,则可以移至 android 端
我建议你使用 Gson Liabrary 来解析 gson - https://stackoverflow.com/a/41616005/4741746
您将直接获得需要为 Spinner 设置的 ArrayList
在响应部分你会得到你的 json 而不是在 android 端使用 Gson Lib BEST OF LUCK解析它
将此依赖项放在 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;
}
}
稍微改变你的反应这是正确的方法
{
"result": [
{
"id": "1",
"country": "UAE"
},
{
"id": "2",
"country": "UK"
},
{
"id": "3",
"country": "SAUDI ARABIA"
},
{
"id": "4",
"country": "OMAN"
},
{
"id": "5",
"country": "BAHRAIN"
}
]
}
现在你可以像这样访问它
@Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
Responce movie = gson.fromJson(response, Responce.class);
ArrayList<Data> mCountryList=movie.result;
}
}
第二种方式但不是正确的方式
@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){
}
}
}
首先,您需要检查 json 是否正确解析。 为此,在获取国家代码和名称的 for 循环中放置一个Log
。
如果您发布的 JSON 与您从Log.d("Test",response);
获得的相同Log.d("Test",response);
,那么你需要改变
从:
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);`
到:
result = new JSONArray(response);
否则,如果响应类似于{result:[...]}
,那么您是对的,您将解析 json。
接下来,如果您在 for 循环日志中获得了正确的值,则问题出在您的适配器上。 为简化起见,请使用扩展BaseAdapter
而不是 ArrayAdapter 的自定义适配器。
添加
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
在 setAdapter 之前
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.