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+"';" ;
Related
I can't understand why is the database either not saving the values I enter or is it the method which I am using to pull all the data not working correctly. It doesn't throw any errors it just doesn't work. Here is the code:
private static final String QUERY_TRIANGLE_CREATE_TABLE =
"CREATE TABLE " + TRIANGLE_TABLE_NAME + " (" + TRIANGLE_COL_ID + " INTEGER PRIMARY KEY, " +
TRIANGLE_VALUE_A + " TEXT, " + TRIANGLE_VALUE_C + "TEXT, " + TRIANGLE_VALUE_B + " TEXT, " + TRIANGLE_RESULT + " TEXT," + TRIANGLE_HISTORY_INFORMATION + " TEXT" + " );";
public void insertTriangleCalc(String a,String b, String c,String d,String e){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TRIANGLE_VALUE_A,a);
values.put(TRIANGLE_VALUE_B,b);
values.put(TRIANGLE_VALUE_C,c);
values.put(TRIANGLE_RESULT,d);
values.put(TRIANGLE_HISTORY_INFORMATION,e);
database.insert("triangle", null, values);
database.close();
}
public void insertTriangleCalc(String a,String b, String c,String d){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TRIANGLE_VALUE_A,a);
values.put(TRIANGLE_VALUE_B,b);
values.put(TRIANGLE_RESULT,c);
values.put(TRIANGLE_HISTORY_INFORMATION,d);
database.insert("triangle", null, values);
database.close();}
public List<Triangle> ObjectRead() {
List<Triangle> valuesList = new ArrayList<>();
String sql = "SELECT * FROM triangle ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
int id = Integer.parseInt(cursor.getString(cursor.getColumnIndex("id")));
String valueA = cursor.getString(cursor.getColumnIndex("valueA"));
String valueB = cursor.getString(cursor.getColumnIndex("valueB"));
String valueC="0";
try {
} catch (Exception e){
}
String result = cursor.getString(cursor.getColumnIndex("result"));
String history = cursor.getString(cursor.getColumnIndex("history"));
Triangle triangle = new Triangle();
triangle.id = id;
triangle.valueA = valueA;
triangle.valueB = valueB;
triangle.valueC = valueC;
triangle.Result = result;
triangle.history = history;
valuesList.add(triangle);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return valuesList;
}
Can anyone have a look at it and help me figure out what am I not setting up properly. It works for public void insertTriangleCalc(String a,String b, String c,String d) , but not for public void insertTriangleCalc(String a,String b, String c,String d,String e).
Decided to check from top to bottom and the whole thing was happening because of a missing empty space TRIANGLE_VALUE_C + "TEXT, "
<- here. This has now been resolved and it can finally store data correctly.
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);
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
I am creating an app to record assignments for different classes. Each class has it's own unique ID so the assignments listed for each class don't overlap into other classes. Here is a method I made to find the rowid for a certain class.
public int getIdFromClassName(String className){
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
return res.getColumnIndex("id");
}
However, this always returns a value of -1.
Any thoughts on what to change to return the proper rowid value?
EDIT:
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table " + CLASSES_TABLE_NAME + " " +
"(id integer primary key, " + CLASSES_COLUMN_NAME + " text)"
);
db.execSQL(
"create table " + ASSIGNMENTS_TABLE_NAME + " " +
"(id integer primary key, " + ASSIGNMENTS_COLUMN_NAME + " text, " + ASSIGNMENTS_COLUMN_TOTAL_POINTS
+ " INTEGER, " + ASSIGNMENTS_COLUMN_CLASS_ID + " INTEGER)");
}
Try this query below to create a new column name rowID:
Cursor cursor= db.rawQuery("SELECT *,"+CLASSES_TABLE_NAME +".rowid AS rowID"+" FROM "+CLASSES_TABLE_NAME , null);
And after this query you can fetch the real rowid from the rowID column :
while (cursor.moveToNext()) {
long chatRow=cursor.getLong(
cursor.getColumnIndexOrThrow("rowID"));
}
The column returned by your query is called rowid, so you will not find a column called id.
Ensure that you use the same column name in the query and in the call to getColumnIndex.
And the index of this column is always zero; you also need to read the actual value from the column:
int colIndex = res.getColumnIndexOrThrow("rowid"); // = 0
if (res.moveToFirst()) {
return res.getInt(colIndex);
} else {
// not found
}
However, Android has an helper function that makes it much easier to read a single value:
public int getIdFromClassName(String className){
String query = "SELECT rowid" +
" FROM " + CLASSES_TABLE_NAME +
" WHERE " + CLASSES_COLUMN_NAME + " = ?;";
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.longForQuery(db, query, new String[]{ className });
}
res.getColumnIndex("id") is going to get you the column index of the column with the name "id". and since you are getting -1, it cant find it.. are you sure your id column is not "_id"?
To get this to work you should do something like this..
res.getLong(res.getColumnIndex("_id"));
Cursor.getColumnIndex()
Cursor.getLong()
(I would recommend you use getLong() rather than getInt() because SQLite database ID's can get larger than int's).
You can try this:
public int getIdFromClassName(String className){
String query = "SELECT id FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
int id=-1;
If(res!=null&&res.moveToFirst())
id=res.getInt(res.getColumnIndex("id"));
return id;
}
public int getIdFromClassName(String className) {
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE "
+ CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
if (res != null) {
if (res.moveToFirst()) {
do {
return Integer.parseInt(res.getString(res.getColumnIndex("id"))); // if your column name is rowid then replace id with rowid
} while (res.moveToNext());
}
} else {
Toast.makeText(context, "cursor is null", Toast.LENGTH_LONG).show();
}
}
Check your Cursor if its null check your Log that your table is created successfully and if its not null make sure your table has column id in it.
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();
}