2017-02-16 69 views
0

我从db中获取数据并迭代arrayList时遇到问题,例如,我在sqlite中插入了两个数据,并且我想通过循环进行选择。但我只选择了循环中的最后一行数据。任何建议,以解决这一问题Android SQLite只获取循环中的最新结果(ArrayList,HashMap)

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

    } 
+0

光标= DB1。 rawQuery(selectQuery,null);你在光标中获得了什么?两个数据还是一个? –

+0

@ZakiPathan我选择了两个数据 – AnthonyTang

+0

和我的Barlist.size()也算作两个 – AnthonyTang

回答

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

感谢您的回复!是工作!! – AnthonyTang

+0

抱歉再次打扰,还有1个问题,String entity = new StringEntity(array.toString()); httppost.setEntity(实体); – AnthonyTang

+0

这是我如何在实体中调用数组,但我仍然在数组中获得相同的结果,你知道这个吗? – AnthonyTang

0

将您hashMap = new HashMap<String, String>();到while循环