簡體   English   中英

在列表視圖中列出HashMap的項目,android

[英]list items of HashMap in a list view, android

我正在編寫一個Android應用程序以顯示附近的位置,我有兩個活動; 一種是在地圖上顯示位置,另一種是在ListView中列出它們。

在第一個活動中,我將有關每個地點的信息存儲在hashMap中,這些信息包括:地點名稱,地點經度和緯度,這是將信息存儲在HashMap中的代碼:

//清除所有現有標記mGoogleMap.clear();

        for(int i=0;i<list.size();i++){

            // Creating a marker
            MarkerOptions markerOptions = new MarkerOptions();

            // Getting a place from the places list
            //HashMap<String, String>
            hmPlace = list.get(i);

            // Getting latitude of the place
            double lat = Double.parseDouble(hmPlace.get("lat"));

            // Getting longitude of the place
            double lng = Double.parseDouble(hmPlace.get("lng"));

            // Getting name
            String name = hmPlace.get("place_name");

           // listP[i]=hmPlace.get("place_name");
            Log.d("places=",hmPlace.get("place_name"));

            // Getting vicinity
            String vicinity = hmPlace.get("vicinity");

            LatLng latLng = new LatLng(lat, lng);

            // Setting the position for the marker
            markerOptions.position(latLng);



            // Setting the title for the marker.
            //This will be displayed on taping the marker
            markerOptions.title(name + " : " + vicinity);

            // Placing a marker on the touched position
            Marker m = mGoogleMap.addMarker(markerOptions);

            // Linking Marker id and place reference
            mMarkerPlaceLink.put(m.getId(), hmPlace.get("reference"));
        }  
    }

在此活動中,我有一個按鈕將我定向到第二個活動,該活動必須在ListView中列出附近的地方; 這是按鈕的代碼:

public void list_airports(View v)
        {
            Intent intent;
            switch (v.getId()) {

            case R.id.list_items:

                intent = new Intent(getApplicationContext(), List_airports.class);
                intent.putExtra("com.example.dashboard_our.hmPlace",hmPlace);
                startActivity(intent);

            }
            }

在第二個活動中,我這樣做:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_airports);
        Bundle extras = getIntent().getExtras();
        HashMap<String, String> places1=(HashMap<String, String>) extras.getSerializable("com.example.dashboard_our.hmPlace");


         final ListView listview = (ListView) findViewById(R.id.list);



        list = new ArrayList<String>();
            for (int i = 0; i < places1.size(); ++i) {

            list.addAll(places1.values());

            }
            }

但是它多次打印出第一位的信息,我該如何解決這個問題呢?

這是其余的代碼:

final StableArrayAdapter adapter = new StableArrayAdapter(this,
                android.R.layout.simple_list_item_1, list);
            listview.setAdapter(adapter);

            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

              @Override
              public void onItemClick(AdapterView<?> parent, final View view,
                  int position, long id) {
                final String item = (String) parent.getItemAtPosition(position);
                view.animate().setDuration(2000).alpha(0)
                    .withEndAction(new Runnable() {
                      @Override
                      public void run() {
                        list.remove(item);
                        adapter.notifyDataSetChanged();
                        view.setAlpha(1);
                      }
                    });
              }

            });
          }



          private class StableArrayAdapter extends ArrayAdapter<String> {

            HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

            public StableArrayAdapter(Context context, int textViewResourceId,
                List<String> objects) {
              super(context, textViewResourceId, objects);
              for (int i = 0; i < objects.size(); ++i) {
                mIdMap.put(objects.get(i), i);
              }
            }

            @Override
            public long getItemId(int position) {
              String item = getItem(position);
              return mIdMap.get(item);
            }

            @Override
            public boolean hasStableIds() {
              return true;
            }




          }


          public static void printMap(Map mp) {
                Iterator it = mp.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry pairs = (Map.Entry)it.next();
                   // System.out.println(pairs.getKey() + " = " + pairs.getValue());
                    list.add(pairs.toString());
                    it.remove(); // avoids a ConcurrentModificationException
                }
            }

這是解析背景並返回位置的“在后台執行”的代碼:

/** A class to parse the Google Places in JSON format */
        private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

            JSONObject jObject;

            // Invoked by execute() method of this object
            @Override
            protected List<HashMap<String,String>> doInBackground(String... jsonData) {

               // List<HashMap<String, String>>
                places = null;
                PlaceJSONParser placeJsonParser = new PlaceJSONParser();

                try{
                    jObject = new JSONObject(jsonData[0]);

                    /** Getting the parsed data as a List construct */
                    places = placeJsonParser.parse(jObject);

                }catch(Exception e){
                    Log.d("Exception",e.toString());
                }
                return places;
            }

在哪里:

  List<HashMap<String, String>> places;

要將值從哈希圖獲取到列表:

        Set keySet = hashMap.keySet();
        Iterator it = keySet.iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            Object value = (Object) hashMap.get(key)
            // do stuff here
            yourListArray.add(value);
        }

從列表到ListView:

  • 首先在適配器的構造函數中傳遞列表,然后在GetView()中使用mList.get(position)初始化單元格。
  • 如果要在列表視圖中添加或刪除單元格,請使用setter(公共無效setmList(列表列表)),然后執行adapter.notifyDataSetChanged()刷新數據。

首先,您的hmPlace是單個HashMap其中包含有關一個位置的信息。 當您將值從第一個活動傳遞給seconfd時,您將執行以下操作:

intent = new Intent(getApplicationContext(), List_airports.class);
intent.putExtra("com.example.dashboard_our.hmPlace",hmPlace);
startActivity(intent);

這意味着您只傳遞了一個包含一個位置信息的HashMap對象。 這可能是您看到該行為的原因。

更新資料

根據您上面的更新。 您的places變量具有所有位置的列表。 (希望)。

因此,您應該執行以下操作:

intent = new Intent(getApplicationContext(), List_airports.class);
intent.putExtra("places",places);
startActivity(intent);

現在,在第二個活動中,使用以下方法獲取地點列表:

ArrayList<HashMap<String, String>> placeList = null;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_airports);

    Bundle bundle = getIntent().getExtras();
    Intent intent = getIntent();
    if(bundle!=null)
    {
        placeList = (ArrayList<HashMap<String, String>>) bundle.getSerializable("places");
    }
}

現在,修改適配器以使用具有HashMap項的此新列表。 您將必須為此修改適配器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM