I have to create 2 to 3 tables and I want to create foreign key of two tables and add into 3rd table. When I run the app data is inserted successfully but foreign key is not showing in the database table structure and table.
Here is my Database class:
public static final String Tsk_id = "task_id";
public static final String Task_Project_NAme = "project_name";
public static final String Task_Team_Member_Name = "assign_to";
public static final String Task_Title = "task_time";
public static final String Task_Start_Date = "start_date";
public static final String Task_CompletionDate = "completion_date";
public static final String Task_CompletionTime = "completion_time";
public static final String Task_Description = "task_description";
public static final String Task_Status = "task_status";
public static final String Task_Is_Active = "IsActive";
public static final String Task_Project_id="project_id";
public static final String Task_Team_Memmber_Id="team_member_id";
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_TASK_TABLE = "CREATE TABLE " + ASSIGN_TASK_TABLE + "("
+ Tsk_id +" integer primary key autoincrement, "
+ Task_Project_NAme + " TEXT,"
+ Task_Team_Member_Name + " TEXT,"
+ Task_Title + " TEXT,"
+ Task_Start_Date + " TEXT,"
+ Task_CompletionDate + " TEXT,"
+ Task_CompletionTime + " TEXT,"
+ Task_Description + " TEXT,"
+ Task_Status + " TEXT,"
+ Task_Is_Active + " TEXT"
+ " FOREIGN KEY ("+Task_Project_id+") REFERENCES " +CONTACTS_TABLE_NAME+" ("+Project_id+")"
+ " FOREIGN KEY ("+Task_Team_Memmber_Id+") REFERENCES " +DEFINE_TEAM_MEMBER_TABLE+" ("+Team_Member_id+")";
db.execSQL(CREATE_TASK_TABLE);
}
public boolean insertTaskDetails(String strTask_Project_NAme,String strTask_Team_Member_Name,
String strTask_Title,String strTask_Start_Date,String strTask_CompletionDat,
String strTask_CompletionTime,String strTask_Description,
String strTask_Status,String strTask_Is_Active)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Task_Project_NAme, strTask_Project_NAme);
contentValues.put(Task_Team_Member_Name, strTask_Team_Member_Name);
contentValues.put(Task_Title, strTask_Title);
contentValues.put(Task_Start_Date, strTask_Start_Date);
contentValues.put(Task_CompletionDate,strTask_CompletionDat);
contentValues.put(Task_CompletionTime,strTask_CompletionTime);
contentValues.put(Task_Description, strTask_Description);
contentValues.put(Task_Status, strTask_Status);
contentValues.put(Task_Is_Active,strTask_Is_Active);
db.insert(ASSIGN_TASK_TABLE, null, contentValues);
db.close();
return true;
}
+ " FOREIGN KEY ("+Task_Project_id+") REFERENCES " +CONTACTS_TABLE_NAME+" ("+Project_id+")"
for this line of code where is Task_Project_id column in the while creating the table.. please check.
You need to create a particular column to reference as foreign key.
same with this line too
" FOREIGN KEY ("+Task_Team_Memmber_Id+") REFERENCES " +DEFINE_TEAM_MEMBER_TABLE+" ("+Team_Member_id+")";
Related
I have tried to insert Student Dethasails on my Student Table Data. But this error is shown:
Error inserting STUDENT_ROLL=1 STUDENT_NAME=D _CID=4
android.database.sqlite.SQLiteException: no such table: STUDENT_TABLE (code 1): , while compiling: INSERT INTO STUDENT_TABLE(STUDENT_ROLL,STUDENT_NAME,_CID) VALUES (?,?,?)
This is my code:
Declare Table:-
public static final String STUDENT_TABLE_NAME = "STUDENT_TABLE";
public static final String S_ID = "_SID";
public static final String STUDENT_NAME_KEY = "STUDENT_NAME";
public static final String STUDENT_ROLL_KEY = "STUDENT_ROLL";
public static final String CREATE_STUDENT_TABLE =
"CREATE TABLE " + STUDENT_TABLE_NAME + "(" +
S_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
C_ID + " LONG , " +
STUDENT_NAME_KEY + " VARCHAR(255), " +
STUDENT_ROLL_KEY + " INTEGER , " +
" FOREIGN KEY (" + C_ID + ") REFERENCES " + CLASS_TABLE_NAME + "(" +C_ID+")" +");";
public static final String DROP_STUDENT_TABLE = " DROP TABLE IF EXISTS " + STUDENT_TABLE_NAME;
public static final String SELECT_STUDENT_TABLE = "SELECT * FROM " + STUDENT_TABLE_NAME;
Add Student Method for adding Students. c_id is a foreign key.
long addStudent(long c_id, String studentName, int studentRoll){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(STUDENT_NAME_KEY,studentName);
values.put(STUDENT_ROLL_KEY,studentRoll);
values.put(C_ID, c_id);
try{
long s_id = sqLiteDatabase.insert(STUDENT_TABLE_NAME, null, values);
return s_id;
} catch (SQLException e){
e.printStackTrace();
}
return -1;
}
The problem here as indicated in the logs is that the table doesn't exists. You created the sqlite statement for creation of the table but I think you didn't execute it from anywhere. You must execute the sqlite statement in your Database helper class:
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(CREATE_STUDENT_TABLE);
}
More information can be found here
you created the query to create your table but it has not been executed anywhere, you just have to execute it before performing an insert
database.execSQL(CREATE_STUDENT_TABLE);
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();
}
I am creating two tables, one for books and one for stores.I want to link every Book in BookStore Table to StoreTable by giving it a Store_ID.
That Store_Id will be the primary key in StoreTable.I am having trouble with the syntax of the foreign key.I also checked http://www.sqlite.org/foreignkeys.html for reference but that didn't provide me with enough clarification.I would be much obliged if anyone helps me.
public class DatabaseHelper extends SQLiteOpenHelper{
//Name of databases
public static final String DATABASE_NAME = "Library.db";
//Version of database
public static final int DATABASE_VERSION = 1;
//Table of Stores
public static final String STORE_TABLE = "Store_Table";
public static final String STORE_ID = "Store_ID";
public static final String STORE_NAME = "Store_name";
public static final String STORE_Address = "Store_Address";
public static final String STORE_LAT = "lat";
public static final String STORE_LNG = "lng";
//Table of Books
public static final String BOOKS_TABLE = "Books_Table";
public static final String BOOK_ID = "Book_ID";
public static final String BOOK_NAME = "Book_name";
public static final String BOOK_AUTHOR = "Book_Author";
public static final String BOOKStore = "BookStore_ID";
//Creating Stores Table
private static final String SQL_CREATE_TABLE_STORE = "CREATE TABLE " + STORE_TABLE + "("
+ STORE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ STORE_NAME + " TEXT NOT NULL, "
+ STORE_Address + " TEXT NOT NULL, "
+ STORE_LAT + " TEXT NOT NULL, "
+ STORE_LNG + " TEXT NOT NULL"
+");";
//Creating Books Table
private static final String SQL_CREATE_TABLE_BOOKS = "CREATE TABLE " + BOOKS_TABLE + "("
+ BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BOOK_NAME + " TEXT NOT NULL, "
+ BOOK_AUTHOR + " TEXT NOT NULL, "
//How to relate BookStore with Store_ID here?
+FOREIGN KEY(BOOKStore) REFERENCES STORE_TABLE(STORE_ID));
+");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_TABLE_STORE);
sqLiteDatabase.execSQL(SQL_CREATE_TABLE_BOOKS);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//Clear all data
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + STORE_TABLE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + BOOKS_TABLE);
//RECREAT THE TABLES
onCreate(sqLiteDatabase);
}
}
I see multiple problems with the CREATE TABLE statement for the Books_Table. First, if you want to designate a column in a table as a foreign key, that column first has to exist. You were referring to the BookStore_ID column when defining your foreign key, but you never actually defined this column. Second, if you want to mark a column as a foreign key, there is a specific syntax. See below for details.
CREATE TABLE Books_Table (
Book_ID INTEGER PRIMARY KEY AUTOINCREMENT,
Book_name TEXT NOT NULL,
Book_Author TEXT NOT NULL,
BookStore_ID INTEGER,
CONSTRAINT fk_bookstore FOREIGN KEY (BookStore_ID)
REFERENCES Store_Table(Store_ID)
);
This is the correct answer:
private static final String SQL_CREATE_TABLE_BOOKS = "CREATE TABLE " + BOOKS_TABLE + "("
+ BOOK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ BOOK_NAME + " TEXT NOT NULL, "
+ BOOK_AUTHOR + " TEXT NOT NULL, "
//How to relate BookStore with Store_ID here?
+ " FOREIGN KEY ("+ BOOKStore +") REFERENCES "+STORE_TABLE+"("+STORE_ID+"));";
I have another problem with SQLite database in Android OS.
I'm trying to create database with two tables: departments and students.
Departments table contains: dep_id, dep_name and dep_major.
Students table contains: stud_id, dep_id, firstname, surname, email, phone.
How can I put data into this two tables?
There is a Databasehandler.java:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String TAG = "DatabaseHandler";
private static final String DATABASE_NAME = "studentsManager2.db";
// pola tabeli "wydzial"
private static final String TABLE_DEPARTMENTS = "departments",
KEY_DEP_ID = "id",
KEY_DEPARTMENT = "wydzial",
KEY_SPECIALIZATION = "kierunek";
// pola tabeli "students"
private static final String TABLE_STUDENTS = "students",
KEY_STUD_ID = "id",
KEY_ID = KEY_DEP_ID,
KEY_FIRSTNAME = "imie",
KEY_SURNAME = "nazwisko",
KEY_INDEKS = "indeks",
KEY_EMAIL = "email",
KEY_NUMER = "numer";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_DEPARTMENTS + "(" + KEY_DEP_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_DEPARTMENT + " TEXT NOT NULL," + KEY_SPECIALIZATION + " TEXT NOT NULL)");
db.execSQL("CREATE TABLE " + TABLE_STUDENTS + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT NOT NULL," + KEY_SURNAME + " TEXT NOT NULL," + KEY_INDEKS + " INTEGER," + KEY_EMAIL + " TEXT NOT NULL," + KEY_NUMER + " TEXT NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DEPARTMENTS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENTS);
onCreate(db);
}
}
Below methods will insert the records in the sqlite database using Datbase helper class:
public void insertDataInBothTables() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues valuesForDepartmentTable = new ContentValues();
valuesForDepartmentTable.put(KEY_DEPARTMENT , "name");
valuesForDepartmentTable.put(KEY_SPECIALIZATION , "special");
// insert row
long idOfDepart = db.insert(TABLE_DEPARTMENTS, null, valuesForDepartmentTable);
ContentValues values = new ContentValues();
values.put(KEY_FIRSTNAME, "first-name");
values.put(KEY_SURNAME, "sur-name");
values.put(KEY_INDEKS , "inserting-data");
values.put(KEY_EMAIL , "inserting-data");
values.put(KEY_NUMER , "inserting-data");
//Parameter to add department id
values.put(KEY_WYDZIAL, idOfDepart + "");
// insert row
db.insert(TABLE_STUDENTS, null, values);
}
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,"");