我正在寻找像Array这样的东西,但它需要存储多种数据类型. Oracle
Java教程说:“数组是一个容器对象,它保存一个固定数量的单个类型的值.”所以如果我不能使用一个数组为多种类型,我该怎么用?
我有一个代码,一次只添加一个标记到地图,因为它写在我的lat和long值每个循环,只传递最后一个onPostExecute.所以我需要像数组一样传递多种形式的联系信息.即我从每个JSON字符串中拉取位置,但我需要拉出并传递名称&电话号码也是从这个后台线程的UI.
try { String apples = endpoint.listContactInfo().execute().toString(); JSONObject jObject = new JSONObject(apples); JSONArray jsonArr = jObject.getJSONArray("items"); for(int i =0 ; i<jsonArr.length() ;i++ ){ JSONObject jsonObj1 = jsonArr.getJSONObject(i); // Storing each json item in variable String id = jsonObj1.getString(TAG_ID); String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME); String nameLast1 = jsonObj1.getString(TAG_LASTNAME); String emailAddress1 = jsonObj1.getString(TAG_EMAIL); String streetAddress1 = jsonObj1.getString(TAG_ADDRESS); String phone1 = jsonObj1.getString(TAG_PHONE); //test to see if made it to string Log.d("YOUR_TAG","First Name: " + nameFirst1 + " Last Name: " + nameLast1); address = coder.getFromLocationName(streetAddress1,5); Address location1 = address.get(0); // SET LAT LNG VALUES FOR MARKER POINT lati = location1.getLatitude(); longi = location1.getLongitude(); Log.d("Location","Location:" + lati + " " + longi); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return (long) 0; } // ADD MARKER TO MAP UI protected void onPostExecute(Long result) { mMap.addMarker(new MarkerOptions() .position(new LatLng(lati,longi)) .title("Hello world")); }
解决方法
您可以创建一个自定义类的数组.
public class YourCustomClass { String id; String name; double longitude; // and many more fields ... public YourCustomClass() { // constructor } public void setID(String id) { this.id = id; } public String getID() { return id; } // and many more getter and setter methods ... }
在您的自定义类中,您可以拥有任何可以存储数据的字段,然后使用它:
// with array YourCustomClass [] array = new YourCustomClass[10]; array[0] = new YourCustomClass(); array[0].setID("yourid"); String id = array[0].getID(); // with arraylist ArrayList<YourCustomClass> arraylist = new ArrayList<YourCustomClass>(); arraylist.add(new YourCustomObject()); arraylist.get(0).setID("yourid"); String id = arraylist.get(0).getID();
您也可以让AsyncTasks doInBackground(…)方法返回您的Custom-class:
protected void onPostExecute(YourCustomClass result) { // do stuff... }
或数组:
protected void onPostExecute(YourCustomClass [] result) { // do stuff... }
或者ArrayList:
protected void onPostExecute(ArrayList<YourCustomClass> result) { // do stuff... }
编辑:当然你也可以做一个你自定义对象的ArrayList.