SQLite Database Upgrade

I have a SQLite database set up from this tutorial, changing it around my own project: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

However, the tutorial doesn't mention how to update the field. I've tried this:

db = new NotesDatabaseHandler(ViewNoteActivity.this);
...
db.updateNote(new Note(identifier, editTextTitle.getText().toString(), editTextContent.getText().toString(), "Updated on: " + printStandardDate()));

      

Although I had no luck .. I launched the application and the note won't update.

Annotation class:

package com.timmo.notes;

class Note {

//private variables
private int _id;
private String _title;
private String _content;
private String _metadata;

// Empty constructor
public Note() {

}

// constructor
public Note(int id, String title, String content, String metadata) {
    this._id = id;
    this._title = title;
    this._content = content;
    this._metadata = metadata;
}

public int getID() {
    return this._id;
}

public void setID(int id) {
    this._id = id;
}

public String getTitle() {
    return this._title;
}

public void setTitle(String title) {
    this._title = title;
}

public String getContent() {
    return this._content;
}

public void setContent(String content) {
    this._content = content;
}

public String getMetadata() {
    return this._metadata;
}

public void setMetadata(String metadata) {
    this._metadata = metadata;
}

}

      

From NotesDatabaseHandler ():

// Updating single note
public int updateNote(Note note) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_TITLE, note.getTitle());
    values.put(KEY_CONTENT, note.getContent());
    values.put(KEY_METADATA, note.getMetadata());

    // updating row
    int ret = db.update(TABLE_NOTES, values, KEY_ID + " = ?",
            new String[]{String.valueOf(note.getID())});
    db.close();
    return ret;
}

      

I used to delete the note and then add it again, but this adds it to the end of the database, not the same position.

So, to the question, how do I properly update one of my notes (contacts) from the method I'm using? Thanks to

Update: I've tried using raw UPDATE:

public void updateNote(Note note) {
    SQLiteDatabase db = this.getWritableDatabase();

    String strSQL = "UPDATE "
            + TABLE_NOTES + " SET "
            + KEY_TITLE + "='" + note.getTitle() + "', "
            + KEY_CONTENT + "='" + note.getContent() + "', "
            + KEY_METADATA + "='" + note.getMetadata() + "'"
            + " WHERE " + KEY_ID + "='" + note.getID() + "'";
    Log.d("SQL: ", strSQL);
    db.execSQL(strSQL);
    db.close();
}

      

And yet nothing happens. My logic outputs:

UPDATE notes SET title='hello', content='there', metadata='Updated on: 09:48 AM - 08 Aug 2015' WHERE id='7'

      

I can't see what's wrong ...

+3


source to share


3 answers


I managed to fix my problems. Kudos to @Tomasz Best for pointers.

Fixed update:

public void updateNote(Note note) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_TITLE, note.getTitle());
    values.put(KEY_CONTENT, note.getContent());
    values.put(KEY_METADATA, note.getMetadata());

    db.update(TABLE_NOTES, values, KEY_ID + " = ?",
            new String[]{String.valueOf(note.getID())});

    db.close();
}

      

Caller operator:



db.updateNote(new Note(identifier, editTextTitle.getText().toString(), editTextContent.getText().toString(), "Updated on: " + printStandardDate()));

      

These issues, along with other fixes, address issues when trying to update RecyclerView items, which I ended up fixing or creating workarounds. The app is working flawlessly now and I've posted an update for the store: https://play.google.com/store/apps/details?id=com.timmo.notes

I have to post the source to github shortly and add a link to the description.

Thanks again to everyone who helped!

0


source


What do you want to update? To update you need to pass a valid (= existing) row id (primary key)

  • read (get id)
  • change
  • update (with old id)

Keep in mind

in conflict

You can also try using raw:

String strSQL = "UPDATE myTable SET Column1 = someValue WHERE columnId = "+ someValue;
myDataBase.execSQL(strSQL);

      

Or try:



String where = "_id=" + note.getId(); 
myDataBase.update(table,cv,where,null) ;

      

I've tried raw, but nothing really happens ... "UPDATE notes SET title = 'hello fgwejfneqdfjoe', content = 'there', metadata = 'Updated: 06:48 AM - 08 Aug 2015' WHERE id =" 7 "which look like they need to be updated.

get rid of Apostrophe from your sql statement

If you are using SQL strings in your database operations, chances are you are facing a problem with strings in the SQL statement. A single apostrophe twists the SQL string, causing an SQL error.

Building an SQL statement by concatenating strings is not recommended. It:

  • unscalable - the database will be "hard-parsed" for each SQL execution -
  • error prone for every name, such as O'Connor (or similar last name), possessive or shorthand.
  • vulnerable to SQL injection by the user if the values โ€‹โ€‹of the input parameters are used as-is.

How do I avoid single quotes in SQL queries?

+2


source


s the update method can only be called if you execute the selection before updating the value, something like this I think:

    @Override
    public void onCreate (Bundle savedInstanceState)
    {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.main);

        DatabaseHandler db = new DatabaseHandler (this);

        / **
         * CRUD Operations
         * * /
        // Inserting Contacts
        Log.d ("Insert:", "Inserting .."); 
        db.addContact (new Contact ("Ravi", "9100000000"));        
        db.addContact (new Contact ("Srinivas", "9199999999"));
        db.addContact (new Contact ("Tommy", "9522222222"));
        db.addContact (new Contact ("Karthik", "9533333333"));

        // Reading all contacts
        Log.d ("Reading:", "Reading all contacts .."); 
        List contacts = db.getAllContacts ();       

        for (Contact cn: contacts)
        {
            Log.d ("TEST", "Id:" + cn.getID () + ", Name:" + cn.getName () + ", Phone:" + cn.getPhoneNumber ());

            if ("Tommy" .equals (cn.getName ())
            {
                cn.setName ("Timmo");
                db.updateContact (cn); // like your updateNote
            }
        }

        Log.d ("Reading:", "Reeeeload all contacts .."); 
        contacts = db.getAllContacts ();       

        for (Contact cn: contacts)
        {
            if ("Timmo" .equals (cn.getName ())
            {
                Log.d ("TEST", "Hello Timmo");
            }
        }   
    }
0


source







All Articles