AnthonyTang
AnthonyTang

Reputation: 89

Android SQLite Only get the latest result in Looping (ArrayList,HashMap)

i have a problem while fetching data from db and iterating arrayList, for example, i inserted two data in sqlite and i want to select by using looping. but i only selected last row data in my looping. any suggestion to solve this problem

public void postDataDtl(String DocNo) {
        database = new ProductDatabase.ProductDatabaseHelper(activityContext);
        try{
            String selectQuery = "select * from BarcodeDtl where DocNo='"+DocNo+"'";
            SQLiteDatabase db1 = database.getWritableDatabase();
            cursor =db1.rawQuery(selectQuery, null);

        cursor.moveToFirst();
        Barlist = new ArrayList<>();
        hashMap = new HashMap<String, String>();
        data = new JSONObject();
        array = new JSONArray();
        while(cursor.isAfterLast()==false) {
            branch = cursor.getString(cursor.getColumnIndex("Branch"));
            docno = cursor.getString(cursor.getColumnIndex("DocNo"));
            time = cursor.getString(cursor.getColumnIndex("Time"));
            seqno = cursor.getString(cursor.getColumnIndex("SeqNo"));
            barcode = cursor.getString(cursor.getColumnIndex("Barcode"));
            qty = cursor.getString(cursor.getColumnIndex("Quantity"));

            hashMap.put("branch",branch);
            hashMap.put("docno",docno);
            hashMap.put("time",time);
            hashMap.put("seqno",seqno);
            hashMap.put("barcode",barcode);
            hashMap.put("qty",qty);
            Barlist.add(hashMap);
            cursor.moveToNext();

        }
//the problem is this for loop getting same result
        for(int i=0; i<Barlist.size();i++) {
            data.put("Branch", hashMap.get("branch"));
            data.put("DocNo", hashMap.get("docno"));
            data.put("CTime", hashMap.get("time"));
            data.put("Seq", hashMap.get("seq"));
            data.put("Barcode", hashMap.get("barcode"));
            data.put("Qty", hashMap.get("qty"));
            array.put(data);
        }
//            }

//                array.put(data);
    }catch (Exception e){

    }

Upvotes: 0

Views: 109

Answers (2)

Ankush Bist
Ankush Bist

Reputation: 1892

here is your mistake

Move your hashMap = new HashMap<String, String>(); into while loop

and then

for(int i=0; i<Barlist.size();i++) {
        HashMap hashMap = Barlist.get(i);   // you have to get hashMap from Barlist again.
        data.put("Branch", hashMap.get("branch"));
        data.put("DocNo", hashMap.get("docno"));
        data.put("CTime", hashMap.get("time"));
        data.put("Seq", hashMap.get("seq"));
        data.put("Barcode", hashMap.get("barcode"));
        data.put("Qty", hashMap.get("qty"));
        array.put(data);
    }

Upvotes: 1

Pratik Popat
Pratik Popat

Reputation: 2999

Move your hashMap = new HashMap<String, String>(); into while loop

Upvotes: 0

Related Questions