samedi 29 août 2015

QT: Database is locked Unable to fetch row - sqlite error 5

I'm working on a software that has different threads. Each threads opens its own connection to a SQLITE 3 database.

After using the software for a while, sometimes after 3 minutes, 5 minutes, and sometimes after much more I get the error:

"Database is locked Unable to fetch row" - SQLite error 5

and the queries aren't executed.

What's happening? Do I have to check something programatically in order to see if the database is busy and wait? Shouldn't this be done automatically by the library internally?

Calling a method in another class

I am calling a method in another class, after the insertion of data. But this returning an error SQLite :

    QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.

Source:

insert_sales.cpp

void DialogSales::insert_sale(){
     //QSqlQuery 
     if (qry.lastInsertId()>0){
            QMessageBox::information(this,"Register", "Registered successfully.");
            MainSystem *ms= new MainSystem(this);
            ms->tableView_listSales();
     }
}

MainSystem.cpp

     MainSystem::MainSystem(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainSystem){

        base = new connection(NAME_BASE);
        if(!base->openBD()){
           QMessageBox::critical(this, "Erro", ERRO_BASE);
           return;
         }
     }

    void MainSystem::tableView_listSales(){
        model = new QSqlQueryModel;
        model->setQuery("SELEC * FROM inventory WHERE strftime('%Y-%m-%d', inventory_date)='"+dateTime.toString("yyyy-MM-dd")+"'");
        model->setHeaderData(0, Qt::Horizontal, tr("Client"));
        model->setHeaderData(1, Qt::Horizontal, tr("Address"));
        model->setHeaderData(3, Qt::Horizontal, tr("Payment"));
        model->setHeaderData(6, Qt::Horizontal, tr("Date"));
        ui->tableView_sales->setModel(model);
    }

execute multiple query in sqlite database and android application

I use this code in onCreate method for create database manualy.But only first line (CREATE TABLE if not exists [tbl_collection]) executed.I execute all query in sqlite expert program and No problem.Please help

    public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE  if not exists [tbl_collection] (  [id]    integer PRIMARY KEY AUTOINCREMENT NOT NULL, [name_collection]   nvarchar(256) NOT NULL COLLATE NOCASE);");
    db.execSQL("CREATE TRIGGER if not exists [fkd_tbl_Subject_id_collection_tbl_collection_id] Before Delete ON [tbl_collection] BEGIN SELECT RAISE(ROLLBACK, 'delete on table tbl_collection violates foreign key constraint fkd_tbl_Subject_id_collection_tbl_collection_id') WHERE (SELECT id_collection FROM tbl_Subject WHERE id_collection = OLD.id) IS NOT NULL;  END;");
    db.execSQL("CREATE TABLE   if not exists [tbl_Subject] (    [id]    integer PRIMARY KEY AUTOINCREMENT NOT NULL, [id_collection] integer NOT NULL,   [name_subject]  nvarchar(256) NOT NULL COLLATE NOCASE,    FOREIGN KEY ([id_collection])        REFERENCES [tbl_collection]([id]));");
    db.execSQL("CREATE TRIGGER if not exists [fki_tbl_Subject_id_collection_tbl_collection_id] Before Insert ON [tbl_Subject] BEGIN SELECT RAISE(ROLLBACK, 'insert on table tbl_Subject violates foreign key constraint fki_tbl_Subject_id_collection_tbl_collection_id') WHERE (SELECT id FROM tbl_collection WHERE id = NEW.id_collection) IS NULL;  END;");
    db.execSQL("CREATE TRIGGER if not exists [fku_tbl_Subject_id_collection_tbl_collection_id] Before Update ON [tbl_Subject] BEGIN SELECT RAISE(ROLLBACK, 'update on table tbl_Subject violates foreign key constraint fku_tbl_Subject_id_collection_tbl_collection_id') WHERE (SELECT id FROM tbl_collection WHERE id = NEW.id_collection) IS NULL;  END;");
    db.execSQL("CREATE TRIGGER if not exists [fkd_tbl_Subject_Property_id_subject_tbl_Subject_id] Before Delete ON [tbl_Subject] BEGIN SELECT RAISE(ROLLBACK, 'delete on table tbl_Subject violates foreign key constraint fkd_tbl_Subject_Property_id_subject_tbl_Subject_id') WHERE (SELECT id_subject FROM tbl_Subject_Property WHERE id_subject = OLD.id) IS NOT NULL;  END;");
    db.execSQL("CREATE TABLE   if not exists [tbl_Subject_Property] (   [id]    integer PRIMARY KEY AUTOINCREMENT NOT NULL, [id_subject]    integer NOT NULL,   [text]  nvarchar(512) COLLATE NOCASE,   [picture]   nvarchar(512) COLLATE NOCASE,   [voice] nvarchar(512) COLLATE NOCASE,   [video] nvarchar(512) COLLATE NOCASE,    FOREIGN KEY ([id_subject])        REFERENCES [tbl_Subject]([id]));");
    db.execSQL("CREATE TRIGGER if not exists [fki_tbl_Subject_Property_id_subject_tbl_Subject_id] Before Insert ON [tbl_Subject_Property] BEGIN SELECT RAISE(ROLLBACK, 'insert on table tbl_Subject_Property violates foreign key constraint fki_tbl_Subject_Property_id_subject_tbl_Subject_id') WHERE (SELECT id FROM tbl_Subject WHERE id = NEW.id_subject) IS NULL;  END;");
    db.execSQL("CREATE TRIGGER if not exists [fku_tbl_Subject_Property_id_subject_tbl_Subject_id] Before Update ON [tbl_Subject_Property] BEGIN SELECT RAISE(ROLLBACK, 'update on table tbl_Subject_Property violates foreign key constraint fku_tbl_Subject_Property_id_subject_tbl_Subject_id') WHERE (SELECT id FROM tbl_Subject WHERE id = NEW.id_subject) IS NULL;  END;");

}

Load sqlite database from http

Hi, guys, I want to change the method how my application get the entries of database directly from a specific HTTP website (like: http://ift.tt/1hncDBV) instead of RAW folder (definitions.txt)

Can anyone show me how to do this?

This is the excerpt of the code (DictionaryDatabase.java)

private void loadWords() throws IOException {
        Log.d(TAG, "Loading words...");
        final Resources resources = mHelperContext.getResources();
        InputStream inputStream = resources.openRawResource(R.raw.definitions);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        try {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strings = TextUtils.split(line, "//");
                if (strings.length < 2) continue;
                long id = addWord(strings[0].trim(), strings[1].trim());
                if (id < 0) {
                    Log.e(TAG, "unable to add word: " + strings[0].trim());
                }
            }
        } finally {
            reader.close();
        }
        Log.d(TAG, "DONE loading words.");
       }

DictionaryDatabase.Java

public class DictionaryDatabase {
private static final String TAG = "DictionaryDatabase";

public static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;
public static final String KEY_DEFINITION = SearchManager.SUGGEST_COLUMN_TEXT_2;

private static final String DATABASE_NAME = "dictionary";
private static final String FTS_VIRTUAL_TABLE = "FTSdictionary";
private static final int DATABASE_VERSION = 2;

private final DictionaryOpenHelper mDatabaseOpenHelper;
private static final HashMap<String,String> mColumnMap = buildColumnMap();

public DictionaryDatabase(Context context) {
    mDatabaseOpenHelper = new DictionaryOpenHelper(context);
}

private static HashMap<String,String> buildColumnMap() {
    HashMap<String,String> map = new HashMap<String,String>();
    map.put(KEY_WORD, KEY_WORD);
    map.put(KEY_DEFINITION, KEY_DEFINITION);
    map.put(BaseColumns._ID, "rowid AS " +
            BaseColumns._ID);
    map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " +
            SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
    map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " +
            SearchManager.SUGGEST_COLUMN_SHORTCUT_ID);
    return map;
}

public Cursor getWord(String rowId, String[] columns) {
    String selection = "rowid = ?";
    String[] selectionArgs = new String[] {rowId};

    return query(selection, selectionArgs, columns);

}

public Cursor getWordMatches(String query, String[] columns) {
    String selection = KEY_WORD + " MATCH ?";
    String[] selectionArgs = new String[] {query+"*"};

    return query(selection, selectionArgs, columns);

}

private Cursor query(String selection, String[] selectionArgs, String[] columns) {

    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    builder.setTables(FTS_VIRTUAL_TABLE);
    builder.setProjectionMap(mColumnMap);

    Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
            columns, selection, selectionArgs, null, null, null);

    if (cursor == null) {
        return null;
    } else if (!cursor.moveToFirst()) {
        cursor.close();
        return null;
    }
    return cursor;
}

private static class DictionaryOpenHelper extends SQLiteOpenHelper {

    private final Context mHelperContext;
    private SQLiteDatabase mDatabase;

    private static final String FTS_TABLE_CREATE =
                "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
                " USING fts3 (" +
                KEY_WORD + ", " +
                KEY_DEFINITION + ");";

    DictionaryOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mHelperContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        mDatabase = db;
        mDatabase.execSQL(FTS_TABLE_CREATE);
        loadDictionary();
    }

    private void loadDictionary() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    loadWords();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    private void loadWords() throws IOException {
        Log.d(TAG, "Loading words...");
        final Resources resources = mHelperContext.getResources();
        InputStream inputStream = resources.openRawResource(R.raw.definitions);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        try {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strings = TextUtils.split(line, "//");
                if (strings.length < 2) continue;
                long id = addWord(strings[0].trim(), strings[1].trim());
                if (id < 0) {
                    Log.e(TAG, "unable to add word: " + strings[0].trim());
                }
            }
        } finally {
            reader.close();
        }
        Log.d(TAG, "DONE loading words.");
    }


    public long addWord(String word, String definition) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_WORD, word);
        initialValues.put(KEY_DEFINITION, definition);

        return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
        onCreate(db);
    }
}

}

call information from database SQLite and show TextView

I'm trying call information from database to show on textview, like profile, calling name,email,...

this is my code:

public class ProfileActivity extends AppCompatActivity {
ImageButton ibt;
Button bt2;
private AlphaAnimation buttonClick = new AlphaAnimation(0.0F, 0.8F);
SQLiteDatabase db;
DatabaseHelper helper = new DatabaseHelper(this);
TextView tvname,tvemail;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    ibt = (ImageButton) findViewById(R.id.imageButton3);
    bt2 = (Button) findViewById(R.id.imageButton15);


    tvname=(TextView)findViewById(R.id.TVname);
    tvemail=(TextView)findViewById(R.id.TVemail);


 // NOW HOW I GET INFORMATION FROM DB AND SHOW AT TVname and TVemail ???
}

Save form serialize data to the Sqlite database javascript

am trying to save the serialized data of a html input and select which is created dynamically i have no idea how to save this using javascript to a sqlite table,Example i have 4 cells in a row 1 cells has a textbox ,the second has a dropdown,third has a textbox and forth too
but on dropdown change the first and the second (third cell) textbox value are automatically filled and after i enter the forth a new row is created and goes so on

My problem is that i want save the data in a sqlite using javascript or jquery as soon as a the save button is clicked the form's input and the selected value should be saved in the sqlite database

Say in my example :

i have four rows entered the data then on click of save the save should ignore the fifth as it has no value

User view Row(s)

  1. first cell second cell(dd) third cell fourth cell
  2. first cell second cell(dd) third cell fourth cell
  3. first cell second cell(dd) third cell fourth cell
  4. first cell second cell(dd) third cell fourth cell
  5. this row should be ignored

save the same data in the sqlite database as rows one below another

Demo JSfiddle

JS:

$('#results').append('<form id=savealldata><table width="100%" border="1" cellspacing="0" cellpadding="5" id="productanddates" class="border"> <tr><td> <input type="text" name="to1" id="to1" value="" /> </td> <td> <select class="dd" name="Phonenumberdd1" id="Phonenumberdd1"> <option value="test">test </option><option value="test2">test 2</option></select></td> <td>   <input type="text" name="renewal_by1" id="renewal_by1" />  </td>   <td> <input type="text" name="Renivaul_to1" id="Renivaul_to1" value="" /> </td></TR></TABLE></form>'
);

    $('#results').on('focus', ':input', function() {
        $(this).closest('tr').filter(function() { 
            return !$(this).data('saved'); 
        })
        .find(':input').each(function() {
            $(this).data('value', this.value);
            $(this).closest('tr').data('saved', true);
        });
    })
    .on('input change', ':input', function() {
        $(this).data('filled', this.value != $(this).data('value'))
        var tr  = $(this).closest('tr');
            all = tr.find(':input'),
            fld = all.filter(function() {
                return $(this).data('filled');
            });
        if( all.length == fld.length ) {
            if( !tr.data('done') ) {
                $('#buttonclck')[0].click();
                tr.data('done', true);
            }
        } else {
            if( tr.data('done') ) {
                tr.next('tr').remove();
                tr.data('done', false);
            }
        }
    });

    $('#buttonclck').on('click', function () {
        var lastRow = $('#productanddates').closest('#productanddates').find("tr:last-child");

        var cloned = lastRow.clone();
        cloned.find('input, select').each(function () {
            var id = $(this).attr('id');

            var regIdMatch = /^(.+)(\d+)$/;
            var aIdParts = id.match(regIdMatch);
            var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);

            $(this).attr('id', newId);
            $(this).attr('name', newId);
        });

        cloned.find("input[type='text']").val('');
        cloned.insertAfter(lastRow);
    });


$('#productanddates tr').on('change','.dd', function(e) {
    var data ="dummy data";
    $(this).closest('td').prev().find('input').val(data).trigger('input');
    $(this).closest('td').next().find('input').val(data).trigger('input');
});

HTML:

<div id="results"></div>

<input id="buttonclck" type="button" class="hide" value="button"/>

<button id="save">save</button>

How to insert new artist into android audio database?

I want to implement a feature, which will allow user to edit artist names of local songs in standard database. That's why I need to insert new artist names to database.

I've tried this code

@Override
    protected void addArtistToDatabase(Artist artist) {
        Uri uri = MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI;
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Artists.ARTIST, artist.getName());
        uri = contentResolver.insert(uri, values);
        long id = Strings.getLongFromString(uri.toString());
        artist.setId(id);
    }

But it throws java.lang.UnsupportedOperationException: Invalid URI content://media/external/audio/artists

But when I tried to add playlists the same way everything works as expected.