- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我一直在开发一个注册表单应用程序,其中使用了几个微调器小部件。微调器用于选择国家、州和城市。因此,这些微调器需要以某种方式相互连接(下面的代码将展示我如何尝试实现这一点)。
表单代码:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="true">
<TextView
android:text="Student Registration Form"
android:textSize="22sp"
android:textAlignment="center"
android:layout_marginBottom="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/country_spinner"
android:foregroundTint="#222"
android:background="#001c47"
android:layout_marginBottom="20dp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/state_spinner"
android:foregroundTint="#222"
android:background="#001c47"
android:layout_marginBottom="20dp" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/city_spinner"
android:foregroundTint="#222"
android:background="#001c47"
android:layout_marginBottom="20dp" />
</LinearLayout>
</ScrollView>
上面的代码有更多的小部件,您可能会在 java 文件中找到它们;我没有将它们包含在上面的代码中,因为它会变得太长。
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.nfc.Tag;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class RegisterFragment extends Fragment implements View.OnClickListener, Spinner.OnItemSelectedListener{
private AppCompatButton btn_register;
private EditText et_email,et_password,et_name;
private TextView tv_login;
private ProgressBar progress;
//Declaring the Spinners
private Spinner country_spinner;
private Spinner state_spinner;
private Spinner city_spinner;
//An ArrayList for Spinner Items
private ArrayList<String> results;
// countGetData: It will keep a count of how many times get data has been run and for 0 times
// it would set the spinners to default state
private int countGetData;
ArrayList student1 = new ArrayList();
//JSON Array
private JSONArray resultArray;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_register,container,false);
initViews(view);
return view;
}
private void initViews(View view){
btn_register = (AppCompatButton)view.findViewById(R.id.btn_register);
tv_login = (TextView)view.findViewById(R.id.tv_login);
et_name = (EditText)view.findViewById(R.id.et_name);
et_email = (EditText)view.findViewById(R.id.et_email);
et_password = (EditText)view.findViewById(R.id.et_password);
progress = (ProgressBar)view.findViewById(R.id.progress);
btn_register.setOnClickListener(this);
tv_login.setOnClickListener(this);
//Initializing the ArrayList
results = new ArrayList<String>();
// Initializing countGetData
countGetData = 0;
//Initializing Spinner
country_spinner = (Spinner) view.findViewById(R.id.country_spinner);
state_spinner = (Spinner) view.findViewById(R.id.state_spinner);
city_spinner = (Spinner) view.findViewById(R.id.city_spinner);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
country_spinner.setOnItemSelectedListener(this);
state_spinner.setOnItemSelectedListener(this);
city_spinner.setOnItemSelectedListener(this);
university_spinner.setOnItemSelectedListener(this);
college_spinner.setOnItemSelectedListener(this);
ca_spinner.setOnItemSelectedListener(this);
getData("getCountries", "", 0);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.tv_login:
goToLogin();
break;
case R.id.btn_register:
String name = et_name.getText().toString();
String email = et_email.getText().toString();
String password = et_password.getText().toString();
if(!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
progress.setVisibility(View.VISIBLE);
registerProcess(name,email,password);
} else {
Snackbar.make(getView(), "Fields are empty !", Snackbar.LENGTH_LONG).show();
}
break;
}
}
private void getData(String urlPart1,String urlPart2, long itemId) {
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_URL+urlPart1+"&"+urlPart2+"="+itemId,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
resultArray = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getResults(resultArray);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getResults(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
results.add(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
if(countGetData == 0) {
student1.add("Select This");
//Setting adapter to show the items in the spinner
country_spinner.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, results));
state_spinner.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, student1));
city_spinner.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, student1));
countGetData += 1;
}
}
//this method will execute when we pic an item from the spinner
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(country_spinner.getSelectedItem().toString().equals("Austria")){
long itemId = country_spinner.getSelectedItemId();
getData("getStates","countryId",itemId);
state_spinner.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, results));
}
else{
long itemId = country_spinner.getSelectedItemId();
getData("getStates","countryId",itemId);
state_spinner.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, results));
}
}
}
有一个 PHP API 可以根据 url 返回国家、州或城市的 json。例如: http://www.example.com/location_api/api.php?type=getCountries
http://www.example.com/location_api/api.php?type=getStates&countryId=12
http://www.example.com/location_api/api.php?type=getCities&stateId=1
在 onItemSelected 中,我试图根据前一个微调器动态设置微调器。 For ex., I'm setting the state spinner whenever a country spinner item is selected.我正在通过一个 if-else block 来检查它;如果条件检查是否选择了奥地利(列表中的国家之一;随机选择)然后设置state微调器else也设置< strong>状态微调器。这样,我最终根据国家/地区微调器元素设置了状态微调器。
为了向 API 指定选择哪个国家/地区,我使用了 itemId,它包含国家/地区微调器中所选项目的 ID。 long itemId = country_spinner.getSelectedItemId();
然后,当我获得 Id 时,我调用 getData 方法来设置 result ArraryList,并将其分配给微调器 state。
getData("getStates","countryId",itemId);
state_spinner.setAdapter(new ArrayAdapter<String>(getActivity().getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, results));
上面的代码使应用程序在运行时崩溃并出现以下错误(我认为只有一部分可能有用,完整的 Logcat 文件在这里:Link):
--------- beginning of crash 04-13 21:05:09.782 9288-9600/com.gouravchawla.loginregistration E/AndroidRuntime: FATAL EXCEPTION: Thread-503 Process: com.gouravchawla.loginregistration, PID: 9288 java.lang.NegativeArraySizeException: -110 at com.android.volley.toolbox.DiskBasedCache.streamToBytes(DiskBasedCache.java:316) at com.android.volley.toolbox.DiskBasedCache.get(DiskBasedCache.java:117) at com.android.volley.CacheDispatcher.run(CacheDispatcher.java:101)
Throwing OutOfMemoryError "Failed to allocate a 1667853436 byte allocation with 777786 free bytes and 381MB until OOM"
最佳答案
例如,在您的代码中,您必须更改依赖于其他微调器的微调器的适配器。
城市 spinner
适配器因州而异 spinner
适配器
状态spinner
适配器因国家/地区而异 spinner
适配器,
我已经编写了一个示例代码来演示如何实现这一点,我已经编写了一个其他人在阅读答案时可以理解的通用代码,请随意提出建议并根据您的要求进行更改。
代码也可在 Github 上获得,以及另一个可以帮助您下载的示例 JSON
来自它使用的网络的数据,OkHttp
, GSON
和 apache-common-io
, code
public class SpinnerCountryActivity extends AppCompatActivity {
private Spinner country_Spinner;
private Spinner state_Spinner;
private Spinner city_Spinner;
private ArrayAdapter<Country> countryArrayAdapter;
private ArrayAdapter<State> stateArrayAdapter;
private ArrayAdapter<City> cityArrayAdapter;
private ArrayList<Country> countries;
private ArrayList<State> states;
private ArrayList<City> cities;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_country);
initializeUI();
}
private void initializeUI() {
country_Spinner = (Spinner) findViewById(R.id.SpinnerCountryActivity_country_spinner);
state_Spinner = (Spinner) findViewById(R.id.SpinnerCountryActivity_state_spinner);
city_Spinner = (Spinner) findViewById(R.id.SpinnerCountryActivity_city_spinner);
countries = new ArrayList<>();
states = new ArrayList<>();
cities = new ArrayList<>();
createLists();
countryArrayAdapter = new ArrayAdapter<Country>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, countries);
countryArrayAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
country_Spinner.setAdapter(countryArrayAdapter);
stateArrayAdapter = new ArrayAdapter<State>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, states);
stateArrayAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
state_Spinner.setAdapter(stateArrayAdapter);
cityArrayAdapter = new ArrayAdapter<City>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, cities);
cityArrayAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
city_Spinner.setAdapter(cityArrayAdapter);
country_Spinner.setOnItemSelectedListener(country_listener);
state_Spinner.setOnItemSelectedListener(state_listener);
city_Spinner.setOnItemSelectedListener(city_listener);
}
private AdapterView.OnItemSelectedListener country_listener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position > 0) {
final Country country = (Country) country_Spinner.getItemAtPosition(position);
Log.d("SpinnerCountry", "onItemSelected: country: "+country.getCountryID());
ArrayList<State> tempStates = new ArrayList<>();
tempStates.add(new State(0, new Country(0, "Choose a Country"), "Choose a State"));
for (State singleState : states) {
if (singleState.getCountry().getCountryID() == country.getCountryID()) {
tempStates.add(singleState);
}
}
stateArrayAdapter = new ArrayAdapter<State>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, tempStates);
stateArrayAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
state_Spinner.setAdapter(stateArrayAdapter);
}
cityArrayAdapter = new ArrayAdapter<City>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, new ArrayList<City>());
cityArrayAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
city_Spinner.setAdapter(cityArrayAdapter);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
private AdapterView.OnItemSelectedListener state_listener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position > 0) {
final State state = (State) state_Spinner.getItemAtPosition(position);
Log.d("SpinnerCountry", "onItemSelected: state: "+state.getStateID());
ArrayList<City> tempCities = new ArrayList<>();
Country country = new Country(0, "Choose a Country");
State firstState = new State(0, country, "Choose a State");
tempCities.add(new City(0, country, firstState, "Choose a City"));
for (City singleCity : cities) {
if (singleCity.getState().getStateID() == state.getStateID()) {
tempCities.add(singleCity);
}
}
cityArrayAdapter = new ArrayAdapter<City>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, tempCities);
cityArrayAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
city_Spinner.setAdapter(cityArrayAdapter);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
private AdapterView.OnItemSelectedListener city_listener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
private void createLists() {
Country country0 = new Country(0, "Choose a Country");
Country country1 = new Country(1, "Country1");
Country country2 = new Country(2, "Country2");
countries.add(new Country(0, "Choose a Country"));
countries.add(new Country(1, "Country1"));
countries.add(new Country(2, "Country2"));
State state0 = new State(0, country0, "Choose a Country");
State state1 = new State(1, country1, "state1");
State state2 = new State(2, country1, "state2");
State state3 = new State(3, country2, "state3");
State state4 = new State(4, country2, "state4");
states.add(state0);
states.add(state1);
states.add(state2);
states.add(state3);
states.add(state4);
cities.add(new City(0, country0, state0, "Choose a City"));
cities.add(new City(1, country1, state1, "City1"));
cities.add(new City(2, country1, state1, "City2"));
cities.add(new City(3, country1, state2, "City3"));
cities.add(new City(4, country2, state2, "City4"));
cities.add(new City(5, country2, state3, "City5"));
cities.add(new City(6, country2, state3, "City6"));
cities.add(new City(7, country2, state4, "City7"));
cities.add(new City(8, country1, state4, "City8"));
}
private class Country implements Comparable<Country> {
private int countryID;
private String countryName;
public Country(int countryID, String countryName) {
this.countryID = countryID;
this.countryName = countryName;
}
public int getCountryID() {
return countryID;
}
public String getCountryName() {
return countryName;
}
@Override
public String toString() {
return countryName;
}
@Override
public int compareTo(Country another) {
return this.getCountryID() - another.getCountryID();//ascending order
// return another.getCountryID()-this.getCountryID();//descending order
}
}
private class State implements Comparable<State> {
private int stateID;
private Country country;
private String stateName;
public State(int stateID, Country country, String stateName) {
this.stateID = stateID;
this.country = country;
this.stateName = stateName;
}
public int getStateID() {
return stateID;
}
public Country getCountry() {
return country;
}
public String getStateName() {
return stateName;
}
@Override
public String toString() {
return stateName;
}
@Override
public int compareTo(State another) {
return this.getStateID() - another.getStateID();//ascending order
// return another.getStateID()-this.getStateID();//descending order
}
}
private class City implements Comparable<City> {
private int cityID;
private Country country;
private State state;
private String cityName;
public City(int cityID, Country country, State state, String cityName) {
this.cityID = cityID;
this.country = country;
this.state = state;
this.cityName = cityName;
}
public int getCityID() {
return cityID;
}
public Country getCountry() {
return country;
}
public State getState() {
return state;
}
public String getCityName() {
return cityName;
}
@Override
public String toString() {
return cityName;
}
@Override
public int compareTo(City another) {
return this.cityID - another.getCityID();//ascending order
// return another.getCityID() - this.cityID;//descending order
}
}
}
此代码使用三个数据模型类 Country
, State
和 City
他们都实现了Comparable<T>
这样它们的实例就可以在 List
中根据它们的 ID 进行排序。 , 你可能想使用 Comprator<T>
这里按字母顺序排序。
我用过AdapterView.OnItemSelectedListener
跟踪 Spinner
中的变化可以更改后续微调器适配器的小部件。
我添加了一些测试数据来演示代码是如何工作的
Country Country1 Country2
______|_____ _____|_________
| | | |
State state1 state2 state3 state4
__|___ ___|___ __|___ __|____
| | | | | | | |
City city1 city2 city3 city4 city5 city6 city7 city8
关于java - 国家、州和城市微调器无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36603522/
我通过 spring ioc 编写了一些 Rest 应用程序。但我无法解决这个问题。这是我的异常(exception): org.springframework.beans.factory.BeanC
我对 TestNG、Spring 框架等完全陌生,我正在尝试使用注释 @Value通过 @Configuration 访问配置文件注释。 我在这里想要实现的目标是让控制台从配置文件中写出“hi”,通过
为此工作了几个小时。我完全被难住了。 这是 CS113 的实验室。 如果用户在程序(二进制计算器)结束时选择继续,我们需要使用 goto 语句来到达程序的顶部。 但是,我们还需要释放所有分配的内存。
我正在尝试使用 ffmpeg 库构建一个小的 C 程序。但是我什至无法使用 avformat_open_input() 打开音频文件设置检查错误代码的函数后,我得到以下输出: Error code:
使用 Spring Initializer 创建一个简单的 Spring boot。我只在可用选项下选择 DevTools。 创建项目后,无需对其进行任何更改,即可正常运行程序。 现在,当我尝试在项目
所以我只是在 Mac OS X 中通过 brew 安装了 qt。但是它无法链接它。当我尝试运行 brew link qt 或 brew link --overwrite qt 我得到以下信息: ton
我在提交和 pull 时遇到了问题:在提交的 IDE 中,我看到: warning not all local changes may be shown due to an error: unable
我跑 man gcc | grep "-L" 我明白了 Usage: grep [OPTION]... PATTERN [FILE]... Try `grep --help' for more inf
我有一段代码,旨在接收任何 URL 并将其从网络上撕下来。到目前为止,它运行良好,直到有人给了它这个 URL: http://www.aspensurgical.com/static/images/a
在过去的 5 个小时里,我一直在尝试在我的服务器上设置 WireGuard,但在完成所有设置后,我无法 ping IP 或解析域。 下面是服务器配置 [Interface] Address = 10.
我正在尝试在 GitLab 中 fork 我的一个私有(private)项目,但是当我按下 fork 按钮时,我会收到以下信息: No available namespaces to fork the
我这里遇到了一些问题。我是 node.js 和 Rest API 的新手,但我正在尝试自学。我制作了 REST API,使用 MongoDB 与我的数据库进行通信,我使用 Postman 来测试我的路
下面的代码在控制台中给出以下消息: Uncaught DOMException: Failed to execute 'appendChild' on 'Node': The new child el
我正在尝试调用一个新端点来显示数据,我意识到在上一组有效的数据中,它在数据周围用一对额外的“[]”括号进行控制台,我认为这就是问题是,而新端点不会以我使用数据的方式产生它! 这是 NgFor 失败的原
我正在尝试将我的 Symfony2 应用程序部署到我的 Azure Web 应用程序,但遇到了一些麻烦。 推送到远程时,我在终端中收到以下消息 remote: Updating branch 'mas
Minikube已启动并正在运行,没有任何错误,但是我无法 curl IP。我在这里遵循:https://docs.traefik.io/user-guide/kubernetes/,似乎没有提到关闭
每当我尝试docker组成任何项目时,都会出现以下错误。 我尝试过有和没有sudo 我在这台机器上只有这个问题。我可以在Mac和Amazon WorkSpace上运行相同的容器。 (myslabs)
我正在尝试 pip install stanza 并收到此消息: ERROR: No matching distribution found for torch>=1.3.0 (from stanza
DNS 解析看起来不错,但我无法 ping 我的服务。可能是什么原因? 来自集群中的另一个 Pod: $ ping backend PING backend.default.svc.cluster.l
我正在使用Hibernate 4 + Spring MVC 4当我开始 Apache Tomcat Server 8我收到此错误: Error creating bean with name 'wel
我是一名优秀的程序员,十分优秀!