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>.
Related
I want to send all the row data present in one table to server, My table having three different data rows, But when I am using Cursor it add only last row data three time. So how to get all three rows
JSONObject putjsonObjectTrans = new JSONObject();
try {
int count = dbHelper.getCountOfRows();
JSONObject invoiceDetail = new JSONObject();
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
String query = "select * from " + TABLE_NAME;
JSONArray invoiceArray = new JSONArray();
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
while (cursor.moveToNext())
{
/* for (int i = 0; i < count; i++)*/
invoiceDetail.put("ItemId", cursor.getInt(1));
invoiceDetail.put("ItemCode", cursor.getString(2));
invoiceDetail.put("ItemName", cursor.getString(3));
invoiceDetail.put("ItemQuantity", cursor.getDouble(4));
invoiceDetail.put("Rate", cursor.getDouble(5));
invoiceDetail.put("DiscAmount", cursor.getDouble(6));
invoiceDetail.put("DiscPercentage", cursor.getDouble(7));
invoiceArray.put(invoiceDetail);
}
putjsonObjectTrans.put("acc_no", acccNo);
putjsonObjectTrans.put("acc_name", accCustomerName);
putjsonObjectTrans.put("EntryType", getEntryTypeName);
putjsonObjectTrans.put("EntryDate", gSentryDAte);
putjsonObjectTrans.put("NetAmount",15.2);
putjsonObjectTrans.put("division_no", MainActivity.divisionID);
putjsonObjectTrans.put("invoicedtl", invoiceArray);
} catch (JSONException e) {
e.printStackTrace();
}
write below line inside while loop
JSONObject invoiceDetail = new JSONObject();
Change code to this
JSONObject putjsonObjectTrans = new JSONObject();
try {
int count = dbHelper.getCountOfRows();
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
String query = "select * from " + TABLE_NAME;
JSONArray invoiceArray = new JSONArray();
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
while (cursor.moveToNext())
{
/* for (int i = 0; i < count; i++)*/
JSONObject invoiceDetail = new JSONObject();
invoiceDetail.put("ItemId", cursor.getInt(1));
invoiceDetail.put("ItemCode", cursor.getString(2));
invoiceDetail.put("ItemName", cursor.getString(3));
invoiceDetail.put("ItemQuantity", cursor.getDouble(4));
invoiceDetail.put("Rate", cursor.getDouble(5));
invoiceDetail.put("DiscAmount", cursor.getDouble(6));
invoiceDetail.put("DiscPercentage", cursor.getDouble(7));
invoiceArray.put(invoiceDetail);
}
putjsonObjectTrans.put("acc_no", acccNo);
putjsonObjectTrans.put("acc_name", accCustomerName);
putjsonObjectTrans.put("EntryType", getEntryTypeName);
putjsonObjectTrans.put("EntryDate", gSentryDAte);
putjsonObjectTrans.put("NetAmount",15.2);
putjsonObjectTrans.put("division_no", MainActivity.divisionID);
putjsonObjectTrans.put("invoicedtl", invoiceArray);
} catch (JSONException e) {
e.printStackTrace();
}
JSON data stored in ArrayList and Sqlite Data Stored Also Another Arraylist. THis Two Database Compare to Each other.in Json Arraylist only New Updated data Stored in Database.JSON and sqlite database data not same after stored in sqlite database. or give me some easy way to JSON data stored in sqlite database.
MainActivity
try
{
JSONArray jsonArray = new JSONArray(s);
if(jsonArray != null){
for (int i = 0; i < 1 ;i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
StudentName = jsonObject.getString("StudentName");
RollNo = jsonObject.getDouble("RollNo");
Standard = jsonObject.getString("Standard");
Division = jsonObject.getString("Division");
FatherNo = jsonObject.getDouble("SMSNo");
Address = jsonObject.getString("Std_Address");
School = jsonObject.getString("SchoolName");
Image = jsonObject.getString("ImagePath");
StdID = jsonObject.getLong("stdid");
DivID = jsonObject.getLong("DivisionID");
String date = jsonObject.getString("DOB");
String replaceDate = date.replace("/Date(", "").replace(")/", "");
Long getDate = Long.valueOf(replaceDate);
DOB = dateFormat.format(getDate);
HashMap<String, String> map = new HashMap<String, String>();
// map.put("Id", cursor.getString(0));
map.put("UserName", StudentName);
map.put("DOB", DOB);
map.put("RollNo", String.valueOf(RollNo));
map.put("STD", Standard);
map.put("DIV", Division);
map.put("MobileNO", String.valueOf(FatherNo));
map.put("Address", Address);
map.put("School", School);
jsonList = new ArrayList<>();
jsonList.add(map);
}
DBHelper db = new DBHelper(getApplicationContext());
ArrayList<HashMap<String,String>> list = db.getAllRegistrationData();
for (int j = 0; j< jsonList.size(); j++ ){
for (int k = 0; k < list.size(); k++){
if (jsonList.get(j).equals(list.get(k))){
Toast.makeText(Registration_Activity.this, "Alredy exist", Toast.LENGTH_SHORT).show();
}else {
long id = db.insertRegistration(StudentName,RollNo,Standard,Division,FatherNo,Address,School,DOB);
Toast.makeText(Registration_Activity.this, "Insert id : " + id, Toast.LENGTH_SHORT).show();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
DBHelper
public ArrayList<HashMap<String,String>> getAllRegistrationData(){
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("select * from "+TABLE_REGISTRATION,null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("Id", cursor.getString(0));
map.put("UserName", cursor.getString(1));
map.put("DOB", cursor.getString(2));
map.put("RollNo", cursor.getString(3));
map.put("STD", cursor.getString(4));
map.put("DIV", cursor.getString(5));
map.put("MobileNO", cursor.getString(6));
map.put("Address", cursor.getString(7));
map.put("School", cursor.getString(8));
list.add(map);
} while (cursor.moveToNext());
}
return list;
}
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
I have a function that gets back JSON. Here is the format for my question of JSON.
[{"ChapterNum":"1","CourseID":"37","ChapterID":"30"},
{"ChapterNum":"2","CourseID":"37","ChapterID":"31"},
{"ChapterNum":"3","CourseID":"37","ChapterID":"32"}]
I basically want to take the "ChapterNum" with its value and store it into my android sqlite database.
I am just confused how to loop through it and put it into my DB...
for a previous db entry to do this.
public long addStudentInfoToDb(String stuID,String stuFName, String stuLName) {
ContentValues student_info = new ContentValues();
student_info.put(STU_ID, stuID);
student_info.put(STU_FNAME, stuFName);
student_info.put(STU_LNAME, stuLName);
return mDb.insert("Student", null, student_info);
}
so I was thinking like
public long addChaptersToDb() {
ContentValues chapter_info = new ContentValues();
///loop through jArray
///read array into contentvalues
return mDb.insert("Chapter", null, chapter_info);
}
Any ideas?
public long addChaptersToDb() {
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
String chapterNum = jsonData.getString("ChapterNum");
String courseID = jsonData.getString("CourseID");
String chapterID = jsonData.getString("ChapterID");
ContentValues chapter_info = new ContentValues();
chapter_info.put(ChapterNum, chapterNum);
chapter_info.put(CourseID, courseID);
chapter_info.put(ChapterID, chapterID);
mDb.insert("Chapter", null, chapter_info);
}
}
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