Android SQLite: Is this possible to avoid insert same variable - android

I am wondering if its possible to query existing database and detect if same value is in the database when inserting.
This is method of inserting in a class extends SQLiteOpenHelper
public void insertTimeTable_Schedule(String title, String subtitle, String color_text, String color_text_bg,
String mon, String tue, String wed, String thus, String fri, String sat, String sun,
String start_time, String end_time){
sqLiteDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE,title);
values.put(COLUMN_SUBTITLE,subtitle);
values.put(COLUMN_COLOR_TEXT,color_text);
values.put(COLUMN_COLOR_TEXT_BG,color_text_bg);
values.put(COLUMN_MON,mon);
values.put(COLUMN_TUE,tue);
values.put(COLUMN_WED,wed);
values.put(COLUMN_THUS,thus);
values.put(COLUMN_FRI,fri);
values.put(COLUMN_SAT,sat);
values.put(COLUMN_SUN,sun);
values.put(COLUMN_START_TIME,start_time);
values.put(COLUMN_END_TIME,end_time);
sqLiteDatabase.insert(TABLE_TIMETABLE, null, values);
}
Now I'd like to detect and make error message if there is same start_time in COLUMN_START_TIME when inserting new table data.
I tried to display values from database using method will be indicated below, and this will show everything I inserted
public String getData_database(){
sqLiteDatabase = this.getReadableDatabase();
String[] columns = new String[]{KEY_ID, COLUMN_TITLE,COLUMN_SUBTITLE,COLUMN_COLOR_TEXT,COLUMN_COLOR_TEXT_BG,
COLUMN_MON,COLUMN_TUE, COLUMN_WED,COLUMN_THUS, COLUMN_FRI,COLUMN_SAT,COLUMN_SUN,
COLUMN_START_TIME,COLUMN_END_TIME};
#SuppressLint("Recycle")
Cursor cursor =
sqLiteDatabase.query(TABLE_TIMETABLE,columns,null,null,null,null,null);
int iId = cursor.getColumnIndex(KEY_ID);
int iTitle = cursor.getColumnIndex(COLUMN_TITLE);
int iTextcolor = cursor.getColumnIndex(COLUMN_COLOR_TEXT);
int iTextBgcolor = cursor.getColumnIndex(COLUMN_COLOR_TEXT_BG);
int iSubtitle = cursor.getColumnIndex(COLUMN_SUBTITLE);
int iStarttime = cursor.getColumnIndex(COLUMN_START_TIME);
int iEndtime = cursor.getColumnIndex(COLUMN_END_TIME);
StringBuilder result = new StringBuilder();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
result.append("Id: ").append(cursor.getString(iId)).append("\n").append("Title: ").append(cursor.getString(iTitle)).append("\n").append("SubTitle: ").append(cursor.getString(iSubtitle)).append("\n").append("Text Color: ").append(cursor.getString(iTextcolor)).append("\n").append("Text BG Color: ").append(cursor.getString(iTextBgcolor)).append("\n").append("Start Time: ").append(cursor.getString(iStarttime)).append("\n").append("End Time: ").append(cursor.getString(iEndtime)).append("\n\n");
}
sqLiteDatabase.close();
return result.toString();
}
If you have any advice, I'd love to hear.

You can have a method that returns a boolean after querying the table. Then in your insert statement you check if the response is true, then show whatever error, otherwise, insert the record.

This method:
public boolean existsStartTime(String start_time){
sqLiteDatabase = this.getWritableDatabase();
String sql = "SELECT 1 FROM " + TABLE_TIMETABLE + " WHERE " + COLUMN_START_TIME + " = ?";
Cursor c = sqLiteDatabase.rawQuery(sql, new String[] {start_time});
boolean result = c.moveToFirst();
c.close();
sqLiteDatabase.close();
return result;
}
will return true if the value of the variable start_time exists in the table or false if it does not exist.
You can check it like:
String start_time = "<value here>";
if (existsStartTime(start_time)) {
<error message here>
} else {
insertTimeTable_Schedule(...);
}

Related

How to iterate and retrieve over all data stored in sqlite database

I am having problem while retrieving data from sqlite database what I need is to retrieve all data on console. But I am getting only one rows data on console
Here is the code to insert and retrieve data from Sqlite. Please specify what I am missing or doing wrong. Thanks for any help.
public long InsertContacts(Contacts contacts) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_IMAGE, DbUtility.getBytes(contacts.getBmp()));
contentValues.put(KEY_BABY_NAME, contacts.getBaby_name());
contentValues.put(KEY_GENDER, contacts.getBaby_gender());
contentValues.put(KEY_SET_DATE, contacts.getDate());
contentValues.put(KEY_SET_TIME, contacts.getTime());
return db.insert(TABLE_NAME, null, contentValues);
}
public Contacts retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time); // I need to get all date here that have been inserted but i am getting only first rows data every time i insert.
cursor.moveToNext();
return new Contacts(DbUtility.getImage(blob), name, gender, date, time);
}
cursor.close();
return null;
}
}
Contacts.java
public class Contacts {
private Bitmap bmp;
private String baby_name;
private String baby_gender;
private String date;
private String time;
public Contacts(Bitmap b, String n, String g, String d, String t) {
bmp = b;
baby_name = n;
baby_gender = g;
date = d;
time = t;
}
public Bitmap getBmp() {
return bmp;
}
public String getBaby_name() {
return baby_name;
}
public String getBaby_gender() {
return baby_gender;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
}
You should change your retriveContactsDetails() to this:
public List<Contacts> retriveContactsDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{KEY_IMAGE, KEY_BABY_NAME, KEY_GENDER, KEY_SET_DATE, KEY_SET_TIME};
List<Contacts> contactsList = new ArrayList<>();
Cursor cursor;
try {
cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext()) {
byte[] blob = cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE));
String name = cursor.getString(cursor.getColumnIndex(KEY_BABY_NAME));
String gender = cursor.getString(cursor.getColumnIndex(KEY_GENDER));
String date = cursor.getString(cursor.getColumnIndex(KEY_SET_DATE));
String time = cursor.getString(cursor.getColumnIndex(KEY_SET_TIME));
contactsList.add(new Contacts(DbUtility.getImage(blob), name, gender, date, time));
Log.d(TAG, DbUtility.getImage(blob) + name + "-" + gender + "-" + date + "- " + time);
}
} catch (Exception ex) {
// Handle exception
} finally {
if(cursor != null) cursor.close();
}
return contactsList;
}
Also, your Contacts class should be named Contact as it contains only a single instance of your object.
public Contacts retriveContactsDetails() {
...
while (cursor.isAfterLast() == false) {
...
cursor.moveToNext();
return new Contacts(...);
}
Your Contacts class is named wrong because it contains only a single contact. It should be named Contact.
The return statement does what it says, it returns from the function. So the loop body cannot be executed more than once.
What you actually want to do is to construct a list of contacts, add one contact object to the list in each loop iteration, and return that list at the end.

SQLite - creating multiple tables that update or insert

i am having problem inserting and updating values correctly into the database. I have a database, with two tables each with 3 columns DATE, NUM_X, NUM_Y. The two different tables contain the same columns, the only difference in the way values are inserted is that the HOURS_TABLE will take HH (the current hour of the day) and DATE_TABLE will take a short time string dd/MM/yyyy.
The values are not being inserted into new rows, but updating the values of the first row. Both tables currently have only one row.
public static final String HOURS_TABLE = "HOURS_TABLE";
public static final String DATE_TABLE = "DATE_TABLE";
public static final String CreateHoursTable = "create table "+
HOURS_TABLE +" ("+DATE+" string not null, "+NUM_X+
" integer default 0,"+NUM_Y+" integer default 0)";
public static final String CreateDateTable = "create table "+
DATE_TABLE +" ("+DATE+" string not null, "+NUM_X+"
integer default 0,"+NUM_Y+" integer default 0)";
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL(CreateDateTable);
db.execSQL(CreateHoursTable);
}
Two different kinds of date strings could be passed in, on formatted dd/MM/yyyy (short date string )and another for HH (hours)
public long createEntry(int x, int y, String date, int Version_Zero_HoursTable_One_DateTable)
{
/*
* first grab the values needed to increment the database values
* */
Cursor c ;
String[] column = new String[]{DATE,NUM_X,NUM_Y};
if(Version_Zero_HoursTable_One_DateTable == 0)
{
c = ourDatabase.query(HOURS_TABLE, column, date, null, null,
null, null);
}
else
{
c = ourDatabase.query(DATE_TABLE, column, date, null, null,
null, null);
}
int current_x =0;
int current_y = 0;
String current_day = "";
int iX = c.getColumnIndex(NUM_X);
int iY = c.getColumnIndex(NUM_Y);
int iDate = c.getColumnIndex(DATE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
current_x += c.getInt(iX);
current_y += c.getInt(iY);
current_day = c.getString(iDate);
}
ContentValues cv = new ContentValues();
cv.put(NUM_X, smokes+current_smokes);
cv.put(NUM_Y, cravings+current_cravings);
cv.put(DATE, date);
the WHEREargs string is my variable for a where clause, so when the selected DATE from the database equals date it will update that selected column, and if nothing is selected (current_day.equals("")), the statement to insert a new row will execute.
String WHEREargs = DATE+"="+date;
if(Version_Zero_HoursTable_One_DateTable == 0)
{
if(current_day.equals(""))
{
return ourDatabase.insert(HOURS_TABLE, null, cv);
}
else
{
return ourDatabase.update(HOURS_TABLE, cv, WHEREargs, null);
}
}
else
{
if(current_day.equals(""))
{
return ourDatabase.insert(DATE_TABLE, null, cv);
}
else
{
return ourDatabase.update(DATE_TABLE, cv, WHEREargs, null);
}
}
}
any help would be greatly appreciated , Thankyou .
You are using the date variable wrong.
A date value such as 24/03/2014 cannot be directly used as a WHERE expression; it would be interpreted as two integer divisions.
Similarly, a string such as DATE = 24/03/2014 cannot be used as a WHERE expression either, because it compares the value in the date column to a number.
In SQL, strings must be enclosed in 'single quotes'.
However, to avoid formatting problems and SQL injection attacks, it is a better idea to use parameters:
String where = DATE + "= ?";
String[] whereArgs = new String[] { date };
...
db.query(..., where, whereArgs, ...);

Android db.update SQLite

I have a small problem with the method db.update. I need to change a string that corresponds to that received by the query. For example from the query I get the string "hello", if the change in "hello1" must change all the strings "hello".
In my Cursor I have name_s = c.getString(3);
And this is my update:
cv.put(Table1.ABC, Ecia.getText().toString());
db.update(Table1.TABLE_NAME, cv, Table1.ABC+ " = ?", new String[] { name_s});
try this :
String newval=Ecia.getText().toString();
String name_s = c.getString(3);
setMyField(name_s , newval);
public int setMyField(String currvalue , String newvalue) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Table1.ABC, newvalue);
// updating row
return db.update(Table1.TABLE_NAME, values, Table1.ABC + " = ?",
new String[] { currvalue });
}

Get data from database Android

I have a page which can retrieve user data from database
but after whole day of trying, I am only able to get the table column name but not the value inside.
this is my code to create database
public static final String LASTLOGIN = "lastuser";
public static final String USER_ID = "suser_id";
public static final String USER_NAME = "suser_name";
public static final String USER_PASSWORD = "spassword";
public static final String PRIME_ID = "id";
private static final String TABLE_USER =
"create table "+ LASTLOGIN+" ("
+PRIME_ID+" integer primary key autoincrement, "
+ USER_ID + " text, "
+ USER_NAME +" text, "
+USER_PASSWORD+" text); ";
and here is the function implemented to get user data
public Cursor getuser()
{
String[] columns = new String[]{PRIME_ID, USER_NAME, USER_PASSWORD};
Cursor cursor = sqLiteDatabase.query(
LASTLOGIN, columns, null, null, null, null, PRIME_ID +" DESC");
Log.d("TAG", columns[1]);
return cursor;
}
and here is my code to display the result
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.getuser();
String[] resultvalue = new String{
SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();
and the toast result only show the column name but not the value inside, is there any mistake i made? and I want to set limit to 1, but where to set it?
Thanks for helping me
the way you try reading the values is completly wrong.
you create an array
String[] resultvalue = new String[]{
SQLiteAdapter.PRIME_ID,
SQLiteAdapter.USER_NAME,
SQLiteAdapter.USER_PASSWORD};
after that you read the values 0 and 1 from this array.
Your toast works absolutly correctly becouse inside this array you define the column names!
If you want to show the values from your query do it this way:
while(cursor.moveToNext()){
Integer str1 = str 1 + cursor.getInteger(1);
String str2 =str2 + cursor.getString(2);
Toast.makeText(this, str1 + str2, Toast.LENGTH_LONG).show();
}
or a better way receiving the correct index:
cursor.getInteger( cursor.getColumnIndex(SQLiteAdapter.PRIME_ID) );
cursor.getString( cursor.getColumnIndex(SQLiteAdapter.USER_NAME) );
Please note when retrieving data from a database, you store it in a Cursor in the memory and hence can only access it using that particular Cursor object, which you have used in the following line of code.
Cursor cursor = mySQLiteAdapter.getuser();
The Following line retrieves the column names and not the values.
String[] resultvalue = new String[]{SQLiteAdapter.PRIME_ID,SQLiteAdapter.USER_NAME, SQLiteAdapter.USER_PASSWORD};
So the following is doing what you have asked it to do, retrieve column names not values
Toast.makeText(this, resultvalue[0]+resultvalue[1], Toast.LENGTH_LONG).show();
You need something like following:
if(cursor.getCount() != 0)
{
while(cursor.moveToNext())
{
resultvalue [0] = csr.getString(0);
resultvalue [1] = csr.getString(1);
//....
}
}
Hope this helps
here is my solution:
final String TABLE_NAME = "table_name";
String selectQuery = "SELECT Column FROM "+TABLE_NAME+" WHERE column='"+some_value+"'";
SQLiteDatabase db = this.openDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = new String[cursor.getCount()];;
int i = 0;
if (cursor.moveToFirst()) {
do {
i=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));
} while (cursor.moveToNext());
}
cursor.close();

Application crashs when I try to view the entries of in a multiple tables Database

I created two table weekone and weektwo in my database. They a both uploaded the data in the database succussfully taken from EditTexts, however when I want to view the database by pressing Viewbutton, the application crashes.
This is how i am saving entries from Editext in database in table weekone
String treadmillTimings = durOnTreadmill.getText().toString();
DatabaseManager entry = new DatabaseManager(this);
entry.open();
entry.createEntry(treadmillTimings);
entry.close();
String stepperTimings = durOnStepper.getText().toString();
DatabaseManager entry1 = new DatabaseManager(this);
entry1.open();
entry1.week1createEntry1(stepperTimings);
entry1.close();
String stationaryRowingTimings = durOnStationaryRowing.getText().toString();
DatabaseManager entry2 = new DatabaseManager(this);
entry2.open();
entry2.week1createEntry2(stationaryRowingTimings);
entry2.close();
String exerciseBikeTimings = durOnExerciseBike.getText().toString();
DatabaseManager entry3 = new DatabaseManager(this);
entry3.open();
entry3.week1createEntry3(exerciseBikeTimings);
entry3.close();
String ellipticalTrainerTimings = durOnEllipticalTrainer.getText().toString();
DatabaseManager entry4 = new DatabaseManager(this);
entry4.open();
entry4.week1createEntry4(ellipticalTrainerTimings);
entry4.close();
Writing Entries in table weekone
//creating entry in table for treadmill in table week 1 with the help of ContentValues
public long createEntry(String treadmillTimings)
{
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
//enterting each exercise name corresponding to their respective edit Texts
cv.put(KEY_EXERCISENAME, "Treadmill");
cv.put(KEY_DURATION, treadmillTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv);
}
//creating entry in table for stepperTimings in table week 1 with the help of ContentValues
public long week1createEntry1 (String stepperTimings)
{
ContentValues cv1 = new ContentValues();
cv1.put(KEY_EXERCISENAME, "Stepper");
cv1.put(KEY_DURATION, stepperTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv1);
}
//creating entry in table for Stationary Rowing in table week 1 with the help of ContentValues
public long week1createEntry2 (String stationaryRowingTimings)
{
ContentValues cv2 = new ContentValues();
cv2.put(KEY_EXERCISENAME, "Stationary Rowing");
cv2.put(KEY_DURATION, stationaryRowingTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv2);
}
//creating entry in table for exercise bike in table week 1 with the help of ContentValues
public long week1createEntry3 (String exerciseBikeTimings)
{
ContentValues cv3 = new ContentValues();
cv3.put(KEY_EXERCISENAME, "Exercise Bike");
cv3.put(KEY_DURATION, exerciseBikeTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv3);
}
//creating entry in table for elliptical trainer in table week 1 with the help of ContentValues
public long week1createEntry4 (String ellipticalTrainerTimings)
{
ContentValues cv4 = new ContentValues();
cv4.put(KEY_EXERCISENAME, "Stationary Rowing");
cv4.put(KEY_DURATION, ellipticalTrainerTimings);
return ourDatabase.insert(DATABASE_TABLE, null,cv4);
}
Displaying entries in database
//displaying/reading data in the table using cursor
public String week1getData()
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_EXERCISENAME, KEY_DURATION};
Cursor cur = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
//creating a result(string type variable) to store the text and display it.
String result = "";
int iRow = cur.getColumnIndex(KEY_ROWID);
int iExerciseName = cur.getColumnIndex(KEY_EXERCISENAME);
int iDuration = cur.getColumnIndex(KEY_DURATION);
// cursor start from the first position, keeps moving to the next as long as the position in not after that last.
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext())
{
/*getting the rows, exercise name and duration in the tables of database and setting it to result.
.The next time it loops, it will still have the prevoius result*/
result = result + cur.getString(iRow) + " " + cur.getString(iExerciseName) + " " + cur.getString(iDuration) + "\n";
}
return result;
}
All the code is same for tableweektwo except for the below
public String week2getData() <------- ERROR IS IN THIS METHOD, BASED ON LOGCAT
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID, KEY_EXERCISENAME, KEY_DURATION};
Cursor cur = ourDatabase.query(DATABASE_TABLE2, columns, null, null, null, null, null);
//creating a result(string type variable) to store the text and display it.
String result = "";
int iRow = cur.getColumnIndex(KEY_ROWID);
int iExerciseName = cur.getColumnIndex(KEY_EXERCISENAME);
int iDuration = cur.getColumnIndex(KEY_DURATION);
// cursor start from the first position, keeps moving to the next as long as the position in not after that last.
for(cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext())
{
/*getting the rows, exercise name and duration in the tables of database and setting it to result.
.The next time it loops, it will still have the previous result*/
result = result + cur.getString(iRow) + " " + cur.getString(iExerciseName) + " " + cur.getString(iDuration) + "\n";
}
return result;
}
Addtionally I did exactly the same for weektwowhatever i did for weekone. please tell me where am I going wrong. thanks
Saw your logcat and it seems that your database is closed when you try to read the data. I would like to suggest to not to open and close the database so frequently. This creates a lot of confusion in the code. You can try to open the database at onCreate of your parent Activity(the context that you pass) and close it in onDestroy() only.
EDIT: You can refer this for design patterns.
EDIT 2 : You can confirm if this is the problem or not by opening the database only once and never closing it to see if the problem goes away. If it does the refer the linked article in previous edit.

Categories

Resources