I saw in the SQLite documentation that you can not insert multiple records at the same time. For example, I have 2 TEXT fields and at the same time I want to insert in filed1 10 records with the date that goes from today to 10 days, and in the field2 value of 50 was added in the 10 record. I hope I explained.
Now normally I insert the record in this way:
public void insertDb(View v) {
ContentValues cv = new ContentValues();
cv.put(Table.ONE, mNe.getText().toString());
cv.put(Table.ONE, mNel.getText().toString());
...
for that you have to use for loop or anything
like below code
public void add_device(String data,
ArrayList<HashMap<String, String>> jsonlist) {
try {
database = this.getWritableDatabase();
for (HashMap<String, String> map : jsonlist) {
ContentValues values = new ContentValues();
values.put(SAVE_COLUMN_NAME, data);
values.put(SAVE_COLUMN_KEY, map.get(SAVE_COLUMN_KEY));
values.put(SAVE_COLUMN_VALUE, map.get(SAVE_COLUMN_VALUE));
Long int1 = database.insertOrThrow(SAVE_TABLE_NAME, null,
values);
Log.i("inserted value", values + "");
Log.i("insserted value ", int1 + "");
}
}
catch (Exception e) {
}
}
you can use loop like i have used
Related
I'm creating a forum application and I currently if I delete a thread I'm deleting all threads.
Is there a good method or query to check if the UserId == ThreadId?
My current code:
public void deleteThread() {
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_THREAD, null, null);
db.close();
Log.d(TAG, "Deleted all Thread info from sqlite");
}
You need to pass correct value to the well-documented delete method to narrow down the scope of deletion to a subset of all entries in the DB table.
public void deleteThreadById(String threadId) {
SQLiteDatabase db = this.getWritableDatabase();
String whereClause = "threadId = " + threadId;
db.delete(TABLE_THREAD, whereClause, null);
db.close();
}
Deleting all threads of a given user via their userId would be similar but probably doesn't make sense in a forum software.
This is how SQL works in general and it's a bit scary you started development without familiarising yourself with the very basics.
Something like this;
public void deleteThread(String threadName) {
SQLiteDatabase db = this.getWritableDatabase();
try {
db.delete(MYDATABASE_TABLE, "name = ?", new String[]{threadName});
} catch (Exception e) {
e.printStackTrace();
} finally {
db.close();
}
}
Something long these lines, querying database to find the specific row that has column which matches the parameter.
For example to delete a row which the name column is "Hello World";
deleteThread("Hello World");
I am trying to insert 1120 records (records=questions since it is trivia game) in my database but it is taking around 20secs i can't even work with insertHelper because it has been deprecated in android.
i searched a lot and used beginTransaction(),setTransactionSuccessful() & db.endTransaction(); but nothing helped. maybe i haven't used them correct so please correct me if it's wrong
HelperClass
private void addingeachquestions(Questions question) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put(QUESTION, question.getQUESTION());
values.put(OPTION1, question.getOPT1());
values.put(ANSWER, question.getANSWER());
values.put(ANSWER2, question.getANSWER2());
db = this.getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
public void addquestions() {
//famous people
Questions q1 = new Questions("Who was the first African American to have served as president of United States of America ?", "BAROBAACKMAQCAEMBD", "BARACK", "OBAMA");
this.addingeachquestions(q1);
Questions q2 = new Questions("Who co-founded Apple company with Steve Wozniak, Ronald Wayne ?", "TSOVWIBYUBZRGOEJSE", "STEVE", "JOBS");
this.addingeachquestions(q2);
MainActivityClass
demoHelperClass = new DemoHelperClass(this);
SQLiteDatabase sqLiteDatabase = demoHelperClass.getWritableDatabase();
demoHelperClass.addquestions();
I have used below method for around 1,00,000 rows insert and definitely faster than other. You can try it.
Instead of one bye one data insert, directly beginTransaction and insert all data and complete transaction.
Add below code(function) in DatabaseHelper(/DbHelper) class and call that function with arraylist of custom class(DataModel class).
Make some adding/changes as per your requirement:-
public void insertBigDataQuickly(ArrayList<DataModel> arrayList) {
SQLiteDatabase db = this.getWritableDatabase(); //db is instance of DatabaseHelper(/DBHelper) class
db.beginTransaction();
try {
String sql = "Insert or Replace into table_name (column1, column2, column3) values(?,?,?)";
SQLiteStatement statement = db.compileStatement(sql);
for (int i = 0; i < arrayList.size(); i++) { //Loop to insert all data one-by-one with Arraylist data
DataModel singleData = arrayList.get(i);
statement.bindString(1, singleData.getValue1()); //1 - Index value of column
statement.bindLong(2, singleData.getValue2()); //2 - Index value of column
statement.bindDouble(3, singleData.getValue3()); //3 - Index value of column
statement.executeInsert();
}
db.setTransactionSuccessful(); // This commits the transaction
}catch (Exception e) {
e.printStackTrace();
Log.d("Database error: ",e.getMessage());
}
finally {
db.endTransaction();
}
db.close();
}
You can collect your data, put it in a list, then iterate through the list inside a transaction like so:
private void addAllQuestions(Arraylist<Questions> allQuestions) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
for (Questions question: allQuestions) {
values.put(QUESTION, question.getQUESTION());
values.put(OPTION1, question.getOPT1());
values.put(ANSWER, question.getANSWER());
values.put(ANSWER2, question.getANSWER2());
db = this.getWritableDatabase();
db.insert(TABLE_NAME, null, values);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
public void addquestions() {
//famous people
ArrayList<Questions> allQuestions = new ArrayList<Questions>();
allQuestions.append(new Questions("Who was the first African American to have served as president of United States of America ?", "BAROBAACKMAQCAEMBD", "BARACK", "OBAMA"));
allQuestions.append(new Questions("Who co-founded Apple company with Steve Wozniak, Ronald Wayne ?", "TSOVWIBYUBZRGOEJSE", "STEVE", "JOBS"));
this.addAllQuestions(allQuestions);
}
Based on this: https://stackoverflow.com/a/32088155/4268599
I have saved data in database. I am trying to update data.
But record is not getting update.
If I debug the update function it shows the values i have entered. But when I retrieve the data it dose not show updated values.
What's wrong?
update function in helper class
public int updateEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE,event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
values.put(KEY_NOTIFICATION_TIME,event.getNotificationTime());
// updating row
return db.update(TABLE, values, KEY_ID + " = ?",
new String[] { String.valueOf(event.getId()) });
}
updating in activity:
if (editMode) {
eventData.setTitle(title.getText().toString());
eventData.setFromDate(showFromTime.getText().toString());
eventData.setToDate(showToTime.getText().toString());
eventData.setDayOfWeek(selectDay.getText().toString());
eventData.setLocation(mAutocompleteView.getText().toString());
eventData.setNotificationTime(notifyTime.getText().toString());
db.updateEvent(eventData);
}
else {
db.addEvent(new EventData(eventTitle, startTime, endTime, dayOfWeek, location, notificationTime));
}
setResult(RESULT_OK, i);
finish();
}
Thank you..
The code below takes data from an ArrayList and writes it to the SQLite database on the device.It runs fairly slow, with an ArrayList size of about 800, it takes about 1.5 minutes.Do you see anything that could make it run faster?
Iterator<PermitData> iterator = permitDataArrayList.iterator();
while (iterator.hasNext()) {
PermitData permitData = (PermitData) iterator.next();
HashMap<String, String> queryValues = new HashMap<String, String>();
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_ID, Integer.toString(permitData.Id));
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_TYPE, permitData.Type);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_NAME, permitData.Name);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD1, permitData.Field1);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD2, permitData.Field2);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD3, permitData.Field3);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD4, permitData.Field4);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD5, permitData.Field5);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD6, permitData.Field6);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD7, permitData.Field7);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD8, permitData.Field8);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD9, permitData.Field9);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD10, permitData.Field10);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD11, permitData.Field11);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD12, permitData.Field12);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD13, permitData.Field13);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD14, permitData.Field14);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD15, permitData.Field15);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_TO_DATE, permitData.ToDate);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FROM_DATE, permitData.FromDate);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD16, permitData.Field16);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD17, permitData.Field17);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_ADDRESS, permitData.Address);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_PHONE, permitData.Phone);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD18, permitData.Field18);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_EMAIL, permitData.Email);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD19, permitData.Field19);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_XCOORD, permitData.XCoord);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_YCOORD, permitData.YCoord);
queryValues.put(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_FIELD20, permitData.Field20);
try {
sqLiteManager.insertOrUpdatePermit(PermitDataContract.PermitDataEntry.TABLE_NAME, queryValues);
}
catch (Exception e) {
Log.d("StoreData", " Id: " + queryValues.get(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_ID) + " Name: " + queryValues.get(PermitDataContract.PermitDataEntry.COLUMN_NAME_PERMIT_NAME));
}
} // end while
SQLiteManager.java
public synchronized void insertOrUpdatePermit(String tableName, HashMap<String, String> queryValues) {
ContentValues contentValues = new ContentValues();
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_ID, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_ID));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_TYPE, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_TYPE));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_NAME, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_NAME));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD1, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD1));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD2, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD2));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD3, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD3));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD4, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD4));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD5, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD5));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD6, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD6));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD7, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD7));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD8, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD8));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD9, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD9));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD10, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD10));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD11, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD11));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD12, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD12));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD13, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD13));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD14, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD14));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD15, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD15));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FROM_DATE, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FROM_DATE));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_TO_DATE, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_TO_DATE));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD16, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD16));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD17, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD17));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_ADDRESS, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_ADDRESS));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_PHONE, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_PHONE));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD18, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD18));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_EMAIL, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_EMAIL));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD19, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD19));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_XCOORD, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_XCOORD));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_YCOORD, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_YCOORD));
contentValues.put(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD20, queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_FIELD20));
String permitId = queryValues.get(PermitDataEntry.COLUMN_NAME_PERMIT_ID);
String columns[] = {PermitDataEntry.COLUMN_NAME_PERMIT_ID};
Cursor cursor = null;
try {
cursor = mDatabase.query(tableName, columns, PermitDataEntry.COLUMN_NAME_PERMIT_ID + "=?", new String[]{permitId}, null, null, null);
}
catch (Exception e) {
Log.e("insertOrUpdatePermit", "exception:cursor: " + tableName + " columns: " + columns);
e.printStackTrace();
}
// if count is 0, then permitId does not exist, so insert
// if count is 1, then permitId does exist, so update
int count = cursor.getCount();
if (count == 0) { // if new row
mDatabase.insert(tableName, null, contentValues);
}
else { // primary key already exists
mDatabase.update(tableName, contentValues, null, null);
}
cursor.close();
}
By default, the boundaries of a SQLite statement (e.g., insert(),update(),execSQL()`) is that individual statement. This means that your code is doing 800 transactions. Each transaction involves disk I/O, to update the database and transaction log. Doing lots of little transactions gets slow.
For bulk data operations, it is better to wrap your own transaction around the work. Partly, that will be for speed. Partly, that way the whole bulk data load will succeed or fail as a whole, so if it fails (e.g., foreign key constraint violation), you do not wind up with a mix of succeeded and failed operations.
The pseudo-Java for this is:
db.beginTransaction();
try {
// do real SQL calls here
db.setTransactionSuccesful();
}
finally {
db.endTransaction();
}
(where db is a SQLiteDatabase, and catch blocks are optional)
Hi i have issue with database SQLITE android
please check my code for reference
when i am going to insert values it returns -1 that i come to know from debug
which is not inserting values so tell me what is wrong
i am inserting value from list view.
public void add_device(String data,
ArrayList<HashMap<String, String>> jsonlist) {
try {
SQLiteDatabase db = this.getReadableDatabase();
// database = this.getWritableDatabase();
for (HashMap<String, String> map : jsonlist) {
ContentValues values = new ContentValues();
values.put(SAVE_COLUMN_NAME, data);
values.put(SAVE_COLUMN_KEY, map.get(SAVE_COLUMN_KEY));
values.put(SAVE_COLUMN_VALUE, map.get(SAVE_COLUMN_VALUE));
#SuppressWarnings("unused")
Long int1 = db.insert(SAVE_TABLE_NAME, null, values);
Log.i("insserted value ", int1 + "");
}
}
/*
* 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); }
*/
catch (Exception e) {
// TODO: handle exception
}
}
thanks in advance
I am guessing that the "-1" value is coming from your Log.i(...) message, so the -1 is the return value of the db.insert(...) call. The -1 indicates an error occurred.
Instead of using insert, user insertOrThrow(...) and look at the exception for clues as to why there is a problem.
-1 is returned when you are inserting the records.
This can be due to violation of table properties (like conflict between type of data you are inserting and the type of column in table ,is "key" and "Value" column in table are of string type) also there can be several other reasons for this like you may be missing any table column value in insert operation or value of 'SAVE_COLUMN_NAME','SAVE_COLUMN_KEY','SAVE_COLUMN_VALUE' doesn't matches with respective column names in table .
[while running app open separate command prompt and write adb logcat ) and show the result here (specifically when you try to insert the record) so that we have more information related to issue]
[EDIT]
OK so i think i have found the problem
SQLiteDatabase db = this.getReadableDatabase();
and you are inserting statement
Long int1 = db.insert(SAVE_TABLE_NAME, null, values);
INSERT SHOULD BE DONE USING WRITABLE DATABASE NOT READABLE DATABASE.
Here SQLiteDatabase db is a Readable Database it should be a Writable database
change
SQLiteDatabase db = this.getReadableDatabase();
to
SQLiteDatabase db = this.getWritableDatabase();
I have made changes like
public void add_device(String data,ArrayList<HashMap<String, String>> jsonlist) {
try {
database = this.getWritableDatabase();
for (HashMap<String, String> map : jsonlist) {
ContentValues values = new ContentValues();
values.put(SAVE_COLUMN_NAME, data);
values.put(SAVE_COLUMN_KEY, map.get(SAVE_COLUMN_KEY));
values.put(SAVE_COLUMN_VALUE, map.get(SAVE_COLUMN_VALUE));
Long int1 = database.insertOrThrow(SAVE_TABLE_NAME, null,
values);
Log.i("insserted value ", int1 + "");
}
}
/*
* 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); }
*/
catch (Exception e) {
}
}