How to get dates from database and check if they overlaps? - java

I have a sqlite database in which I store all events. I store StartTime and EndTime against each events in date format.
I have fragments for days with tabs and one activity which adds events. Events are shown in another fragments.
Now I want to check if events do overlap with each other and based on which app should display a message.
How to display message in added event activity when the user saves events.
How can I do this?
I have tried this way but still events get added with same start time and end time:
ImageButton imageButton = (ImageButton)findViewById(R.id.imgbtn_fab);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
eventTitle = title.getText().toString();
EventTableHelper db = new EventTableHelper(getApplication());
List<EventData> events;
events = db.getAllEvents();
for (EventData eventData : events) {
String datefrom = eventData.getFromDate();
String[] times = datefrom.substring(11, 16).split(":");
minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
String dateTo = eventData.getToDate();
//times = dateTo.substring(11,16).split(":");
String[] times1 = dateTo.substring(11, 16).split(":");
minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
}
if (eventTitle.length() == 0) {
Toast.makeText(getApplicationContext(), "Title can not be empty.", Toast.LENGTH_LONG).show();
}
else if(minutesFrom == minutesTo) {
Toast.makeText(getApplicationContext(),"Event with same time exists.",Toast.LENGTH_LONG).show();
}
else
{
db.addEvent(new EventData(eventTitle, startTime, endTime, dayOfWeek, location));
setResult(RESULT_OK, i);
finish();
}
}
});
I get dates like this:
c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
df = new SimpleDateFormat("HH:mm a");
datefrom = c.getTime();
startTime = String.valueOf(datefrom);
aTime = df.format(datefrom.getTime());
showFromTime.setText(aTime);
c.add(Calendar.HOUR_OF_DAY, 1);
dateto = c.getTime();
endTime = String.valueOf(dateto);
bTime = df.format(dateto.getTime());
showToTime.setText(bTime);
I have created an EventTableHelper:
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_LOCATION = "location";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT "
+ KEY_LOCATION + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
}
I tried to use getAll events function in an activity to get data.
Edit: Here's my current code.
#Override
public void onClick(View v) {
eventTitle = title.getText().toString();
EventTableHelper db = new EventTableHelper(getApplication());
List<EventData> events;
// events = db.getOverlappingEvents(startTime,endTime);
if (eventTitle.length() == 0) {
Toast.makeText(getApplicationContext(), "Title can not be empty.", Toast.LENGTH_LONG).show();
}
else if(db.doesEventOverlap(startTime,endTime))
{
Toast.makeText(getApplicationContext(), "Event exists", Toast.LENGTH_LONG).show();
}
else
{
db.addEvent(new EventData(eventTitle, startTime, endTime, dayOfWeek, location));
setResult(RESULT_OK, i);
finish();
}
}

minutesTo, minutesFrom will only have the value for the last line in the db.
I would try to do a new function in EventTableHelper:
List<EventData> getOverlappingEvents(Date startTime, Date endTime) {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE
+ " WHERE (" + KEY_FROM_DATE + " < '" + startTime
+ "' AND '" + startTime + "' < " + KEY_TO_DATE + ") OR "
+ " (" + KEY_FROM_DATE + " < '" + endTime
+ "' AND '" + endTime + "' < " + KEY_TO_DATE + ") OR "
+ " (" + KEY_FROM_DATE + " < '" + startTime
+ "' AND '" + endTime + "' < " + KEY_TO_DATE + ") OR "
+ " ('" + startTime + "' < " + KEY_FROM_DATE
+ " AND " + KEY_TO_DATE + " < '" + endTime + "')";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
and in onClick:
events = db.getOverlappingEvents();
...
and instead of:
else if(minutesFrom == minutesTo)
this:
else if(events.size() > 0)
Actually it could be even further optimized, because it looks like you don't need the overlapping events data, only a boolean if there's at least one overlapping event:
boolean doesEventOverlap(Date startTime, Date endTime) {
String selectQuery = "SELECT COUNT(*) FROM " + TABLE
+ " WHERE (" + KEY_FROM_DATE + " < '" + startTime
+ "' AND '" + startTime + "' < " + KEY_TO_DATE + ") OR "
+ " (" + KEY_FROM_DATE + " < '" + endTime
+ "' AND '" + endTime + "' < " + KEY_TO_DATE + ") OR "
+ " (" + KEY_FROM_DATE + " < '" + startTime
+ "' AND '" + endTime + "' < " + KEY_TO_DATE + ") OR "
+ " ('" + startTime + "' < " + KEY_FROM_DATE
+ " AND " + KEY_TO_DATE + " < '" + endTime + "')";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
return cursor.getInt(0) > 0;
} while (cursor.moveToNext());
}
return false;
}
and in onClick instead of:
else if(minutesFrom == minutesTo)
this:
else if(db.doesEventOverlap())

Related

Error: Attempt to invoke virtual method on null object reference 'android.database.Cursor com.myapplication.DatabaseHeleper.getData()'

This the error
I have attached the error above after executing code below mentioned, the code given below is not full code but it targets the main code for which my question is.I am trying to send sms through a variable in which number is stored by fetching from sqlite database. So below code shows that I tried to fetch from dbhelper.java class and store in variable num in sendsms.java class but i think it is not fetching Hence i would request you to see the code and guide where i am wrong for improvement. I hope that now question is clear and sufficient description is given so please help.
sendsms.java
try {
Cursor cursor = databaseHelper.getdata();
while (cursor.moveToNext())
{
String num = cursor.getString(0);
String numm = cursor.getString(1);
String nummm = cursor.getString(2);
}
}
catch(Exception e){
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
public void run() {
sms.sendTextMessage(num, null, "Help! I've met with an accident at http://maps.google.com/?q=" + String.valueOf(latitude) + "" +
"," + String.valueOf(longitude), null, null);
dbhelper.java
public static final String TABLE_REGISTER = "signin";
public static final String COL_ID = "USER_ID";
public static final String COL_NAME = "NAME";
public static final String COL_PHONE = "PHONE_NUMBER";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_PASSWORD = "PASSWORD";
public static final String COL_CONFIRM_PASSWORD = "CONFIRM_PASSWORD";
public static final String COL_NAMEone_CON = "NAMEONE";
public static final String COL_NUMBERone_CON = "NUMBERONE";
public static final String COL_NAMEtwo_CON = "NAMETWO";
public static final String COL_NUMBERtwo_CON = "NUMBERTWO";
public static final String COL_NAMEthree_CON = "NAMETHREE";
public static final String COL_NUMBERthree_CON = "NUMBERTHREE";
public SQLiteDatabase db;
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_REGISTER + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ COL_NAME + " TEXT , " + COL_PHONE + " LONG UNIQUE ," + COL_EMAIL + " VARCHAR UNIQUE," + COL_PASSWORD + " VARCHAR , "
+ COL_CONFIRM_PASSWORD + " VARCHAR ," + COL_NAMEone_CON + " TEXT , "
+ COL_NUMBERone_CON + " LONG UNIQUE ," + COL_NAMEtwo_CON + " TEXT ," + COL_NUMBERtwo_CON + " LONG UNIQUE , "
+ COL_NAMEthree_CON + " TEXT ," + COL_NUMBERthree_CON + " LONG UNIQUE " + ")");
}
public Cursor getdata(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select NUMBERONE, NUMBERTWO,NUMBERTHREE from signin ", null);
return cursor;
}
It seems that you have to call getReadableDatabase or getWritableDatabase before you need the data, this is because it takes time to create the database.So, you have to be aware of that.
Also, I wanted to remark that you must cursor.moveToFirst() before you do cursor.moveToNext() on sendsms.java
Please change your code like this:-
try {
Cursor cursor = databaseHelper.getdata();
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String num = cursor.getString(0);
String numm = cursor.getString(1);
String nummm = cursor.getString(2);
}
}
}
catch(Exception e){
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}

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 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.database.sqlite.SQLiteConstraintException can not be fixed

I have a insertion method which cheks first if the row is available or not, if not then it tries to create new or if available then it updates that, but this method giving me the exception in the else part, here is my method
public long SetSettings(String whichCol, String value) {
// TODO Auto-generated method stub
preferences = ourcontext.getSharedPreferences(filenames, 0);
String[] colum = new String[] { KEY_CAR };
Cursor c = ourDB.query(DBhelper.DATABASE_SETTINGSTABLE, colum, KEY_CAR
+ "=" + "'" + preferences.getString("selectedcar", "") + "'",
null, null, null, null);
ContentValues cvedit = new ContentValues();
cvedit.put(KEY_CAR, preferences.getString("selectedcar", ""));
cvedit.put(whichCol, value);
if (c.getCount() > 0) {
return ourDB.update(
DBhelper.DATABASE_SETTINGSTABLE,
cvedit,
KEY_CAR + "=" + "'"
+ preferences.getString("selectedcar", ""), null);
} else {
return ourDB.insert(DBhelper.DATABASE_SETTINGSTABLE, null, cvedit);
}
}
and this is how I created my database:
public static final String KEY_ID = "_id";
public static final String KEY_CAR = "car";
public static final String KEY_SET_DISENTRY_MODE = "ditance_entry_mode";
public static final String KEY_SET_DISUNIT = "distance_unit";
public static final String KEY_SET_PETROLUNIT = "petrol_unit";
public static final String KEY_SET_CONDISPLAY = "consumption_display";
public static final String KEY_SET_DATEFORMAT = "date_format";
public static final String KEY_SET_CURRENCY = "currency";
public static final String KEY_SET_STOREFILLLOC = "store_fillloc";
public static final String KEY_SET_GPSPIN = "gps_pin";
public static final String KEY_SET_KEYCLICK = "keyboard_click";
public static final String KEY_SET_KEYVIBRATE = "keyboard_vibrate";
public static final String KEY_SET_BACKUP = "backup";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_SETTINGSTABLE + " (" + KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_CAR
+ " TEXT NOT NULL, " + KEY_SET_DISENTRY_MODE + " TEXT, "
+ KEY_SET_DISUNIT + " TEXT, " + KEY_SET_PETROLUNIT + " TEXT, "
+ KEY_SET_CONDISPLAY + " TEXT, " + KEY_SET_DATEFORMAT
+ " TEXT, " + KEY_SET_CURRENCY + " TEXT, "
+ KEY_SET_STOREFILLLOC + " TEXT, " + KEY_SET_GPSPIN + " TEXT, "
+ KEY_SET_KEYCLICK + " TEXT, " + KEY_SET_KEYVIBRATE + " TEXT, "
+ KEY_SET_BACKUP + " TEXT NOT NULL);");
}
I cant figure out where is my problem, any help?
you have a constraint KEY_SET_BACKUP TEXT NOT NULL but when updating you are passing null as this value, so add below line too to the contentvalues
cvedit.put(KEY_SET_BACKUP,"");

Categories