WEBINAR:
On-Demand
Building the Right Environment to Support AI, Machine Learning and Deep Learning
Updating a Title
To update a particular title, call DBAdapter's updateTitle() method by passing the ID of the title you want to update as well as the values of the new fields (Listing 6).
A message is displayed to indicate if the update is successful. At the same time, you retrieve the title that you have just updated to verify that the update is indeed correct.
Deleting a Title
To delete a title, use the deleteTitle()method in the DBAdapter class by passing the ID of the title you want to delete:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);
//---delete a title---
db.open();
if (db.deleteTitle(1))
Toast.makeText(this, "Delete successful.",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Delete failed.",
Toast.LENGTH_LONG).show();
db.close();
}
A message is displayed to indicate if the deletion is successful.
Upgrading the Database
To upgrade the database, change the DATABASE_VERSION constant in the DBAdapter class to a value higher than the previous one. For example, if its previous value was 1, change it to 2:
 |
|
Figure 5. The LogCat Window: The message shows that the database has been upgraded. |
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_ISBN = "isbn";
public static final String KEY_TITLE = "title";
public static final String KEY_PUBLISHER = "publisher";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "books";
private static final String DATABASE_TABLE = "titles";
//---change this to a higher value---
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table titles (_id integer primary key autoincrement, "
+ "isbn text not null, title text not null, "
+ "publisher text not null);";
When you run the application one more time, you will see the message in Eclipse's LogCat window (see Figure 5) indicating that the database has been upgraded.
Easy Database Access
Using the DBAdapter class pattern defined in this article, you can easily access database records for your own Android applications. One important thing to note is that all SQLite databases created in Android are visible only to the application that created it. If you need to share common data, you need to use a content provider, a topic that will be covered in a future article.