来自服务器的数据未在 android 中进入微调器?
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) {
}
}
这是 congig.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 中没有收到任何错误...我不知道为什么它没有显示??
你好,你能这样试试吗
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和 邮递员
检查 -https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
输入你想要的 URL , Header 然后检查响应是否完美
如果回答正确,您可以移至 android 侧
我建议你使用 Gson Liabrary 来解析 gson - https://whosebug.com/a/41616005/4741746
并且你会直接得到你需要为Spinner设置的ArrayList
在响应部分你会得到你的 json 而不是在 android 端使用 Gson Lib 解析它 祝你好运
将此依赖项放入应用 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,您的 JSON 数组没有 任何名称,而您正在尝试解析为
result = j.getJSONArray(Config.JSON_ARRAY); // Config.JSON_ARRAY = "results";
您的解析似乎不正确。
你必须像这样解析 JSON 数组 -
JSONArray result = new JSONArray(response);
同时移除
j = new JSONObject(response);
首先,您需要检查 json 是否被正确解析。为此,在获取国家代码和名称的 for 循环中放置一个 Log
。
如果您发布的 JSON 与您从 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);
设置适配器之前
我正在尝试将服务器数据放入我的微调器中,但是当我尝试使用此代码时,我没有得到任何东西,它没有在微调器中显示任何数据。 这是我的 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) {
}
}
这是 congig.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 中没有收到任何错误...我不知道为什么它没有显示??
你好,你能这样试试吗
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和 邮递员 检查 -https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en
输入你想要的 URL , Header 然后检查响应是否完美
如果回答正确,您可以移至 android 侧
我建议你使用 Gson Liabrary 来解析 gson - https://whosebug.com/a/41616005/4741746
并且你会直接得到你需要为Spinner设置的ArrayList
在响应部分你会得到你的 json 而不是在 android 端使用 Gson Lib 解析它 祝你好运
将此依赖项放入应用 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,您的 JSON 数组没有 任何名称,而您正在尝试解析为
result = j.getJSONArray(Config.JSON_ARRAY); // Config.JSON_ARRAY = "results";
您的解析似乎不正确。
你必须像这样解析 JSON 数组 -
JSONArray result = new JSONArray(response);
同时移除
j = new JSONObject(response);
首先,您需要检查 json 是否被正确解析。为此,在获取国家代码和名称的 for 循环中放置一个 Log
。
如果您发布的 JSON 与您从 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);
设置适配器之前