Hi can someone point me in right direction how to insert arraylist values into database. i have two arraylist as below:
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);
i created a POJO class for this values as below:
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;}}
I am passing this values to my database adapter as below
dbHelper.open();
dbHelper.topinchartsRecord(new ProductCategory(achieve_val,achieve_vol));
Now in my database adpater i am not sure how to access those vlaues and insert in database , done somethin as below:
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);
}
}
Try this method Hope this help you
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();
}
}
From your Method
public void topinchartsRecord(ProductCategory productCategory) {
try{
insertRecords(productCategory.getAchieve_val(),"tableNameForThisValues");
insertRecords(productCategory.getAchieve_vol(),"tableNameForThisValues");
}catch (Exception e) {
}
}
Pass ArrayList of Hashmap to this method and name of table will insert into database.
Related
This is the class where I try to add elements from cursor to ArrayList.
public ArrayList<String> getArrayList()
{
int i;
sdb=this.getReadableDatabase();
c=null;
ArrayList<String> list=null;
try{
c=sdb.rawQuery("select * from Products", null);
c.moveToFirst();
if(c!=null)
{
list=new ArrayList<String>();
do
{
for(i=1;i<=c.getColumnCount();i++)
{
list.add(c.getString(c.getColumnIndex("ProductName")));
list.add(c.getString(c.getColumnIndex("ProduceType")));
list.add(c.getString(c.getColumnIndex("Company")));
list.add(c.getString(c.getColumnIndex("Price")));
list.add(c.getString(c.getColumnIndex("Quantity")));
}
}while(c.moveToNext());
}
else
System.out.println("c null");
}catch(Exception e)
{
e.printStackTrace();
//c=null;
}
/*finally{
if(c!=null && !c.isClosed())
{
c.close();
c=null;
}
close();
}*/
return list;
}
This is where I try to retrieve data from ArrayList and add them to expandablelistview.I want the 1st column of every row in cursor in the group view and the remaining columns of the corresponding row in child view.
private void loadData(){
db=new DatabaseHelper(this);
//db.open();
System.out.println("returned from db.open() in loadData");
ArrayList<String> al=db.getArrayList();
db.close();
int count=al.size();
int i,j;
try{
for(i=1;i<=count;i=i+5)
{
String pn=al.get(i);
for(j=i;j<=i+5;j++)
{
String inf=al.get(j);
addProduct(pn,inf);
}
}
}catch(StackOverflowError e)
{
e.printStackTrace();
}
}
I am going wrong with the for loop as of my knowledge.Logcat is showing the following error
07-04 02:44:14.747: E/CursorWindow(1881): Failed to read row 0, column -1 from a CursorWindow which has 3 rows, 5 columns.
Please tell me the correct usage of arraylist data retrieval.Thanks in advance.
I would suggest going with this approach, as the approach you are using is a bad practice.
Instead of having List of String, use an object of a custom class called ProductInfo, (which include all these Strings), and add and retrieve data from that List.
public class ProductInfo{
String productName, productType, company, price, quantity;
//getter setter
}
// add data
List<ProductInfo> productList = new ArrayList<ProductInfo>();
Cursor c = null;
do {
for (int i = 1; i <= c.getColumnCount(); i++) {
ProductInfo pInfo = new ProductInfo();
pInfo.setProductName(c.getString(c
.getColumnIndex("ProductName")));
pInfo.setProductType(c.getString(c
.getColumnIndex("ProduceType")));
pInfo.setCompany(c.getString(c.getColumnIndex("Company")));
pInfo.setPrice(c.getString(c.getColumnIndex("Price")));
pInfo.setQuantity(c.getString(c.getColumnIndex("Quantity")));
productList.add(pInfo);
}
} while (c.moveToNext());
// retrieve data
for (int i = 0; i < productList.size(); i++) {
System.out.println("Info of Product "+(i+1));
ProductInfo pInfo = productList.get(i);
System.out.println("Prod name: "+ pInfo.getProductName());
System.out.println("Prod Type: "+pInfo.getProductType());
System.out.println("Company: "+pInfo.getCompany());
System.out.println("Price: "+pInfo.getPrice());
System.out.println("Quantity: "+pInfo.getQuantity());
}
Try this way,hope this will help you to solve your problem.
public ArrayList<HashMap<String, String>> getArrayList() {
int i;
sdb = this.getReadableDatabase();
c = null;
ArrayList<HashMap<String, String>> list = null;
try {
c = sdb.rawQuery("select * from Products", null);
c.moveToFirst();
if (c != null) {
list = new ArrayList<HashMap<String, String>>();
do {
for (i = 1; i <= c.getColumnCount(); i++) {
HashMap<String, String> row = new HashMap<String, String>();
row.put("ProductName", c.getString(c.getColumnIndex("ProductName")));
row.put("ProduceType", c.getString(c.getColumnIndex("ProduceType")));
row.put("Company", c.getString(c.getColumnIndex("Company")));
row.put("Price", c.getString(c.getColumnIndex("Price")));
row.put("Quantity", c.getString(c.getColumnIndex("Quantity")));
list.add(row);
}
} while (c.moveToNext());
} else
System.out.println("c null");
} catch (Exception e) {
e.printStackTrace();
//c=null;
}
/*finally{
if(c!=null && !c.isClosed())
{
c.close();
c=null;
}
close();
}*/
return list;
}
private void loadData() {
db = new DatabaseHelper(this);
//db.open();
System.out.println("returned from db.open() in loadData");
ArrayList<HashMap<String, String>> al = db.getArrayList();
db.close();
int count = al.size();
int i, j;
try {
for (HashMap<String, String> product : al) {
System.out.println("ProductName: " + product.get("ProductName"));
System.out.println("ProduceType: " + product.get("ProduceType"));
System.out.println("Company: " + product.get("Company"));
System.out.println("Price: " + product.get("Price"));
System.out.println("Quantity: " + product.get("Quantity"));
}
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
I stored hashmap in database but when the items in hashmap are more than one, the last value is shown multiple times... for example in hashmap i have
bag
pen
book
but when I retrieve the values I get
book
book
book
How do I fix this?
DatabaseHandler.java
public void addQuote(Quote q, ArrayList<HashMap<String, String>> put_q_list)
{
myDataBase=this.getWritableDatabase();
try{
ContentValues values=new ContentValues();
values.put("q_customer_name", q.getCustomer_name());
values.put("q_customer_email", q.getCustomer_email());
values.put("q_b_street", q.getBilling_street());
values.put("q_b_city", q.getBilling_city());
values.put("q_b_state", q.getBilling_state());
values.put("q_b_zipcode", q.getBilling_zipcode());
values.put("q_b_country", q.getBilling_country());
values.put("q_s_street", q.getShipping_street());
values.put("q_s_city", q.getShipping_city());
values.put("q_s_state", q.getShipping_state());
values.put("q_s_zipcode", q.getShipping_zipcode());
values.put("q_s_country", q.getShipping_country());
values.put("q_day", q.getDay());
values.put("q_month", q.getMonth());
values.put("q_year", q.getYear());
values.put("q_total", q.getTotal());
values.put("q_discount", q.getTotal_discount());
myDataBase.insert("quote",null,values);
}catch(Exception e)
{
Log.e("bderror",e.toString());
e.printStackTrace();
}
String selectQuery = "SELECT quote_id FROM quote WHERE q_customer_email=?";
Cursor cursor = myDataBase.rawQuery(selectQuery, new String[] {q.getCustomer_email()});
int i=0;
while(cursor.moveToNext())
{
i=cursor.getInt(0);
}
cursor.close();
for (HashMap<String, String> map : put_q_list) {
ContentValues cv = new ContentValues();
cv.put("quote_id", i);
cv.put("q_item_code", map.get("item_code_final"));
cv.put("q_item_desc", map.get("desc_final"));
cv.put("q_item_price", map.get("item_price_final"));
cv.put("q_item_qty", map.get("item_qty_final"));
cv.put("q_item_tax", map.get("item_tax_final"));
cv.put("q_item_discount", map.get("item_discount_final"));
myDataBase.insert("q_item", null, cv);
}
}
Add.java`
HashMap<String, String> map_item_final = new HashMap<String, String>();
map_item_final.put("item_code_final",autoComplete_item.getText().toString());
map_item_final.put("desc_final", item_desc.getText().toString());
map_item_final.put("item_price_final", String.valueOf(item_price.getText()));
map_item_final.put("item_tax_final",String.valueOf(item_tax.getText()));
map_item_final.put("item_discount_final",String.valueOf(item_discount.getText()));
map_item_final.put("item_qty_final", item_qty.getText().toString());
final_items.add(map_item_final);
dataBase.addQuote(q, final_items);
Retrieving....
public ArrayList<HashMap<String, String>> getQuoteItem(String quote_id)
{
ArrayList<HashMap<String, String>> put_list= new ArrayList<HashMap<String, String>>();
myDataBase=this.getWritableDatabase();
Cursor cursor=myDataBase.rawQuery("SELECT * from q_item where quote_id="+Integer.parseInt(quote_id),null);
HashMap<String, String> map = new HashMap<String, String>();
while(cursor.moveToNext())
{
map.put("i_item_code", cursor.getString(1));
map.put("i_item_desc", cursor.getString(2));
map.put("i_item_price", String.valueOf(cursor.getInt(3)));
map.put("i_item_qty", String.valueOf(cursor.getInt(4)));
map.put("i_item_tax", String.valueOf(cursor.getFloat(5)));
map.put("i_item_discount", String.valueOf(cursor.getInt(6)));
put_list.add(map);
}
cursor.close();
return put_list;
}
SQLite database browser
The first items is becoming null!!! Only last item is stored
[img]
https://drive.google.com/file/d/0B8fPYT_K7J81OXl0ejFiZlpFRDQ/edit?usp=sharing
Please HELP!!!!
I think your problem is this bit of code in add quote():
int i=0;
while(cursor.moveToNext()) {
i=cursor.getInt(0);
}
You're storing the value in the cursor into an int, then overwriting it each time before you do anything with it.
create hashmap object inside of while loop
HashMap<String, String> map = null;
while(cursor.moveToNext())
{
map = new HashMap<String, String>();
map.put("i_item_code", cursor.getString(1));
map.put("i_item_desc", cursor.getString(2));
map.put("i_item_price", String.valueOf(cursor.getInt(3)));
map.put("i_item_qty", String.valueOf(cursor.getInt(4)));
map.put("i_item_tax", String.valueOf(cursor.getFloat(5)));
map.put("i_item_discount", String.valueOf(cursor.getInt(6)));
put_list.add(map);
}
I am using SQlite Database.I create 2 tables and populate them(working fine) and use there data to show in list view. when first time list adapter is populating list view show newDATA varibale as zero. some data. but when i go back and furter start that activity newDATA has correct values. . I use below code
public ArrayList<HashMap<String, Object>> GetDataFirst(String id) {
ArrayList<HashMap<String, Object>> firstvariable = new ArrayList<HashMap<String, Object>>();
Cursor c =sdb.rawQuery("Select * from table_name ",new String[]{id} );
String[] colums = c.getColumnNames();
while (c.moveToNext()) {
HashMap<String, Object> record = new HashMap<String, Object>();
for (int i = 0; i < colums.length; i++) {
record.put(colums[i], c.getString(c.getColumnIndex(colums[i])));
}
{
ArrayList<HashMap<String, String>> now_add = GetmainData(id, record.get("vget").toString());
record.put("NewDATA", now_add);
hint.add(record);
}
}
}
c.close();
return firstvariable ;
}
public ArrayList<HashMap<String, String>> GetCluesDataVerical(String id,String vhid) {
ArrayList<HashMap<String, String>> hint = new ArrayList<HashMap<String, String>>();
Cursor c = sdb.rawQuery("SELECT * FROM table_data", new String[] {id,vhid});
String[] colums = c.getColumnNames();
while (c.moveToNext()) {
HashMap<String, String> record_add = new HashMap<String, String>();
for (int i = 0; i < colums.length; i++) {
record_add.put(colums[i], c.getString(c.getColumnIndex(colums[i])));
}
hint.add(record_add);
}
c.close();
return hint;
}
and in list adapter i call these as below:
recordData=context.crossDatabaseAdapter.GetDataFirst(value);
wArray = (ArrayList<HashMap<String, String>>) recordData.get(position).get("NewDATA");
I tried a lot But still not come with any solution.
You must use an instance state to save the content of the list adapter when you stop the application and when application is starting you must check if you can retrieve data thanks to instance state, else load data from database, this might solve your problem
I try to retrieve all data from database and put into arraylist of hasmap
but i get only the last record of table.
here is my code :
databaseAirport myDbHelper = new databaseAirport(this);
myDbHelper.open();
Cursor c = myDbHelper.selectAll();
HashMap<String, String> map = new HashMap<String, String>();
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
if(c!=null && c.moveToFirst())
{
do
{
map.put(KEY_ACODE, c.getString(5).toString());
map.put(KEY_FNUM, c.getString(6).toString());
map.put(KEY_STOP_1, c.getString(8).toString());
map.put(KEY_FTIME, c.getString(7).toString());
map.put(KEY_REMARK, c.getString(10).toString());
map.put(KEY_REM_COM, c.getString(11).toString());
dataList.add(map);
}while(c.moveToNext());
}
At the end, my dataList(map) retrieve the last record only...
Can anyone help me please..
Move this line as follow: HashMap<String, String> map = new HashMap<String, String>();
databaseAirport myDbHelper = new databaseAirport(this);
myDbHelper.open();
Cursor c = myDbHelper.selectAll();
HashMap<String, String> map;
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
if(c!=null ){
c.moveToFirst();
while( cur.isAfterLast() == false )
{
map = new HashMap<String, String>(); // <---- moved here
map.put(KEY_ACODE, c.getString(5).toString());
map.put(KEY_FNUM, c.getString(6).toString());
map.put(KEY_STOP_1, c.getString(8).toString());
map.put(KEY_FTIME, c.getString(7).toString());
map.put(KEY_REMARK, c.getString(10).toString());
map.put(KEY_REM_COM, c.getString(11).toString());
dataList.add(map);
c.moveToNext();
}
}
Change your code like this
databaseAirport myDbHelper = new databaseAirport(this);
myDbHelper.open();
Cursor c = myDbHelper.selectAll();
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
while(c.moveToNext());
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ACODE, c.getString(5).toString());
map.put(KEY_FNUM, c.getString(6).toString());
map.put(KEY_STOP_1, c.getString(8).toString());
map.put(KEY_FTIME, c.getString(7).toString());
map.put(KEY_REMARK, c.getString(10).toString());
map.put(KEY_REM_COM, c.getString(11).toString());
dataList.add(map);
}
I need your help! 3 pages of purple links on Google and I'm stuck on such a simple task! What I'm trying to do is get an ArrayList of type HashMap that contains mutiple HashMaps and display them using a ListAdapter. I'm getting the information from an SQL DB, I know this is possible but I can't see what I'm doing wrong, the list just shows up blank.
public class History extends ListActivity {
ArrayList<HashMap<String, String>> inboxList;
HashMap<String, String> dealList;
ListView lv;
AddSQL entry;
Button bRefresh;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
entry = new AddSQL(History.this);
inboxList = new ArrayList<HashMap<String, String>>();
ListAdapter adapter = new SimpleAdapter(History.this, inboxList, R.layout.history_list, new String[] { SEX, NAME, RATING, DATE },
new int[] { R.id.sex, R.id.name, R.id.rating, R.id.date });
inboxList = entry.getAllEntrys();
setListAdapter(adapter);
}
/** This is my SQL */
public ArrayList<HashMap<String, String>> getAllEntrys(){
Log.d("Select", "Get");
String s = "";
String n = "";
String r = "";
String d = "";
String select = "SELECT sex, name, rating, date FROM " + MAIN_TABLE;
ArrayList<HashMap<String, String>> inboxList = new ArrayList<HashMap<String, String>>();
Log.d("Select", "1");
try{
open();
Cursor mCursor = database.rawQuery(select, null);
while(mCursor.moveToNext()){
HashMap<String, String> dealList = new HashMap<String, String>();
s = mCursor.getString(mCursor.getColumnIndex(SEX));
n = mCursor.getString(mCursor.getColumnIndex(NAME));
r = mCursor.getString(mCursor.getColumnIndex(RATING));
d = mCursor.getString(mCursor.getColumnIndex(DATE));
dealList.put(SEX, s);
dealList.put(NAME, n);
dealList.put(RATING, r);
dealList.put(DATE, d);
inboxList.add(dealList);
}
return null;
}catch (Exception e){
Log.e("Sort By List", "ERROR: " + e);
e.printStackTrace();
}
return null;
}
Your getAllEntrys always returns null, should be inboxList in the try block.