嗨,有人可以指出我正确的方向如何将arraylist值插入数据库。我有两个arraylist如下:
ArrayList<HashMap<String, String>> achieve_val = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> achieve_vol = new ArrayList<HashMap<String, String>>();
HashMap<String, String> Achiev_Vol_map = new HashMap<String, String>();
Achiev_Vol_map.put(PRODUCT_CAKE, Achieve_Vcake);
Achiev_Vol_map.put(PRODUCT_YEASTEXTRACT, Achieve_Vyeastextract);
.
.
.
achieve_vol.add(Achiev_Vol_map);
我为这个值创建了一个POJO类,如下所示:
public class ProductCategory {
ArrayList<HashMap<String, String>> achieve_val,achieve_vol ;
public ArrayList<HashMap<String, String>> getAchieve_val() {
return achieve_val;}
public void setAchieve_val(ArrayList<HashMap<String, String>> achieve_val) {
this.achieve_val = achieve_val;}
public ArrayList<HashMap<String, String>> getAchieve_vol() {
return achieve_vol;}
public void setAchieve_vol(ArrayList<HashMap<String, String>> achieve_vol) {
this.achieve_vol = achieve_vol;}
/**my constructor**/
public ProductCategory(ArrayList<HashMap<String, String>> achieve_val,
ArrayList<HashMap<String, String>> achieve_vol) {
super();
this.achieve_val = achieve_val;
this.achieve_vol = achieve_vol;}}
我将此值传递给我的数据库适配器,如下所示
dbHelper.open();
dbHelper.topinchartsRecord(new ProductCategory(achieve_val,achieve_vol));
现在在我的数据库adpater中我不知道如何访问这些版本并插入数据库,完成以下操作:
public void topinchartsRecord(ProductCategory productCategory) {
for(ArrayList<HashMap<String, String>> map : achieve_val){
ContentValues cv = new ContentValues();
cv.put(FILE_NAME, map.get(FILE_NAME));
db.insert("tablename", null, cv);
}
}
答案 0 :(得分:0)
试试这个方法希望这有助于你
public void insertRecords(ArrayList<HashMap<String, String>> data,
String tableName) {
if (data != null && data.size() > 0) {
ContentValues con = new ContentValues();
db.beginTransaction();
for (int i = 0; i < data.size(); i++) {
con.clear();
HashMap<String, String> row = data.get(i);
Iterator<String> it = row.keySet().iterator();
while (it.hasNext()) {
String columnName = it.next();
con.put(columnName, row.get(columnName));
}
db.insertWithOnConflict(tableName, null, con,
SQLiteDatabase.CONFLICT_IGNORE);
}
db.setTransactionSuccessful();
db.endTransaction();
}
}
从您的方法
public void topinchartsRecord(ProductCategory productCategory) {
try{
insertRecords(productCategory.getAchieve_val(),"tableNameForThisValues");
insertRecords(productCategory.getAchieve_vol(),"tableNameForThisValues");
}catch (Exception e) {
}
}
将Hashmap的ArrayList传递给此方法,并将表的名称插入到数据库中。