Android SQLite 只在循环 (ArrayList,HashMap) 中得到的最新结果

发布时间: 2017/3/4 6:04:46
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有一个问题时从数据库中提取数据和迭代 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){

    }

解决方法 1:

这里是你的错

移动你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);
    }
赞助商