Android Sqlite仅获得循环的最新结果(arrayList,hashmap)



我在获取数据库的数据并迭代arrayList时遇到了问题,我在sqlite中插入了两个数据,我想通过循环选择。但是我只在循环中选择了最后一行数据。解决此问题的任何建议

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){
    }

这是你的错误

移动您的hashMap = new HashMap<String, String>(); into while loop

,然后

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

将您的hashMap = new HashMap<String, String>();移动到Loop

相关内容

最新更新