Android copy values from table and insert in another - android

I'm trying to copy all the data in a database table, which correspond to the WHERE clause, and insert them into another table. I'm trying this code, but in the table prev there are only 2 records in the table Ver are inserted more than 100 records .... why?
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
String sql = "SELECT data, unita_di_misura FROM prev WHERE numero ='"+numero_ricevuto+"'";
Cursor c = db.rawQuery(sql, null);
int count = c.getCount();
String[] data = new String[count];
String[] unita_di_misura = new String[count];
for(int i=0; i<count; i++) {
c.moveToNext();
data[i] = c.getString(0);
unita_di_misura[i] = c.getString(1);
}
for(int i=0 ;i < data.length;i++){
ContentValues cv = new ContentValues();
cv.put(VerTable.SI_NO, "0");
cv.put(VerTable .DATA, data[i]);
cv.put(VerTable .U_M, e.unita_di_misura[i]);
db.insert(VerTable .TABLE_NAME, null, cv);
}
c.close();
db.close();
}

Try this 3 line solution hope this will help you
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
String sql = "INSERT INTO "+VerTable .TABLE_NAME+" SELECT 0,data, unita_di_misura FROM prev WHERE numero = '"+numero_ricevuto+"'";
db.execSQL(sql);
db.close();
}

but in the table prev there are only 2 records in the table Ver are inserted more than 100 records .... why?
Possibly you ran the code more than once.
Also, pulling data from db only to insert it back is not very efficient. It's better to let the database engine do the work for you, e.g.
db.execSQL("INSERT INTO " + VerTable.TABLE_NAME +
"(" + VerTable.SI_NO + "," VerTable.DATA + "," + VerTable.U_M + ") " +
"SELECT 0, data, unita_di_misura FROM prev WHERE numero=?",
new String[] { numero_ricevuto });
Using ? params also avoids the possiblity of string SQL injection.

Related

Android SQLiteStatement Insert, nothing happen

i have some data from SoapObject, i want insert to sqlite, for better performance, i use the following code :
public void testInsert(String sql, SoapObject rs, int index) {
try {
sql = "INSERT INTO NSPMasterHarga (KdBarang, Wilayah, HargaJual1, HargaJual2) VALUES (?, ?, ?, ?)";
theDatabase = getWritableDatabase();
theDatabase.beginTransaction();
String drop = "DROP TABLE IF EXISTS NSPMasterHarga";
SQLiteStatement stmtDrop = theDatabase.compileStatement(drop);
stmtDrop.execute();
String create = "CREATE TABLE NSPMasterHarga (KdBarang TEXT PRIMARY KEY, Wilayah TEXT, HargaJual1 TEXT, HargaJual2 TEXT)";
SQLiteStatement stmtCreate = theDatabase.compileStatement(create);
stmtCreate.execute();
SQLiteStatement stmt = theDatabase.compileStatement(sql);
int count = rs.getPropertyCount();
for (int i = 0; i < count; i++) {
SoapObject row = (SoapObject) rs.getProperty(i);
for (int j = 1; j <= index; j++) {
stmt.bindString(j, row.getProperty(j - 1).toString().replace("anyType{}", ""));
}
long entryID = stmt.executeInsert();
stmt.clearBindings();
}
/*for (int i = 0; i < NUMBER_OF_ROWS; i++) {
//generate some values
stmt.bindString(1, randomName);
stmt.bindString(2, randomDescription);
stmt.bindDouble(3, randomPrice);
stmt.bindLong(4, randomNumber);
long entryID = stmt.executeInsert();
stmt.clearBindings();
}*/
theDatabase.setTransactionSuccessful();
theDatabase.endTransaction();
theDatabase.close();
}
catch (Exception ex)
{
String err = ex.getMessage();
}
}
When debug, i've got nothing error, but the data not insert to my sqlite.
Any idea or clue ?
Thanks
for better performance
I'm not so sure which part of the code you are referring to. Opening and closing the database after each interaction is terrible for performance. The SQLiteOpenHelper takes care of all this, so you don't need to do anything manually.
Try the following alternative to insert an entry:
public boolean addEntry(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("column1", "value1"); // make sure the type corresponds to your sql column type
values.put("column2", "value2");
values.put("column3", "value3");
values.put("column4Int", 1);
long newRowId = db.insert(TABLE_NAME, null, values);
Log.d("DBHelper", "Added row " + newRowId + " to DB.");
return newRowId != -1; // -1 means it failed
}

Checking if a record already exists in database, if no insert else increment the count field

I created a sqlite database to store the songs which are most played by the user. Basically, I'm creating "Most played songs" playlist for my music app. The logic I'm using is, when the user selects a song, it is send to the database. If is already there in the database, an integer field will increment its value else the song will be added to database. And I display the result according to the integer field(song with most integer value will be displayed on the top).But my app does't do the sorting according to the integer value. I don't know what is wrong.
Code to add songs:
public void addSong(SongInfoModel songInfoModel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, songInfoModel.getSongID());
values.put(KEY_NAME, songInfoModel.getSongName());
values.put(KEY_ARTIST, songInfoModel.getArtistName());
values.put(KEY_DURATION, songInfoModel.getDuration());
values.put(KEY_LAST_PLAYED, getDateTime());
values.put(KEY_ART, songInfoModel.getAlbumIDArtwork());
if(!CheckIsDataAlreadyInDBorNot(songInfoModel)) {
values.put(KEY_MOST_PLAYED, count);
Log.i("Doesn't Exists:", String.valueOf(count));
}
else {
values.put(KEY_MOST_PLAYED, count++);
Log.i("Exists:", String.valueOf(count));
}
db.insert(TABLE_NAME,null,values);
db.close();
Log.i("Time song was clicked:", getDateTime());
Code to check if song already exists:
public boolean CheckIsDataAlreadyInDBorNot(SongInfoModel songInfoModel) {
SQLiteDatabase db = this.getWritableDatabase();
String Query = "Select * from " + TABLE_NAME + " where " + KEY_ID + " = " + songInfoModel.getSongID();
Cursor cursor = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
Code to display the array of songs:
public ArrayList<SongInfoModel> getMostPlayed(){
ArrayList<SongInfoModel> mpList = new ArrayList<>();
String query = "SELECT * FROM " + TABLE_NAME + " ORDER BY " + KEY_MOST_PLAYED + " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
long id = cursor.getLong(0);
String SongName = cursor.getString(1);
String artistName = cursor.getString(2);
long dur = cursor.getLong(3);
String Art = cursor.getString(5);
SongInfoModel sh = new SongInfoModel(id,SongName,artistName,dur,null,Art);
mpList.add(sh);
}while (cursor.moveToNext());
}cursor.close();
return mpList;
Change to boolean CheckIsDataAlreadyInDBorNot to int CheckIsDataAlreadyInDBorNot,
public int CheckIsDataAlreadyInDBorNot(SongInfoModel songInfoModel) {
int mostPlayed=-1;
SQLiteDatabase db = this.getWritableDatabase();
String Query = "Select KEY_MOST_PLAYED from " + TABLE_NAME + " where " + KEY_ID + " = " + songInfoModel.getSongID();
Cursor cursor = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return -1;
}else {
if(cursor.moveToFirst()){
mostPlayed = cursor.getInt(....)
}
}
cursor.close();
return mostPlayed;
}
then use
count = CheckIsDataAlreadyInDBorNot(songInfoModel)+1;
//add count to SongInfoModel
values.put(KEY_MOST_PLAYED, count);
db.insert(TABLE_NAME,null,values);
db.close();
If I understand correctly, if the song doesn't exist you want to add it, if the song does exist then you want to increment the count of how many times the song has been played within the song.
In SQLite terms new song = INSERT, change song (count) = UPDATE.
You appear to only attempt to INSERT, which would either add another row for the song or not add one due to the KEY_ID already existing (or other constraints). Which, depends upon how the KEY_ID column has been defined. I suspect the latter which would explain the sort not working as expected due to the count never being increased.
Additionally count++ (post increment) increments the value AFTER the value has been applied. So that to would have resulted in the count not being incremented even though the message in the log would indicate that it has been incremented. ++count (pre increment) increments the value BEFORE it is applied, so this has been used.
As such I believe that you need something along the lines of :-
public void addSong(SongInfoModel songInfoModel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if(!CheckIsDataAlreadyInDBorNot(songInfoModel)) {
values.put(KEY_ID, songInfoModel.getSongID());
values.put(KEY_NAME, songInfoModel.getSongName());
values.put(KEY_ARTIST, songInfoModel.getArtistName());
values.put(KEY_DURATION, songInfoModel.getDuration());
values.put(KEY_LAST_PLAYED, getDateTime());
values.put(KEY_ART, songInfoModel.getAlbumIDArtwork());
values.put(KEY_MOST_PLAYED, count);
Log.i("Doesn't Exists:", String.valueOf(count));
db.insert(TABLE_NAME,null,values);
}
else {
values.put(KEY_MOST_PLAYED, ++count);
db.update(TABLE_NAME,values,
KEY_ID + "=?,
new String[]{songInfoModel.getSongID()}
);
Log.i("Exists:", String.valueOf(count));
}
db.close();
Log.i("Time song was clicked:", getDateTime());
}
Notes
- The code hasn't been checked so it may contain errors.

Android SQLite incrementing a column value

I'm trying to create a score database that increments the players 'score' by one when they win by calling updateScore(). The primary key and player number are identical (I may need to restructure the DB at some point) and the final column is 'score'.
Below is the code that initially sets the score (this works), the method that gets the score (also works fine) and the method that updates the score, incrementing the relevant players score by 1. This is the part the doesn't work, is there something I should be doing differently here? Thanks.
/** Add a record to the database of two player scores
* #param playerId
* #param playerScore
**/
public void addScore (int playerId, int playerScore) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, playerId);
values.put(PLAYERNUM, playerId);
values.put(SCORE, playerScore);
database.insert(TABLE_2PSCORES, null, values);
database.close();
}
// Get the score
public int getScore (int playerId) {
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.query(TABLE_2PSCORES, COLUMNS, " player = ?", new String[] {String.valueOf(playerId) }, null, null, null, null); //null = groupby, having, orderby, limit
if (cursor !=null) { cursor.moveToFirst(); }
int output = cursor.getInt(2);
return output;
}
// Increment score by 1
public void updateScore (int playerId) {
SQLiteDatabase database = this.getWritableDatabase();
int playerScore = getScore(playerId);
int playerScoreInc = playerScore ++;
ContentValues values = new ContentValues();
values.put("score", playerScoreInc);
database.update(TABLE_2PSCORES, values, PLAYERNUM+" = ?", new String[] {String.valueOf(playerId)} );
database.close();
}
int playerScoreInc = playerScore ++;
This assigns playerScore to playerScoreInc and only after that increments playerScore. To first increment and then assign, change to ++playerScore.
However, you can do it all in SQL, no need to fetch score, increment it in code and then update the database table separately:
database.execSQL("UPDATE " + TABLE_2PSCORES + " SET " + SCORE + "=" + SCORE + "+1" + " WHERE " + PLAYERNUM + "=?",
new String[] { String.valueOf(playerId) } );
The other answers solve the original question, but the syntax makes it hard to understand. This is a more general answer for future viewers.
How to increment a SQLite column value
SQLite
The general SQLite syntax is
UPDATE {Table} SET {Column} = {Column} + {Value} WHERE {Condition}
An example of this is
UPDATE Products SET Price = Price + 1 WHERE ProductID = 50
(Credits to this answer)
Android
Now that the general syntax is clear, let me translate that into Android syntax.
private static final String PRODUCTS_TABLE = "Products";
private static final String ID = "ProductID";
private static final String PRICE = "Price";
String valueToIncrementBy = "1";
String productId = "50";
String[] bindingArgs = new String[]{ valueToIncrementBy, productId };
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("UPDATE " + PRODUCTS_TABLE +
" SET " + PRICE + " = " + PRICE + " + ?" +
" WHERE " + ID + " = ?",
bindingArgs);
db.close();
TODO
This answer should be updated to use update rather than execSQL. See comment below.
Change
int playerScoreInc = playerScore ++;
to
int playerScoreInc = ++ playerScore;
I think this will work
// Increment score by 1
public void updateScore (int playerId) {
SQLiteDatabase database = this.getWritableDatabase();
int playerScore = getScore(playerId);
int playerScoreInc = ++ playerScore;
ContentValues values = new ContentValues();
values.put("score", playerScoreInc);
database.update(TABLE_2PSCORES, values, PLAYERNUM+" = ?", new String[] {String.valueOf(playerId)} );
database.close();
}
Have you tried debugging? Try debugging this line:
int playerScoreInc = playerScore ++;
The playerScoreInc doesn't increment.

Android create Insert statement at runtime

I have fileds list & values list.I want to insert records using DBAdapter.I tried from this link http://mfarhan133.wordpress.com/2010/10/24/database-crud-tutorial-for-android/
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(Insert.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
initialValues.put("name", etName.getText().toString());
initialValues.put("age", etAge.getText().toString());
long n = dbAdapter.insertRecordsInDB("user", null, initialValues);
Toast.makeText(Insert.this, "new row inserted with id = " + n, Toast.LENGTH_SHORT).show();
Please anybody help me how to send the fields & their values at runtime.Please help me as soon as possible
You can make fields as String array & their value also make array.For example:
String[] strToFields = new String[names.length()];
String[] strToFieldsVal = new String[names.length()];
for (int k = 0; k < names.length(); k++) {
strToFields[k] = names.getString(k);
strToFieldsVal[k]=strVal;
}
calling method like
insertTableRecords(actualtable, strToFields, strToFieldsVal);
method should be:
public void insertTableRecords(String strTableName, String[] strToFields, String[] strValues){
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(DownlaodTableActivity.this);
dbAdapter.openDataBase();
ContentValues initialValues = new ContentValues();
for(int i=0 ;i<strToFields.length;i++){
initialValues.put(strToFields[i],strValues[i]);
}
long n = dbAdapter.insertRecordsInDB(strTableName, null, initialValues);
System.out.println( " -- inserted status : --- " + n);
}
If you need more help see this Android sqlite dynamic insert query

sql lite, android - copy record into the same table

I am trying to copy a record from a sql lite database within a android application and then insert that same record into the same table but with two different ids in the first two columns. any ideas?
SQLiteDatabase db = dbs.getReadableDatabase();
String SQL = "SELECT * FROM table_1 a " +
"join table_2 b on a.ID = b.ID " +
"where table1_Id = '"+Id+"' And" +
"table_2_ID = 'one'";
Cursor cursor2 = db.rawQuery(SQL, null);
startManagingCursor(cursor2);
int m = cursor2.getColumnCount();
try{
while (cursor2.moveToNext()) {
for(int i=0; i<m; i++){
String id1 = cursor2.getString(i);
}
}
}
catch(Exception e){}
try {
while (cursor2.moveToNext()) {
dbs.ad(Id, Id, cursor2.getString(3), "",
cursor2.getString(5), cursor2.getString(6), cursor2.getString(7),
"", "");
}
}

Categories

Resources