【问题标题】:list items of HashMap in a list view, android在列表视图中列出 HashMap 的项目,android
【发布时间】:2013-11-29 08:31:43
【问题描述】:

我正在编写一个 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
                }
            }

这是解析 Json 并返回位置的“后台执行”代码:

/** 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;

【问题讨论】:

  • by "打印第一个位置的信息" 你的意思是在日志中打印还是在列表视图中显示?如果在列表视图中.. 然后发布您的适配器代码。如果在日志中打印,那么您序列化数据的方式有问题
  • 您应该使用 list.get(i) 来获取 hashmap 值。
  • @AmulyaKhare 在列表视图中,我将编辑我的问题
  • @HAL9000 我怎么能使用 list.get(i)??我想将 HashMap 中的值添加到列表中,然后将它们放入 ListView
  • @AmulyaKhare 检查编辑

标签: android listview hashmap


【解决方案1】:

从哈希映射中获取值到列表:

        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:

  • 首先在 Adapter 的构造函数中传递 List,在 GetView() 中使用 mList.get(position) 来初始化单元格。
  • 如果要在列表视图中添加或删除单元格,请使用 setter (public void setmList(List list)),然后执行 adapter.notifyDataSetChanged() 刷新数据。

【讨论】:

  • 没有变化!!它仍然打印第一名的信息
  • 我试图根据我对您问题的理解提供帮助。也许您的问题还不够清楚:) 您是否想将 hashmap 值放入列表中,然后在刷新之前将其传递给列表视图? (一个建议:你应该更多地分离你的代码并使用更好的缩进)而且使用 BaseAdapter 很简单..
  • 我有一个 HashMap,我想从中获取值并将它们放入列表中以便在 listView 中查看它们,我的问题是:我只得到一个元素,它被打印了 5 次
  • 好的,我给你的方法有效(我使用它)尝试做一些日志来看看你的价值观发生了什么
【解决方案2】:

首先,您的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 项的新列表。您必须为此修改适配器。

【讨论】:

  • 正如我所提到的,这是一个可能的原因。你能验证我所说的是否正确吗?查看第二个活动中的list 是否有所有位置?我还问你截图..这会有所帮助
  • 我在上面回答了你的问题 :)
  • 如果您有任何我需要的进一步信息,请告诉我。否则我现在帮不了你..
  • 我不知道您可能需要什么信息!我觉得你说的是对的,hmPlace 包含一个地方的信息。我将发布一个解析 Json 并获取位置的代码
  • 你发布第一个活动怎么样让我看看..也许我会尝试编译看看。
猜你喜欢
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多