How to save ArrayList< HashMap< String, String>> in database?
Getting NULL values in the database
I tried this method: Saving records into the database from the hashmap in android
but didn't help
public void addQuote(Quote q, ArrayList<HashMap<String, String>> put_q_list)
{
try{
myDataBase=this.getWritableDatabase();
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();
myDataBase.beginTransaction();
for (int j = 0; j < put_q_list.size(); j++) {
HashMap<String, String> map = new HashMap<String, String>();
map = put_q_list.get(j);
//Each value by using this method
String item_code = map.get("item_code_final");
ContentValues cv = new ContentValues();
cv.put("quote_id", i);
cv.put("q_item_code", item_code);
myDataBase.insert("q_item", null, cv);
}
myDataBase.setTransactionSuccessful();
myDataBase.endTransaction();
myDataBase.close();
}
Only the value of "i" is being inserted!!! not the item code
Please help!!!
try this. It should work.
for (int i = 0; i < mapList.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map = mapList.get(i);
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"));
db.insert("tablename", null, cv);
}
db.close();
You should first declare an Database instance to deal with and begin the transactions. as following
SQLiteDatabase db = mDbHelper.getDatabase();
db.beginTransaction();
Then perform the loop
for(HashMap<String, String> map : mylist){
ContentValues cv = new ContentValues();
cv.put(FILE_NAME, map.get(FILE_NAME));
cv.put(DESC, map.get(DESC));
cv.put(UPLOADED_BY, map.get(DATE_UPLOADED));
cv.put(ACTION, map.get(FILE_NAME));
cv.put(ID, map.get(ID));
cv.put(FILE_URI, map.get(FILE_URI));
db.insert("tablename", null, cv);
}
Then close the cursor
db.setTransactionSuccessful();
db.endTransaction();
db.close();
That was clear in your link in the accepted answer
Related
I need to insert an array loaded by JSON into an SQLite database. Any help is appreciated.
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray sites = jsonObj.getJSONArray("Sites");
for (int i = 0; i < sites.length(); i++) {
JSONObject c = sites.getJSONObject(i);
String id = c.getString("id");
String nam = c.getString("names");
String loc = c.getString("location");
HashMap<String, String> sit = new HashMap<>();
sit.put("id", id);
sit.put("names", name);
sit.put("location", loc);
array_sites.add(sit);
Try this:
public void addData(ArrayList<String> list){
int size = list.size();
SQLiteDatabase db = getWritableDatabase();
try{
for (int i = 0; i < size ; i++){
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, list.get(i));
Log.d("Data Inserted ",""+ cv);
db.insertOrThrow(TABLE_NAME, null, cv);
}
db.close();
}catch (Exception e){
Log.e("Exception>>>>", e + " ");
}
Call from where you store your data
addData(array_sites);
I suggested for ArrayList<String>, You can use your own ArrayList<YourDataType>.
ERROR- am getting as type mistmatch.
Here is my code-Please help
public void addDetailDescription(List<Detail> detailList) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < detailList.size(); i++) {
Log.e("vlaue inserting==", "" + detailList.get(i));
values.put(DETAIL_ID, String.valueOf(detailList.get(i)));
values.put(COLUMN_HEADING, String.valueOf(detailList.get(i)));
values.put(COLUMN_IMAGE_DETAIl, String.valueOf(detailList.get(i)));
values.put(COLUMN_DETAIL, String.valueOf(detailList.get(i)));
values.put(DETAIL_DESCRIPTION_ID, String.valueOf(detailList.get(i)));
}
db.insert(DESCRIPTION_DETAIL_TABLE, null, values);
db.close();
}
I think you have to write a function like this and in a for cycle ,call this function for each item of list.
public long SaveUsers(Users users) {
long id = -1;
ContentValues contentValues = null;
try {
contentValues = new ContentValues();
contentValues.put("name", users.getName());
contentValues.put("email", users.getEmail());
contentValues.put("phone", users.getPhone());
contentValues.put("password", users.getPassword());
db=sqliteHelper.getWritableDatabase();
id = db.insert(SqliteHelper.TABLE_USERS, null, contentValues);
} catch (Exception e) {
Log.d("Database Insert","Exception:"+e.getMessage());
} finally {
if(db!=null && db.isOpen())
db.close();
}
return id;
}
In your code, contentValue change every time and finally just the last item will be inserted to database and it's completely wrong.
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);
}
Hi I just want to know better on how to use this. Since I'm using this kind of method in doing my custom listView now I wanted to apply it since I love the approach on this but I don't know how I should do it. Anyway What I have is a database query where I get all the result from a search query in SQLite Database. Now I'm sure about the content of my query since I already tested it but when I display it the result always return the same output which is the last row of the query. For better understanding here's my code:
public ArrayList<HashMap<String,String>> getList(String search_param){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> hashmap = new HashMap<String,String>();
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
if (cursor.moveToFirst()) {
do {
item_list.put("column1", cursor.getString(0));
item_list.put("column2",cursor.getString(1));
list.add(hashmap);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
now to retrieve the list here's what I tried so far:
ArrayList<HashMap<String,String>> new_list;
DatabaseClass db = new DatabaseClass(getActivity());
new_list = db.getList("");
for(int i=0;i<new_list.size();i++){
HashMap<String,String> content = new HashMap<String, String>();
content = new_list.get(i);
Log.v("The hashmap",content.get("column1").toString());
Log.v("The hashmap",content.get("column2").toString());
}
now the content of my Database should be 1,2,3 for column1 and test1,test2,test3 for column2. but what I get from the result are 3,3,3 and test3,test3,test3
I also tried the method of doing
newlist.get(i).get("column1").toString; but it doesn't even solve the problem.
Any idea on what I should do about this?
Within do while you need to create instance for hashmap,
public ArrayList<HashMap<String,String>> getList(String search_param){
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> hashmap;
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
if (cursor.moveToFirst()) {
do {
hashMap = new HashMap<String,String>();
hashMap.put("column1", cursor.getString(0));
hashMap.put("column2",cursor.getString(1));
list.add(hashmap);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
This works like charm with me
public ArrayList<HashMap<String, String>> getList(String search_param){
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
String query_select = "SELECT column1, column2 FROM tablename WHERE column2 LIKE '%"+ search_param +"%';";
Cursor cursor = db.rawQuery(query_select,null);
int colCount = cursor.getColumnCount();
int rowCount = cursor.getCount();
if (cursor.moveToFirst()) {
do {
HashMap<String, String> col = new HashMap<String, String>();
int size =cursor.getColumnCount();
for (int i = 0; i < size; i++) {
col.put(cursor.getColumnName(i), cursor.getString(i));
}
list.add(col);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
I just wanted to ask help for this one. I have a hashmap populate in the listview. the code below is my code for my hashmap:
mylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < listSelectedFileNames.size(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(FILE_NAME, selectedFileNames[i]);
map.put(DESC, "");
map.put(UPLOADED_BY, "User");
map.put(DATE_UPLOADED, myDate);
map.put(ACTION, "Delete");
map.put(ID, String.valueOf(i));
map.put(FILE_URI, selectedFileUri[i]);
mylist.add(map);
}
How can I possibly save that data in the database. FILE_NAME, DESC, UPLOADED_BY, FILE_URI are the different columns in my database. Thanks for anyone who would help me. Here's the other code that maybe could help.
selectedFileNames = new String[listSelectedFileNames.size()];
for (int i = 0; i < listSelectedFileNames.size(); i++) {
selectedFileNames[i] = listSelectedFileNames.get(i);
}
selectedFileUri = new String[listSelectedFileUri.size()];
for (int i = 0; i < listSelectedFileUri.size(); i++) {
selectedFileUri[i] = listSelectedFileUri.get(i);
}
myCustomAdapterIreport = new CustomArrayAdapterIreport(getApplicationContext(), mylist, R.layout.attribute_selected_ireport_file,
new String[]{FILE_NAME, DESC, UPLOADED_BY, DATE_UPLOADED, ACTION, ID, FILE_URI},
new int[]{R.id.tv_iFile, R.id.txt_iDesc,R.id.tv_iUploadedBy,R.id.tv_iDateUploaded, R.id.tv_iAction, R.id.tv_RowId, R.id.tv_iUri}, true);
lv_AttachedFileData.setAdapter(myCustomAdapterIreport);
SQLiteDatabase db = mDbHelper.getDatabase();
db.beginTransaction();
for(HashMap<String, String> map : mylist){
ContentValues cv = new ContentValues();
cv.put(FILE_NAME, map.get(FILE_NAME));
cv.put(DESC, map.get(DESC));
cv.put(UPLOADED_BY, map.get(DATE_UPLOADED));
cv.put(ACTION, map.get(FILE_NAME));
cv.put(ID, map.get(ID));
cv.put(FILE_URI, map.get(FILE_URI));
db.insert("tablename", null, cv);
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
A database helper will need to be implemented by you, the string keys will need to match the column names. You can read more on database helpers here: http://developer.android.com/training/basics/data-storage/databases.html