Pregunta

What i am doing::

  • I am getting data using cursor and adding them as Hashmap Object one-by-one to a ArrayList object and printing in log

What is happening::

  • I am able to move my cursor one by one and put the data into HashMap

  • So there are 5 hashmap objects added to ArryList object

in turn ArrayList has 5 rows but the last entry of hashmap object is replaced in all the rows so

ex::

  • HashMap has objects 1,2,3,4,5
  • Now after the last iteration ArrayList has 5,5,5,5,5 instead it should be 1,2,3,4,5

Please check the logcat <-->ArrayListObject<--> has same entry many times even though i have the hashmap object has different entries, how can i resolve this, i am making some mistake in adding values to arraylist, how can i correct myself


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;
    }
}

Log::

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}]
¿Fue útil?

Solución

You are using the same object every time in your do-while loop, thus overwriting its values.

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());

You should create a new map at the beginning of each iteration.

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());
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top