我有一个微调器,可以在下拉列表中加载客户的姓名。
微调器从 JSON 数组获取字符串。
我还有一些文本视图,当旋转器选择更改时,应加载所选客户的姓名、地址、电话号码。
但是 JSONArray 在另一个类中使用,我如何在另一个类中使用 JSONArray?(当微调器选择更改时,如何加载正确的客户详细信息?)
这是我的代码:
public class Gegevens extends Main {
Spinner spCustomers;
private JSONObject jsonChildNode;
private JSONArray jsonMainNode;
private String name;
private TextView txtNaam;
private TextView txtAdres;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gegevens);
new AsyncLoadCustDetails().execute();
spCustomers = (Spinner) findViewById(R.id.spKlanten);
spCustomers.setOnItemSelectedListener(new mySelectedListener());
txtNaam = (TextView)findViewById(R.id.txtNaam);
}
protected class AsyncLoadCustDetails extends
AsyncTask<Void, JSONObject, ArrayList<String>> {
ArrayList<CustomerDetailsTable> custTable = null;
@Override
protected ArrayList<String> doInBackground(Void... params) {
RestAPI api = new RestAPI();
ArrayList<String> spinnerArray = null;
try {
JSONObject jsonObj = api.GetCustomerDetails();
JSONParser parser = new JSONParser();
custTable = parser.parseCustomerDetails(jsonObj);
spinnerArray = new ArrayList<String>();
//All i can think of is make new array for each value?
Log.d("Customers: ", jsonObj.toString());
jsonMainNode = jsonObj.optJSONArray("Value");
for (int i = 0; i < jsonMainNode.length(); i++) {
jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.optString("Naam");
spinnerArray.add(name);
}
} catch (Exception e) {
Log.d("AsyncLoadCustDetails", e.getMessage());
}
return spinnerArray;
}
@Override
protected void onPostExecute(ArrayList<String> spinnerArray) {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item, spinnerArray);
spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item); // The drop down view
spCustomers.setAdapter(spinnerArrayAdapter);
}
}
public class mySelectedListener implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView parent, View view, int pos, long id) {
String value = (String) parent.getItemAtPosition(pos);
txtNaam.setText(value); //got the name working since it wasnt that hard
//load the other details in the textviews
}
@Override
public void onNothingSelected(AdapterView parent) {
}
}
}
这是 jsonObj 的样子:
{
"Successful": true,
"Value": [
{
"Naam": "Google",
"Adres": "Kerkstraat 3",
"Postcode": "4455 AK Roosendaal",
"Telefoon": "0165-559234",
"Email": "[email protected] /cdn-cgi/l/email-protection",
"Website": "www.google.nl"
},
{
"Naam": "Apple",
"Adres": "Kerkstraat 4",
"Postcode": "4455 AD Roosendaal",
"Telefoon": "0164-559234",
"Email": "[email protected] /cdn-cgi/l/email-protection",
"Website": "www.apple.nl"
}
]
}
(只有 2 个“客户”,因为它是虚拟数据)