ArrayList多次具有相同的条目

时间:2014-05-11 10:06:42

标签: java android arraylist

我在做什么 ::

  • 我使用游标获取数据并将其添加为Hashmap对象 一个接一个到ArrayList对象并在日志中打印

发生了什么 ::

  • 我可以逐个移动光标并将数据放入HashMap

  • 因此,hashmap对象中添加了5个ArryList个对象

反过来ArrayList有5行,但hashmap对象的最后一个条目在所有行中被替换,所以

::

  • HashMap包含对象1,2,3,4,5
  • 现在在最后一次迭代后ArrayList有5,5,5,5,5而不是它 应该是1,2,3,4,5

请检查logcat <-->ArrayListObject<-->多次使用相同的条目,即使我的hashmap对象有不同的条目,我该如何解决这个问题,我是在为arraylist添加值时犯了一些错误,我该如何纠正自己


mFragSortingHome.java

public class mFragSortingHome extends SherlockListFragment implements View.OnTouchListener {

    Button ratingButtonId,priceButtonId,distanceButtonId;
    String queryString;
    ArrayList<HashMap<String, String>> arrayListBuffet=new ArrayList<HashMap<String,String>>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view=inflater.inflate(R.layout.fragment1, container, false);

        //Setting the NavigationTag from AppControllerApplication class
        AppController.CURRENT_FRAGMENT="mFragSortingHome";

        setRetainInstance(true);

        return view;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
                WillYouQuitAppDialog();
        }
        return false;
    }

    public void WillYouQuitAppDialog(){
        //GPS-Dialog
        WillYouQuitAppDialog quitAlert;
        try {
            quitAlert = new WillYouQuitAppDialog();
            quitAlert.show(getActivity().getSupportFragmentManager(), "GpsAlert_Tag");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        ratingButtonId=(Button) getActivity().findViewById(R.id.ratingButtonId);
        priceButtonId=(Button) getActivity().findViewById(R.id.priceButtonId);
        distanceButtonId=(Button) getActivity().findViewById(R.id.distanceButtonId);

        ratingButtonId.setOnTouchListener(this);
        priceButtonId.setOnTouchListener(this);
        distanceButtonId.setOnTouchListener(this);

        //getFragmentManager().beginTransaction().replace(R.id.sortBodyContainerId, FragSortParentViewAsList.newInstance("FragRatingAscendingListTag"), "FragRatingAscendingListTag").addToBackStack(null).commit();
        ratingButtonId.setBackgroundResource(R.drawable.tab_button_pressed);
        priceButtonId.setBackgroundResource(R.drawable.tab_button_default);
        distanceButtonId.setBackgroundResource(R.drawable.tab_button_default);

        CharSequence styledItemName1,styledItemName2,styledItemName3;

        styledItemName1=setMultiStylingSpan("(ASC)",new ForegroundColorSpan(Color.parseColor("#00aeef")));
        styledItemName1=TextUtils.concat(ratingButtonId.getText()+"\n",setMultiStylingSpan(styledItemName1,new RelativeSizeSpan(0.6f)));
        ratingButtonId.setText(styledItemName1);

        styledItemName2=setMultiStylingSpan("(DESC)",new ForegroundColorSpan(Color.parseColor("#00aeef")));
        styledItemName2=TextUtils.concat(priceButtonId.getText()+"\n",setMultiStylingSpan(styledItemName2,new RelativeSizeSpan(0.6f)));
        priceButtonId.setText(styledItemName2);

        styledItemName3=setMultiStylingSpan("(DESC)",new ForegroundColorSpan(Color.parseColor("#00aeef")));
        styledItemName3=TextUtils.concat(distanceButtonId.getText()+"\n",setMultiStylingSpan(styledItemName3,new RelativeSizeSpan(0.6f)));
        distanceButtonId.setText(styledItemName3);


    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        new LoadNextPage().execute();
        FragmentAdapter adapter=new FragmentAdapter(getActivity(),R.layout.display_buffet_adapater, arrayListBuffet);
        setListAdapter(adapter);
    }


    protected class LoadNextPage extends AsyncTask<Integer, Void, Integer>{

        @Override
        protected Integer doInBackground(Integer... arg0){
            /// dA=new DatabaseAdapter(getActivity());


            DatabaseHandler mHelper = new DatabaseHandler(getActivity().getApplicationContext());
            SQLiteDatabase db = mHelper.getWritableDatabase();
            String selectQuery = "SELECT * FROM buffets";
            Cursor cursor = db.rawQuery(selectQuery, null);


            HashMap<String, String> mapObj = new HashMap<String, String>();
///
            try {
                cursor.moveToFirst();
                if(cursor.moveToFirst()){
                    do{
                        mapObj.put("buf_off_id", cursor.getString(1));
                        mapObj.put("from_time", cursor.getString(2));
                        mapObj.put("to_time", cursor.getString(3));
                        mapObj.put("online_price", cursor.getString(4));
                        mapObj.put("reserved_price", cursor.getString(5));
                        mapObj.put("buf_image", cursor.getString(6));
                        mapObj.put("res_name", cursor.getString(7));
                        mapObj.put("rating", cursor.getString(8));
                        mapObj.put("latitude", cursor.getString(9));
                        mapObj.put("longitude", cursor.getString(10));
                        mapObj.put("buf_type_name", cursor.getString(11));
                        mapObj.put("from_date", cursor.getString(12));
                        mapObj.put("to_date", cursor.getString(13));
                        mapObj.put("city_id", cursor.getString(14));
                        mapObj.put("city_name", cursor.getString(15));
                        mapObj.put("meal_type_id", cursor.getString(16));
                        mapObj.put("meal_type_name", cursor.getString(17));
                        mapObj.put("distance", cursor.getString(18));
                        mapObj.put("buf_desc", cursor.getString(19));
                        Log.d("<-->MapObject<-->", mapObj.toString());
                        arrayListBuffet.add(mapObj);//Add to arraylist onject(One row i each iteration)
                    }while(cursor.moveToNext());
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                db.close();
            }
            //cursor.close();
            Log.d("<-->ArrayListObject<-->", arrayListBuffet.toString());
            return null;
        }

        @Override
        protected void onPostExecute(Integer offset){

        }
    }



    //Detecting onTouch for the tabButtons
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub

        if(v.getId()==R.id.ratingButtonId)
        {
            ratingButtonId.setBackgroundResource(R.drawable.tab_button_pressed);
            priceButtonId.setBackgroundResource(R.drawable.tab_button_default);
            distanceButtonId.setBackgroundResource(R.drawable.tab_button_default);
            switch (event.getAction())
            {

            case MotionEvent.ACTION_DOWN: 
            {
                ratingButtonId.setBackgroundResource(R.drawable.tab_button_focus);

                //v.setBackgroundResource(R.drawable.buttonpressed);
                if(AppController.RATING_LIST_FLAG==false){
                    //getFragmentManager().beginTransaction().replace(R.id.sortBodyContainerId, FragSortParentViewAsList.newInstance("FragRatingDescendingListTag"), "FragRatingDescendingListTag").addToBackStack(null).commit();
                    queryString="SELECT * FROM buffets ORDER BY rating DESC";
                    AppController.RATING_LIST_FLAG=true;
                }else{
                    //getFragmentManager().beginTransaction().replace(R.id.sortBodyContainerId, FragSortParentViewAsList.newInstance("FragRatingAscendingListTag"), "FragRatingAscendingListTag").addToBackStack(null).commit();
                    queryString="SELECT * FROM buffets ORDER BY rating ASC";
                    AppController.RATING_LIST_FLAG=false;
                }
                v.invalidate();
                break;
            }
            case MotionEvent.ACTION_UP: 
            {
                ratingButtonId.setBackgroundResource(R.drawable.tab_button_pressed);
                v.invalidate();
                break;
            }
            }
        }else if(v.getId()==R.id.priceButtonId){
            ratingButtonId.setBackgroundResource(R.drawable.tab_button_default);
            priceButtonId.setBackgroundResource(R.drawable.tab_button_pressed);
            distanceButtonId.setBackgroundResource(R.drawable.tab_button_default);
            switch (event.getAction())
            {
            case MotionEvent.ACTION_DOWN: 
            {
                priceButtonId.setBackgroundResource(R.drawable.tab_button_focus);

                //v.setBackgroundResource(R.drawable.buttonpressed);
                if(AppController.PRICE_LIST_FLAG==false){
                    //getFragmentManager().beginTransaction().replace(R.id.sortBodyContainerId, FragSortParentViewAsList.newInstance("FragPriceAscendingListTag"), "FragPriceAscendingListTag").addToBackStack(null).commit();
                    queryString="SELECT * FROM buffets ORDER BY online_price ASC";
                    AppController.PRICE_LIST_FLAG=true;
                }else{
                    //getFragmentManager().beginTransaction().replace(R.id.sortBodyContainerId, FragSortParentViewAsList.newInstance("FragPriceDescendingListTag"), "FragPriceDescendingListTag").addToBackStack(null).commit();
                    queryString="SELECT * FROM buffets ORDER BY online_price DESC";
                    AppController.PRICE_LIST_FLAG=false;
                }
                v.invalidate();
                break;
            }
            case MotionEvent.ACTION_UP: 
            {
                priceButtonId.setBackgroundResource(R.drawable.tab_button_pressed);

                //v.setBackgroundResource(R.drawable.buttonnormal);

                v.invalidate();
                break;
            }
            }
        }else if(v.getId()==R.id.distanceButtonId) {
            ratingButtonId.setBackgroundResource(R.drawable.tab_button_default);
            priceButtonId.setBackgroundResource(R.drawable.tab_button_default);
            distanceButtonId.setBackgroundResource(R.drawable.tab_button_pressed);

            switch (event.getAction())
            {
            case MotionEvent.ACTION_DOWN: 
            {

                distanceButtonId.setBackgroundResource(R.drawable.tab_button_focus);
                //v.setBackgroundResource(R.drawable.buttonpressed);
                if(AppController.DISTANCE_LIST_FLAG==false){
                    //getFragmentManager().beginTransaction().replace(R.id.sortBodyContainerId, FragSortParentViewAsList.newInstance("FragDistanceAscendingListTag"), "FragDistanceAscendingListTag").addToBackStack(null).commit();
                    queryString="SELECT * FROM buffets ORDER BY distance ASC";
                    AppController.DISTANCE_LIST_FLAG=true;
                }else{

                    //getFragmentManager().beginTransaction().replace(R.id.sortBodyContainerId, FragSortParentViewAsList.newInstance("FragDistanceDescendingListTag"), "FragDistanceDescendingListTag").addToBackStack(null).commit();
                    queryString="SELECT * FROM buffets ORDER BY distance DESC";
                    AppController.DISTANCE_LIST_FLAG=false;
                }
                v.invalidate();
                break;
            }
            case MotionEvent.ACTION_UP: 
            {
                distanceButtonId.setBackgroundResource(R.drawable.tab_button_pressed);
                v.invalidate();
                break;
            }
            }
        }


        return false;
    }

    public static CharSequence setMultiStylingSpan(CharSequence text, CharacterStyle... cs){
        SpannableStringBuilder ssb = new SpannableStringBuilder(text);
        for (CharacterStyle c : cs){
            ssb.setSpan(c, 0, text.length(), 0);
        }
        text = ssb;
        return text;
    }
}

日志 ::

05-11 15:31:25.941: D/<-->MapObject<-->(554): {city_name=bangalore, buf_type_name=indian, online_price=100, buf_desc=Dilicious food offered, meal_type_id=1, meal_type_name=breakfast, from_date=2013-12-31T18:30:00.000Z, city_id=1, distance=16, res_name=sherton, reserved_price=150, from_time=07:00:00, buf_image=indian_breakfast_sherton.jpg, to_date=2014-03-30T18:30:00.000Z, longitude=77.5554, latitude=13.0127, rating=2, to_time=12:00:00, buf_off_id=1}
05-11 15:31:26.139: D/<-->MapObject<-->(554): {city_name=bangalore, buf_type_name=chinese/thai, online_price=400, buf_desc=Dilicious food offered, meal_type_id=2, meal_type_name=lunch, from_date=2013-12-31T18:30:00.000Z, city_id=1, distance=16, res_name=sherton, reserved_price=100, from_time=12:00:00, buf_image=chinese_lunch_sherton.jpg, to_date=2014-06-29T18:30:00.000Z, longitude=77.5554, latitude=13.0127, rating=2, to_time=16:00:00, buf_off_id=2}
05-11 15:31:26.419: D/<-->MapObject<-->(554): {city_name=bangalore, buf_type_name=chinese/indian/thai, online_price=1500, buf_desc=Dilicious food offered, meal_type_id=3, meal_type_name=dinner, from_date=2013-12-31T18:30:00.000Z, city_id=1, distance=16, res_name=sherton, reserved_price=2500, from_time=12:00:00, buf_image=indian_dinner_sherton.jpg, to_date=2012-12-30T18:30:00.000Z, longitude=77.5554, latitude=13.0127, rating=2, to_time=16:00:00, buf_off_id=3}
05-11 15:31:26.469: D/<-->MapObject<-->(554): {city_name=pune, buf_type_name=rajastani, online_price=345, buf_desc=Food Served Here, meal_type_id=3, meal_type_name=dinner, from_date=2013-12-31T18:30:00.000Z, city_id=4, distance=5, res_name=leela palace, reserved_price=400, from_time=20:00:00, buf_image=rajastani_dinner_leela_palace.jpg, to_date=2014-05-30T18:30:00.000Z, longitude=77.6484, latitude=12.9617, rating=2.5, to_time=23:00:00, buf_off_id=5}
05-11 15:31:26.569: D/<-->MapObject<-->(554): {city_name=washington, buf_type_name=indian, online_price=400, buf_desc=Unique food With Taste, meal_type_id=2, meal_type_name=lunch, from_date=2013-12-31T18:30:00.000Z, city_id=3, distance=9, res_name=novotel, reserved_price=600, from_time=13:00:00, buf_image=indian_lunch_novotel.jpg, to_date=2014-05-30T18:30:00.000Z, longitude=77.607, latitude=12.9751, rating=4.5, to_time=16:00:00, buf_off_id=4}
05-11 15:31:26.799: D/dalvikvm(554): GC_CONCURRENT freed 245K, 6% free 8146K/8583K, paused 6ms+9ms
05-11 15:31:26.839: D/<-->ArrayListObject<-->(554): [{city_name=washington, buf_type_name=indian, online_price=400, buf_desc=Unique food With Taste, meal_type_id=2, meal_type_name=lunch, from_date=2013-12-31T18:30:00.000Z, city_id=3, distance=9, res_name=novotel, reserved_price=600, from_time=13:00:00, buf_image=indian_lunch_novotel.jpg, to_date=2014-05-30T18:30:00.000Z, longitude=77.607, latitude=12.9751, rating=4.5, to_time=16:00:00, buf_off_id=4}, {city_name=washington, buf_type_name=indian, online_price=400, buf_desc=Unique food With Taste, meal_type_id=2, meal_type_name=lunch, from_date=2013-12-31T18:30:00.000Z, city_id=3, distance=9, res_name=novotel, reserved_price=600, from_time=13:00:00, buf_image=indian_lunch_novotel.jpg, to_date=2014-05-30T18:30:00.000Z, longitude=77.607, latitude=12.9751, rating=4.5, to_time=16:00:00, buf_off_id=4}, {city_name=washington, buf_type_name=indian, online_price=400, buf_desc=Unique food With Taste, meal_type_id=2, meal_type_name=lunch, from_date=2013-12-31T18:30:00.000Z, city_id=3, distance=9, res_name=novotel, reserved_price=600, from_time=13:00:00, buf_image=indian_lunch_novotel.jpg, to_date=2014-05-30T18:30:00.000Z, longitude=77.607, latitude=12.9751, rating=4.5, to_time=16:00:00, buf_off_id=4}, {city_name=washington, buf_type_name=indian, online_price=400, buf_desc=Unique food With Taste, meal_type_id=2, meal_type_name=lunch, from_date=2013-12-31T18:30:00.000Z, city_id=3, distance=9, res_name=novotel, reserved_price=600, from_time=13:00:00, buf_image=indian_lunch_novotel.jpg, to_date=2014-05-30T18:30:00.000Z, longitude=77.607, latitude=12.9751, rating=4.5, to_time=16:00:00, buf_off_id=4}, {city_name=washington, buf_type_name=indian, online_price=400, buf_desc=Unique food With Taste, meal_type_id=2, meal_type_name=lunch, from_date=2013-12-31T18:30:00.000Z, city_id=3, distance=9, res_name=novotel, reserved_price=600, from_time=13:00:00, buf_image=indian_lunch_novotel.jpg, to_date=2014-05-30T18:30:00.000Z, longitude=77.607, latitude=12.9751, rating=4.5, to_time=16:00:00, buf_off_id=4}]

1 个答案:

答案 0 :(得分:4)

每次在do-while循环中使用相同的对象,从而覆盖其值。

HashMap<String, String> mapObj = new HashMap<String, String>(); // 
try {
    cursor.moveToFirst();
    if(cursor.moveToFirst()){
        do{
            mapObj.put("buf_off_id", cursor.getString(1));

            //...
            arrayListBuffet.add(mapObj);//Add to arraylist onject(One row i each iteration)
        }while(cursor.moveToNext());

您应该在每次迭代开始时创建一个新地图。

try {
    cursor.moveToFirst();
    if(cursor.moveToFirst()){
        do{
            HashMap<String, String> mapObj = new HashMap<String, String>();
            mapObj.put("buf_off_id", cursor.getString(1));

            //...
            arrayListBuffet.add(mapObj);//Add to arraylist onject(One row i each iteration)
        }while(cursor.moveToNext());