Android Notification not inserting into SQLite database - java

I have been debugging this problem for hours and I have looked around and cannot seem to find a solution. When I run the code everything works fine except insertNotification is not inserting a new value into the notification table and no exceptions are thrown. Why is this?
public void updateLaw(int lawID, String newSummary, String newFullText){
int tagID = getTagID(lawID);
String tagName = getTagName(tagID);
int categoryID = getCategoryID(tagID);
String categoryName = getCategoryName(categoryID);
openToWrite();
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_SUMMARY, newSummary);
if(newFullText!=null)
contentValues.put(Constants.KEY_FULL_TEXT, newFullText);
mSqLiteDatabase.update(Constants.TABLE_LAW, contentValues, Constants.KEY_LAW_ID + "=" + lawID, null);
close();
try {
insertNotification(categoryName, tagName + " has changed in " + getLocationName(getLocationID(lawID)));
}
catch(Exception e){
exceptionHandler.alert(e, "UpdateLaw()");
}
}
public void insertNotification(String type, String text){
openToWrite();
try {
mSqLiteDatabase.execSQL("DROP TABLE IF EXISTS notification");
String tableQuery = "CREATE TABLE "+Constants.TABLE_NOTIFICATION+" (\n" +
Constants.KEY_NOTIFICATION_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
Constants.KEY_LAW_ID + " INT,\n" +
Constants.KEY_NOTIFICATION_TEXT + " VARCHAR,\n" +
Constants.KEY_NOTIFICATION_TIME + " DATETIME DEFAULT CURRENT_TIMESTAMP,\n" +
Constants.KEY_NOTIFICATION_STATUS + " VARCHAR\n" +
");\n";
mSqLiteDatabase.execSQL(tableQuery);
}
catch(Exception e){
exceptionHandler.alert(e, "insertNotification()");
}
try {
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_NOTIFICATION_TYPE, type);
contentValues.put(Constants.KEY_NOTIFICATION_TEXT, text);
contentValues.put(Constants.KEY_NOTIFICATION_STATUS, "unread");
mSqLiteDatabase.insert(Constants.TABLE_NOTIFICATION, null, contentValues);
}
catch(Exception e){
exceptionHandler.alert(e, "insertNotification()");
}
close();
}

try close(); and then openToWrite(); before inserting new record.
public void insertNotification(String type, String text){
openToWrite();
try {
mSqLiteDatabase.execSQL("DROP TABLE IF EXISTS notification");
String tableQuery = "CREATE TABLE "+ Constants.TABLE_NOTIFICATION + " ( " +
Constants.KEY_NOTIFICATION_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
Constants.KEY_LAW_ID + " INT, " +
Constants.KEY_NOTIFICATION_TEXT + " VARCHAR, " +
Constants.KEY_NOTIFICATION_TIME + " DATETIME DEFAULT CURRENT_TIMESTAMP, " +
Constants.KEY_NOTIFICATION_STATUS + " VARCHAR " +
")";
mSqLiteDatabase.execSQL(tableQuery);
}
catch(Exception e){
exceptionHandler.alert(e, "insertNotification()");
}
try {
close();
openToWrite();
ContentValues contentValues = new ContentValues();
contentValues.put(Constants.KEY_NOTIFICATION_TYPE, type);
contentValues.put(Constants.KEY_NOTIFICATION_TEXT, text);
contentValues.put(Constants.KEY_NOTIFICATION_STATUS, "unread");
mSqLiteDatabase.insert(Constants.TABLE_NOTIFICATION, null, contentValues);
}
catch(Exception e){
exceptionHandler.alert(e, "insertNotification()");
}
close();
}

Related

android - prevent duplicate insert data in SQLite

I just learned to use sqlite on android. how to prevent duplicate data when it will be inserted .. so, when there is same data entry, it will overwrite the data?
here I attach the code snippet:
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FAVORIT_TABLE = "CREATE TABLE " + Constant.favoritDBtable + "("
+ Constant.id_postFav + " INTEGER PRIMARY KEY AUTOINCREMENT," + Constant.titleFav + " TEXT," + Constant.namaPerusahaanFav + " TEXT,"
+ Constant.lokasiFav + " TEXT," + Constant.kriteria_1Fav + " TEXT," + Constant.kriteria_2Fav
+ " TEXT," + Constant.kriteria_3Fav + " TEXT," + Constant.gajiFav + " TEXT," + Constant.img_logoFav
+ " TEXT," + Constant.tanggalFav + " TEXT);";
public String addFavorit(Favorit favorit){
SQLiteDatabase db = this.getWritableDatabase();
// long rows = 0;
ContentValues values = new ContentValues();
values.put(Constant.titleFav, favorit.getTitleFav());
values.put(Constant.namaPerusahaanFav, favorit.getNamaPerusahaanFav());
values.put(Constant.lokasiFav, favorit.getLokasiFav());
values.put(Constant.kriteria_1Fav, favorit.getKriteria_1Fav());
values.put(Constant.kriteria_2Fav, favorit.getKriteria_2Fav());
values.put(Constant.kriteria_3Fav, favorit.getKriteria_3Fav());
values.put(Constant.gajiFav, favorit.getGajiFav());
values.put(Constant.img_logoFav, favorit.getImg_logoFav());
values.put(Constant.tanggalFav, favorit.getTanggalFav());
db.insert(Constant.favoritDBtable, null, values,);
Log.d("Favorit saved: ", "Success 200 OK");
return null;
}
MainActivity.java
#Override
public void onClick(View v) {
if (job.getTitle() != null && job.getLokasi() != null){
saveToFavoritDB();
}
}
private void saveToFavoritDB() {
Favorit favorit = new Favorit();
favorit.setTitleFav(job.getTitle());
favorit.setGajiFav(job.getGaji());
Log.d(TAG, "gaji " + job.getGaji());
db.addFavorit(favorit);
List<Favorit> favList = db.getAllFavorit();
for (Favorit each : favList) {
String log = "ID: " + each.getTitleFav() + ", Name: " + each.getLokasiFav() + ", Phone: " + each.getGajiFav();
Log.d(TAG, "saveToFavoritDB: " + String.valueOf(db.getCountFavorit()));
Log.d(TAG, "Hasil: " + log);
}
}
hope you can help me
Before go through addFavorit method, you can add one method to check whether the data is already exists to prevent duplicate.
boolean check;
check = checkDuplicate(...,...,...,id_post); // check whether data exists
if(check == true) // if exists
{
Toast.makeText(MainActivity.this, " Data Already Exists", Toast.LENGTH_LONG).show();
}else{
db.addFavorit(favorit);
}
public static boolean checkDuplicate(String TableName,String dbfield, String fieldValue, int id_post) {
String Query = ".... WHERE "+ Constant.id_postFav +"="+ id_post; // your query
Cursor cursor = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
Crate a function to check row is in db or not
private static boolean CheckIsInDBorNot(String titleFav) {
String selectQuery = "SELECT * FROM " + Constant.favoritDBtable + " WHERE " + Constant.titleFav +"'"+titleFav "'";
final SQLiteDatabase db = open();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
than check
if (!CheckIsInDBorNot(commentOrderId, commentId)) {
db.insertOrThrow(Constant.favoritDBtable, null, cVal);
}
It will check and insert
Create method IsItemExist() in your DatabaseHelper class and call this method in you activity class like IsItemExist(name,mobile)
public boolean IsItemExist(String name,String mobile) {
try
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery("SELECT "+NAME+" FROM "+TABLE+" WHERE "+NAME+"=?",new String[]{name});
Cursor cursor1=db.rawQuery("SELECT "+MOBILE+" FROM "+TABLE+" WHERE "+MOBILE+"=?",new String[]{mobile});
if (cursor.moveToFirst() && cursor1.moveToFirst())
{
db.close();
Log.d("Record Already Exists", "Table is:"+TABLE+" ColumnName:"+NAME);
return true;//record Exists
}
Log.d("New Record ", "Table is:"+TABLE+" ColumnName:"+NAME+" Column Value:"+NAME);
db.close();
}
catch(Exception errorException)
{
Log.d("Exception occured", "Exception occured "+errorException);
// db.close();
}
return false;
}

How to update a SQLite database in android?

I am trying to update an SQLite database table with an integer value.I have tried 2 approaches the first one does not update the table and the 2nd one gives an SQLiteException.
1st using the update method:-
public void updateBookQty(String quantity,String bookId)
{
SQLiteDatabase db = this.getWritableDatabase();
int updateQty = getQuantity(bookId) - Integer.parseInt(quantity) ;
ContentValues values = new ContentValues();
values.put(KEY_QTY,updateQty);
try{
db.update(BOOKS_TABLE, values, KEY_BOOK_ID+ " = ?",
new String[] { String.valueOf(bookId) });
Log.d("BookUpdate", String.valueOf(updateQty));
}catch (SQLException e)
{
Log.d("UpdateError",e.toString());
}
}
2nd using execSQL:-
public void updateQty(Integer qty,String bookId)
{
int originalQty = getQuantity(bookId);
int updateQty = originalQty - qty;
try{
SQLiteDatabase db = this.getWritableDatabase();
String rawQuery = "update "+BOOKS_TABLE+" set "+KEY_QTY+" = "+updateQty+ " where "+KEY_BOOK_ID+" = "+bookId+" ;" ;
db.execSQL(rawQuery);
db.close();
Log.v("UpdateQty", "Qty updated");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
Here I get a SQLiteException:-
System.err: android.database.sqlite.SQLiteException: near "0000169":
syntax error (code 1): , while compiling: update books_table set
quantity = -10 where book_id = BK 0000169 ;
try this,
public void updateQty(Integer qty,String bookId)
{
int originalQty = getQuantity(bookId);
int updateQty = originalQty - qty;
try{
SQLiteDatabase db = this.getWritableDatabase();
String rawQuery = "update " + BOOKS_TABLE + " set " + KEY_QTY + " = " + updateQty + " where " + KEY_BOOK_ID + " = '" + bookId + "';";
db.execSQL(rawQuery);
db.close();
Log.v("UpdateQty", "Qty updated");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
As your id is string you must quote the value, esp. It contains space:
String rawQuery = "update "+BOOKS_TABLE
+ " set "+KEY_QTY+" = "+updateQty
+ " where "+KEY_BOOK_ID+" = '"+bookId+"';" ;

How to insert values into a sqlite database using beans and retrieving those table values into json array

Inserting values into table using beans
public static void addGetAssessmentDetail(Context context,
GetAssessmentBean getassessmentDetail) {
DBHelper dbHelper = null;
SQLiteDatabase sqlDBRead = null;
SQLiteDatabase sqlDBWrite = null;
try {
dbHelper = new DBHelper(context, LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
sqlDBRead = dbHelper.getReadableDatabase();
sqlDBWrite = dbHelper.getWritableDatabase();
ContentValues book = new ContentValues();
book.put(TB_FinalAssessmentValues.CL_1_ID, getassessmentDetail.getId());
book.put(TB_FinalAssessmentValues.CL_2_USER_ID , getassessmentDetail.getUser_id());
book.put(TB_FinalAssessmentValues.CL_3_BOOK_ID, getassessmentDetail.getBook_id());
book.put(TB_FinalAssessmentValues.CL_4_CHAPTER_ID,
getassessmentDetail.getChapter_id());
book.put(TB_FinalAssessmentValues.CL_5_QUESTION_TYPE,
getassessmentDetail.getQuestion_type());
book.put(TB_FinalAssessmentValues.CL_6_QUESTION_ID,
getassessmentDetail.getQuestion_id());
book.put(TB_FinalAssessmentValues.CL_7_OPTION_ID,
getassessmentDetail.getOption_id());
book.put(TB_FinalAssessmentValues.CL_8_MARK,
getassessmentDetail.getMark());
book.put(TB_FinalAssessmentValues.CL_9_NOTES,
getassessmentDetail.getNotes());
book.put(TB_FinalAssessmentValues.CL_10_MATCH_OPTION, getassessmentDetail.getMatchOption());
book.put(TB_FinalAssessmentValues.CL_11_DRAG_VALUES,
getassessmentDetail.getDragValues());
book.put(TB_FinalAssessmentValues.CL_12_ADDED_TIME,
getassessmentDetail.getAdded_time());
Log.i("", "assessment values insertion success" );
} catch (Exception e) {
e.printStackTrace();
}
}
And trying to retrieve those table values into JSON array
public JSONArray getFullAssessmentData(Context mContext, String bookid,
int UserId) {
DBHelper dbh = new DBHelper(mContext, LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
SQLiteDatabase db = dbh.getReadableDatabase();
JSONArray resultSet = new JSONArray();
try {
Cursor c = db.rawQuery("SELECT * FROM " + TB_FinalAssessmentValues.NAME
+ " WHERE " + TB_FinalAssessmentValues.CL_3_BOOK_ID+ "='"+ bookid + "'", null);
Log.i("tag", "msg vachindi");
if (c.getCount() > 0) {
c.moveToFirst();
do {
c.moveToFirst();
while (c.isAfterLast() == false) {
int totalColumn = c.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (c.getColumnName(i) != null) {
try {
rowObject.put(c.getColumnName(i),
c.getString(i));
} catch (Exception e) {
}
}
}
resultSet.put(rowObject);
c.moveToNext();
}
c.close();
db.close();
}
while (c.moveToNext());
}
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}
And finally trying to store those values into JSON array
JSONArray fullassessmentjson = rdb.getFullAssessmentData( getContext(), BookId, UserId);
Log.i("Tag123456","Finalcheck"+fullassessmentjson);
DBHelper
db.execSQL("CREATE TABLE IF NOT EXISTS " + TB_FinalAssessmentValues.NAME + "("
+ TB_FinalAssessmentValues.CL_1_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_2_USER_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_3_BOOK_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_4_CHAPTER_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_5_QUESTION_TYPE + " TEXT, "
+ TB_FinalAssessmentValues.CL_6_QUESTION_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_7_OPTION_ID + " TEXT, "
+ TB_FinalAssessmentValues.CL_8_MARK + " TEXT, "
+ TB_FinalAssessmentValues.CL_9_NOTES + " TEXT, "
+ TB_FinalAssessmentValues.CL_10_MATCH_OPTION + " TEXT, "
+ TB_FinalAssessmentValues.CL_11_DRAG_VALUES + " TEXT, "
+ TB_FinalAssessmentValues.CL_12_ADDED_TIME + " TEXT)");
and the error is its showing nothing in the Json array
Seems like you're adding the values to your ContentValues object, but do not perform the actual insert into the database.
(because of this you're basically querying an empty table)
You should call the insert() method of SQLiteDatabase at the end of addGetAssessmentDetail() to insert the data into your table:
sqlDBWrite.insert(TABLE_TO_INSERT, null, book);

SQLite Database Upgrade Condition

I have an android Quote application in which I have used SQLite Database for storing quotes. I have launched the first version of the application with this DatabaseHelper.
public class DataBaseHandler extends SQLiteOpenHelper {
private static String DB_PATH;
private static String DB_NAME = "SuccessQuotes";
private SQLiteDatabase myDataBase;
private static int DATABASE_VERSION = 1;
private final Context myContext;
public DataBaseHandler(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH = context.getDatabasePath(DB_NAME).toString();
Log.e("path", DB_PATH);
}
// ==============================================================================
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
// ==============================================================================
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
// ==============================================================================
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
// ==============================================================================
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
// ==============================================================================
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
// ==============================================================================
#Override
public void onCreate(SQLiteDatabase db) {
}
// ==============================================================================
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
and my Database Activity is :
public class DAO {
// All Static variables
private SQLiteDatabase database;
private DataBaseHandler dbHandler;
private static final String TABLE_QUOTES = "quotes";
private static final String TABLE_AUTHORS = "authors";
private static final String TABLE_SETTINGS = "settings";
// Pages Table Columns names
private static final String QU_ID = "_quid";
private static final String QU_TEXT = "qu_text";
private static final String QU_AUTHOR = "qu_author";
private static final String QU_FAVORITE = "qu_favorite";
private static final String QU_WEB_ID = "qu_web_id";
private static final String AU_ID = "_auid";
private static final String AU_NAME = "au_name";
private static final String AU_PICTURE = "au_picture";
private static final String AU_PICTURE_SDCARD = "au_picture_sdcard";
private static final String AU_WEB_ID = "au_web_id";
// ==============================================================================
public DAO(Context context) {
dbHandler = new DataBaseHandler(context);
try {
dbHandler.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHandler.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// Log.e("path2", context.getDatabasePath("SuccessQuotes").toString());
// open();
}
// ==============================================================================
// Getting All Quotes
public Cursor getQuotes(String start) {
// Select All Query
String limit = "15";
if (start.equals("5000")) {
String query_count = "SELECT COUNT(" + QU_ID + ") AS count FROM "
+ TABLE_QUOTES;
Cursor c_count = database.rawQuery(query_count, null);
c_count.moveToFirst();
Integer count = c_count.getInt(c_count.getColumnIndex("count"));
limit = String.valueOf(count);
}
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
//Log.i("query",query);
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting All Quotes
public Cursor getFavoriteQuotes(String start) {
// Select All Query
String limit = "15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1"+" ORDER BY " + QU_WEB_ID + " DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
//======================================================================
// Getting Fav Quote from ID
public String getFavQuotes(String strkey_id) {
// Select All Query
String fav = "";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_FAVORITE + " = " + "1 AND " + QU_ID + " = " +strkey_id;
Cursor cursor = database.rawQuery(query, null);
if(cursor.getCount() != 0)
{
cursor.moveToFirst();
fav = cursor.getString(cursor.getColumnIndex(QU_FAVORITE));
}
return fav;
}
// ==============================================================================
// Getting All Author Quotes
public Cursor getAuthorQuotes(String authorID,String start) {
// Select All Query
String limit="15";
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_AUTHOR + " = " + authorID + " ORDER BY "+ QU_WEB_ID +" DESC "+ " LIMIT " + start + ", " + limit;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Selected Quote
public Cursor getOneQuote(String quoteID) {
// Select All Query
String query = "SELECT * FROM " + TABLE_QUOTES + " JOIN "
+ TABLE_AUTHORS + " ON " + QU_AUTHOR + " = " + AU_WEB_ID
+ " WHERE " + QU_ID + " = '" + quoteID + "'";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public void addOrRemoveFavorites(String id, String value) {
ContentValues values = new ContentValues();
values.put(QU_FAVORITE, value);
// Update Row
// database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
database.update(TABLE_QUOTES, values, QU_ID + "=?", new String[] { id });
}
// ==============================================================================
// Getting All Authors
public Cursor getAllAuthors() {
// Select All Query
String query = "SELECT *, COUNT(" + QU_AUTHOR + ") AS count FROM "
+ TABLE_AUTHORS + " LEFT JOIN " + TABLE_QUOTES + " ON " + AU_WEB_ID
+ " = " + QU_AUTHOR + " GROUP BY " + AU_NAME ;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
// Getting Quotes Count
public Integer getQuotesCount() {
String query = "SELECT COUNT(" + QU_TEXT + ") AS count FROM "
+ TABLE_QUOTES;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer count = cursor.getInt(cursor.getColumnIndex("count"));
return count;
}
// ==============================================================================
// Getting Quote ID
public Integer getQotdId() {
String query = "SELECT " + QU_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY RANDOM() LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
Integer id = cursor.getInt(cursor.getColumnIndex(QU_ID));
return id;
}
// ==============================================================================
public void updateSetting(String field, String value) {
open();
ContentValues values = new ContentValues();
values.put(field, value);
// Update Row
database.update(TABLE_SETTINGS, values, null, null);
}
// ==============================================================================
public Cursor getSettings() {
open();
String query = "SELECT * FROM " + TABLE_SETTINGS;
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor;
}
// ==============================================================================
public int getLastAuthor() {
String query = "SELECT " + AU_WEB_ID + " FROM " + TABLE_AUTHORS
+ " ORDER BY " + AU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(AU_WEB_ID));
}
// ==============================================================================
public int getLastQuote() {
String query = "SELECT " + QU_WEB_ID + " FROM " + TABLE_QUOTES
+ " ORDER BY " + QU_WEB_ID + " DESC LIMIT 1";
Cursor cursor = database.rawQuery(query, null);
cursor.moveToFirst();
return cursor.getInt(cursor.getColumnIndex(QU_WEB_ID));
}
// ==============================================================================
public void addAuthor(String au_name, String au_picture, int au_web_id) {
open();
ContentValues v = new ContentValues();
v.put(AU_NAME, au_name);
v.put(AU_PICTURE, au_picture);
v.put(AU_PICTURE_SDCARD, 1);
v.put(AU_WEB_ID, au_web_id);
database.insert(TABLE_AUTHORS, null, v);
}
// ==============================================================================
public void addQuote(String qu_text, int qu_author, int qu_web_id) {
open();
ContentValues v = new ContentValues();
v.put(QU_TEXT, qu_text);
v.put(QU_AUTHOR, qu_author);
v.put(QU_FAVORITE, "0");
v.put(QU_WEB_ID, qu_web_id);
database.insert(TABLE_QUOTES, null, v);
}
// ==============================================================================
public void open() throws SQLException {
// database = dbHandler.getReadableDatabase();
database = dbHandler.getWritableDatabase();
}
// ==============================================================================
public void closeDatabase() {
dbHandler.close();
}
Now if I want to update application with more quotes, which changes should I make so that the new and old users don't face any issue ?
I know That Database Version Should Increased, I will it, but What should I put in onUpgrade method ?
I am not expert Android developer, so Please explain me little more if possible, I will very thankful for it.
Thanks
Thanks
Well the Java doc pretty much explains what needs to be done.
From Java doc
Called when the database needs to be upgraded. The implementation
should use this method to drop tables, add tables, or do anything else it
needs to upgrade to the new schema version.
What we do is , alter the tables whenever we have changed the table schema.
In addition you can also perform some data migration if required. Basically its a hook which you got and you can perform any kind of compatibility logic.
cheers,
Saurav

Android: How to change value of sqlite column

I am relatively new to using sqlite in the android world and I currently I my sqlite database set up like the following:
db.execSQL("CREATE TABLES " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCKERNUMBER
+ " TEXT NOT NULL, " + KEY_STATUS + " INTEGER DEFAULT 0, "
+ KEY_PIN + " INTEGER DEFAULT 0);");
And I have the following methods to insert data into the database:
// function to add lockers to database
public long createLockerEntry(String lockerNumber, int status) {
ContentValues cv = new ContentValues();
cv.put(KEY_LOCKERNUMBER, lockerNumber);
cv.put(KEY_STATUS, status);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
// function to create a pin for the locker
public void createPin(String lockerNumber, int pin, int status) {
}
// function to remove pin
public void removePin(String lockerNumber, int pin, int status) {
}
My intentions are to add a pin number for a certain locker number to the KEY_PIN column within the method Create pin and then change the status value to 1. I would assume I would use the where clause statement but I am not completely sure about the syntax or if that is the write approach. Any suggestions?
The method you want is update()
You can read about it by searching for "update" on this page:
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
One way to use this would be:
// function to create a pin for the locker
public void createPin(tring lockerNumber, int pin, int status) {
ContentValues cv = new ContentValues()
cv.put(KEY_PIN, pin);
cv.put(KEY_STATUS, status);
ourDatabase.update(DATABASE_TABLE, cv, KEY_LOCKERNUMBER + " = ?"
, new String[] {lockerNumber});
}
Here's an example where I toggle the value of an entry. It is an int value used as binary (i.e. 1 or 0).
The two methods checkAsWildTest, and uncheckAsWildTest.
public void checkAsWildTest(Cursor c, int val) {
assertDbOpen();
String[] _params = { String.valueOf(c.getInt(ID_COLUMN)) };
//next 4 lines are just for debug
log(".uncheckAsWildTest(), " + "c.getCount() = " + c.getCount());
log("row selected = " + c.getInt(ID_COLUMN));
log("cursor content: " + c.getString(ANSWERS_RESPONSE_COLUMN));
log("cursor columns" + Arrays.toString(c.getColumnNames()));
ContentValues cv = new ContentValues();
cv.put(KEY_ANSWERS_CHECKED, val);
db.update(ANSWERS_TABLE, cv, "_id=?", _params);
}
public void uncheckAsWildTest(Cursor c) {
assertDbOpen();
int unchecked = 0;
String[] _params = { String.valueOf(c.getInt(ID_COLUMN)) };
//next 4 lines are just for debug
log(".uncheckAsWildTest(), " + "c.getCount() = " + c.getCount());
log("column selected = " + c.getInt(ID_COLUMN));
log("cursor content: " + c.getString(ANSWERS_RESPONSE_COLUMN));
log("cursor columns" + Arrays.toString(c.getColumnNames()));
ContentValues cv = new ContentValues();
cv.put(KEY_ANSWERS_CHECKED, unchecked);
db.update(ANSWERS_TABLE, cv, "_id=?", _params);
}
I believe you can work with this, and modify it for your purposes.

Categories