How to insert values with Foreign KEY in SQLite? - java

I am new with Android Sqlite Database.
I have created a database with SQLite in Android and I have a table Student_details which use a foreign key of the table: Student, I have made the id as AUTOINCREMENT.
And i tried to return the value of the AUTOINCREMENT Id from Student table.
But I am stuck to use the return values to insert into COLUMN_FR_KEY_USER_ID = "student_id"; as Foreign Key values.
How can I add value with a foreign key from another table using ContentValues into insetDataIntoStudentDetails method?
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "finalStudent.db";
private static final int VERSION_NUMBER = 16;
private static final String TABLE_STUDENT = "Student";
private static final String TABLE_DETAILS_NAME = "Student_details";
private static final String COLUMN_STUDENT_ID = "id";
private static final String COLUMN_DETAILS_ID = "id";
private static final String COLUMN_FR_KEY_USER_ID = "student_id";
private static final String COLUMN_STUDENT_NAME = "name";
private static final String COLUMN_DETAILS_NAME = "name";
private static final String COLUMN_STUDENT_EMAIL = "email";
private static final String COLUMN_STUDENT_PASSWORD = "password";
private static final String CREATE_STUDENT_TABLE = "CREATE TABLE "+TABLE_STUDENT+"( "+COLUMN_STUDENT_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+COLUMN_STUDENT_NAME+" TEXT, "+COLUMN_STUDENT_EMAIL+" TEXT, "+COLUMN_STUDENT_PASSWORD+" TEXT)";
private static final String CREATE_DETAILS_TABLE = "CREATE TABLE "+TABLE_DETAILS_NAME+"( "+COLUMN_DETAILS_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+COLUMN_DETAILS_NAME+" TEXT, "+COLUMN_FR_KEY_USER_ID+" INTEGER, FOREIGN KEY("+COLUMN_FR_KEY_USER_ID+") REFERENCES "+TABLE_STUDENT+" ("+COLUMN_STUDENT_ID+") ON UPDATE CASCADE ON DELETE CASCADE)";
private Context context;
private static final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_STUDENT;
private static final String DROP_DETAILS_TABLE = "DROP TABLE IF EXISTS "+TABLE_DETAILS_NAME;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, VERSION_NUMBER);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
Toast.makeText(context,"Table created successfully and called onCreate method",Toast.LENGTH_SHORT).show();
db.execSQL(CREATE_STUDENT_TABLE);
db.execSQL(CREATE_DETAILS_TABLE);
}catch (Exception e){
Toast.makeText(context,"Exception : "+e,Toast.LENGTH_SHORT).show();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
Toast.makeText(context,"Table created successfully and called onCreate method",Toast.LENGTH_SHORT).show();
db.execSQL(DROP_TABLE);
db.execSQL(DROP_DETAILS_TABLE);
onCreate(db);
}catch (Exception e){
Toast.makeText(context,"Exception : "+e,Toast.LENGTH_SHORT).show();
}
}
public long insertDataIntoStudent( String name, String email, String password){
// to write or read data in database , we have to call getWritableDatabase
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
// we have to call contentValues class to store data in the data
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_STUDENT_NAME,name);
contentValues.put(COLUMN_STUDENT_EMAIL,email);
contentValues.put(COLUMN_STUDENT_PASSWORD,password);
// Insert the new row, returning the primary key value of the new row
long newRowId = sqLiteDatabase.insert(TABLE_STUDENT,null,contentValues);
return newRowId;
}
public void insetDataIntoStudentDetails(String name){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// TODO: insert the foreign key's value
contentValues.put(name,name);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
//enable foreign key constraints like ON UPDATE CASCADE, ON DELETE CASCADE
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private final AppCompatActivity activity = MainActivity.this;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseHelper = new DatabaseHelper(activity);
databaseHelper.insertDataIntoStudent("Bappy","abcd#gmail.com","145456");
}
}

I'll answer about databases in general, not specifically about Sqlite or it's usage in Android.
So you have student's name (which is not a primary key), but you need to save some additional data for this student to another table. The steps are:
Execute SELECT id FROM students WHERE name = ? to find the relevant identifier.
Execute INSERT INTO student_details for your secondary table using retrieved id as a key.
Extra tips:
Name is not a good unique identifier. It's good to have one more criteria - such as some group name, or group number or even date of birth.
When your database is large enough you may benefit from index for your search criteria to optimize execution of the first query. But usually it's not the case for client-side (in-app) databases.
Here we assume that name is not the data which could be updated by someone (or something) else between searching for id and executing INSERT. Otherwise it's wise to use transaction and "lock" your student until you complete the updates.

Related

How to create two tables in one db file?

I want to create two tables in one db file, but it is not working as expected.
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "Bocchi.db";
public DBHelper(Context context) {
super(context, "Bocchi.db", null, 1);
}
public static final String TABLE_NAME1 = "users";
public static final String TABLE_NAME2 = "breakfast";
#Override
public void onCreate(SQLiteDatabase MyDB) {
String table1 = "CREATE TABLE "+TABLE_NAME1+"(username TEXT PRIMARY KEY, password TEXT)";
String table2 = "CREATE TABLE "+TABLE_NAME2+"(username TEXT PRIMARY KEY, energy INT)";
MyDB.execSQL(table1);
MyDB.execSQL(table2);
}
Why am I doing like on video but it cannot create two tables. I have checked the db file, but it only has one table.
You can try the onUpgrade method like below
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVer, int newVer){
onCreate(_db);
}

Migration from SQLite to Room DB

I am facing a problem while migrating from SQLite to Room DB.
The problem is my old SQLite schema doesn't match with the new Room DB schema in my old SQLite DB I forgot to set primaryKey to NOT NULL and also I have a column URL and that column doesn't have any type like TEXT, INTEGER or BOOLEAN.
So now when I try to migrate my SQLite to Room I got Schema don't match error and my App is published on play store with SQLite DB.
So any help will be highly appreciated.
My old SQLite DB code:
private static final String DATABASE_NAME = "mylist.db";
private static final String TABLE_NAME = "mylist_data";
private static final String POST_TITLE = "ITEM1";
private static final String POST_URL = "URL";
private static final String KEY_ID = "ID";
public BookmarksDb(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" ITEM1 TEXT," +
" URL)";
db.execSQL(createTable);
}
My new Room DB code:
#Entity(tableName = "mylist_data")
public class Bookmark {
#PrimaryKey()
#ColumnInfo(name = "ID")
private int id;
#ColumnInfo(name = "ITEM1")
private String postTitle;
#ColumnInfo(name = "URL")
private String postUrl;
Problems are:
ID is NOT NULL = false in SQLite and in Room it is true by default(can't change it)
URL column in SQLite doesn't have any type and in Room it is TEXT by default.
I don't want to lose my old data which is stored in SQLite and my app is published, so now I want to migrate to Room without losing old user data.
Please help me to solve this problem.
You have two issue, the first the NOT NULL required is due to how Room handles primatives. So instead of using int use Integer (although really you should use Long). So change the Entity to be :-
#Entity(tableName = "mylist_data")
public class Bookmark {
#PrimaryKey()
#ColumnInfo(name = "ID")
private Integer id;
#ColumnInfo(name = "ITEM1")
private String postTitle;
#ColumnInfo(name = "URL")
private String postUrl;
The second issue is the column affinity, you need to ALTER your table to suit the Entity, As you have private String postUrl; then as you have found Room expects a column type of TEXT as opposed to nothing (UNDEFINED Affinity = 1).
To circumvent this, you could run the following SQL's to convert the table to suit Room:-
DROP TABLE IF EXISTS converted_mylist_data;
DROP TABLE IF EXISTS old_mylist_data;
CREATE TABLE IF NOT EXISTS converted_mylist_data (ID INTEGER PRIMARY KEY AUTOINCREMENT, ITEM1 TEXT, URL TEXT);
INSERT INTO converted_mylist_data SELECT * FROM mylist_data; /* copies existing data into new table */
ALTER TABLE mylist_data RENAME TO old_mylist_data;
ALTER TABLE converted_mylist_data RENAME TO mylist_data;
DROP TABLE IF EXISTS old_mylist_data;
Note you can actually retrieve the SQL to create the new table from the java(generated)
Example
Run 1 creates the database (version 1) not using Room using:-
db.execSQL("CREATE TABLE mylist_data (ID INTEGER PRIMARY KEY AUTOINCREMENT,ITEM1 TEXT, URL);");
db.execSQL("INSERT INTO mylist_data VALUES(null,'item1','my url');");
The following changes are then made :-
Added the Entity
:-
#Entity(tableName = "mylist_data")
public class Bookmark {
#PrimaryKey()
#ColumnInfo(name = "ID")
private Long id; /* <<<<<<<<<< CHANGED (could be Integer) from primative to object*/
#ColumnInfo(name = "ITEM1")
private String postTitle;
#ColumnInfo(name = "URL")
private String postUrl;
public Bookmark(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
public String getPostUrl() {
return postUrl;
}
public void setPostUrl(String postUrl) {
this.postUrl = postUrl;
}
}
A Dao
:-
#Dao
interface AllDao {
#Query("SELECT * FROM mylist_data")
List<Bookmark> getAll();
}
The Database with the version increased and a Migration for version 1 to 2
:-
#Database(entities = Bookmark.class,version = 2 /*<<<<<<<<<<*/,exportSchema = false)
abstract class TheDatabase extends RoomDatabase {
abstract AllDao getAllDao();
private static volatile TheDatabase instance;
public static TheDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context,TheDatabase.class,"mylist.db")
.allowMainThreadQueries()
.addMigrations(MIGRATION_1_2)
.build();
}
return instance;
}
static final Migration MIGRATION_1_2 = new Migration(1,2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
database.beginTransaction();
database.execSQL("DROP TABLE IF EXISTS converted_mylist_data;");
database.execSQL("DROP TABLE IF EXISTS oldmylist_data;");
database.execSQL("CREATE TABLE IF NOT EXISTS converted_mylist_data (ID INTEGER PRIMARY KEY AUTOINCREMENT, ITEM1 TEXT, URL TEXT);");
database.execSQL("INSERT INTO converted_mylist_data SELECT * FROM mylist_data;");
database.execSQL("ALTER TABLE mylist_data RENAME TO oldmylist_data;");
database.execSQL("ALTER TABLE main.converted_mylist_data RENAME TO mylist_data;");
database.setTransactionSuccessful();
database.endTransaction();
}
};
}
The changed invoking/using activity (from SQLite to Room with old code commented out)
:-
public class MainActivity extends AppCompatActivity {
//DBHelper db; /* Run 1 */
TheDatabase db; /* Run 2 NEW */
AllDao dao; /* Run 2 NEW */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Run 1 create the SQLite based database */
/*
db = new DBHelper(this);
db.getWritableDatabase();
*/
/* Run 2 NEW */
db = TheDatabase.getInstance(this);
dao = db.getAllDao();
for (Bookmark b: dao.getAll()) {
Log.d("BOOKMARKINFO","ID = " + b.getId() + " PostTitle = " + b.getPostTitle() + " PostURL =" + b.getPostUrl());
}
}
}
Result :-
Successfully runs and outputs :-
D/BOOKMARKINFO: ID = 1 PostTitle = item1 PostURL =my url
i.e. data has been kept.
By default sqlite use Blob column type if type not defined in create table statement . Paragraph 3.1.3 of sqlite doc. That's why you can use #ColumnInfo(name = "URL", typeAffinity = ColumnInfo.BLOB) to solve your second problem. You declare id with type int which cant be null, try to use Integer instead int - i think it solve your first problem.
I think you have other option to migrate on room and not lose your data: use migration mechanism.

Database error in Android from create method

I get this logcat error:
Caused by: android.database.sqlite.SQLiteException: no such column: id (code 1): , while compiling: SELECT * FROM notes WHERE id=0
This my code:
public static final String dbName="notesDb";
public static final Integer DB_version=1;
public static final String key_id="id";
public static final String key_title="title";
public static final String key_subject="subject";
public static final String Table_notes="notes";
public DbNotes(Context context) {
super(context, dbName, null, DB_version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String create_table="create table "+Table_notes+"("+key_id+"Integer primary key,"+key_title+" varchar(30), "+key_subject+" varchar(50)) ";
db.execSQL(create_table);
}
public Note getNoteByID(int id){
Note note=null;
SQLiteDatabase db=this.getReadableDatabase();
String selectQuery="SELECT * FROM "+Table_notes+" WHERE "+key_id+"="+id;
Cursor cursor=db.rawQuery(selectQuery,null);
if (cursor.moveToFirst()){
String title=cursor.getString(cursor.getColumnIndex(key_title));
String subject=cursor.getString(cursor.getColumnIndex(key_subject));
int id_item=cursor.getInt(cursor.getColumnIndex(key_id));
note=new Note(title,subject,id_item);
}
cursor.close();
return note;
}
How can I solve this?
Error is in your Create query, you need to provide appropriate space after column name.
"create table "+Table_notes+"("+key_id+" Integer primary key," // you missed space before Integer
So sqlite will create your column with name idInteger and not id, You can try using select query by referring id column as idInteger.

How to setup MySQL database tables for an Android Studio Application?

currently I am developing an app for my final class in college. The concept of the app is a Contact keeping app, essentially a user will be greeted by a login screen where they can either login if they already have an account or register if they don't. When you register the user will be prompt to enter their name, username, password and email. They then submit it and they will again be greeted by the login screen where they can now login in with their recently created credentials. Once they login successfully they be be show an Activity that welcomes them with their name that is retrieved from the table in the database by matching the username and password on the login, it retrieves all the information in that row. I pretty much have that down but what I am having trouble with is where am I going to hold the contacts that the users wants to save, I know that is has to be in another table but how am I going to set it up so I can match the a certain user to all of their contacts in the other table.
Once I get that information I need to put it on a ListView so the user can see their contacts and scroll through them, they can then add, delete or edit them.
As of right now I am able to register, login and display the welcome screen with no problem now I just need to be able to add, delete and edit contacts.
Java is used for the Android Studio part and PHP is used for the file that make the connection in the host online.
I am using Volley and JSON request.
The database and PHP files that make the request to the database are hosted in 000webhost.
This seems like a simple CRUD application.
If you use a RESTful communication model it's quite simple to achieve.
As for storing the contacts, you can have a file specific to each user and have that file's URI on the user's table in the DB. The file can be CSV, or JSON which is easily convertable into POJOs with the right API.
Good luck.
First, create a MySQLite Helper class
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_CONTACTS = "contacts";
public static final String COLUMN_CONTACTS_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_USERNAME ="username";
public static final String COLUMN_PASSWORD = "password"
private static final String DATABASE_NAME = "Contacts.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CONTACTS_CREATE = "create table "+ TABLE_CONTACTS+
"("+COLUMN_CONTACTS_ID+" integer primary key autoincrement, "
+COLUMN_NAME+" text not null, "
+COLUMN_USERNAME+" text not null,"
+COLUMN_PASSWORD+" text not null);";
public MySQLiteHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database){
database.execSQL(DATABASE_CONTACTS_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
Log.w(MySQLiteHelper.class.getName(),"Upgrading database from version "
+oldVersion
+ " to"
+newVersion
+", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS "+TABLE_CONTACTS);
onCreate(db);
}}
Then a model class
public class ContactModel {
private long id;
private String name;
private String username;
private String password;
///////////
public long getId(){
return id;
}
public void setId(long id){
this.id = id;
}
//////////
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public void setUsername(String username){
this.username = username;
}
////////////
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
} }
Then a datasource
public class ContactsDataSource {
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allContactsColumns = {MySQLiteHelper.COLUMN_CONTACTS_ID,MySQLiteHelper.COLUMN_NAME,MySQLiteHelper.COLUMN_USERNAME,
MySQLiteHelper.COLUMN_PASSWORD};
public ContactsDataSource(Context context){
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close(){
dbHelper.close();
}
public ContactModel createContact(String name, String username, String password){
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NAME, name);
values.put(MySQLiteHelper.COLUMN_EMAIL,username);
values.put(MySQLiteHelper.COLUMN_PHONE,password);
long insertContactsId = database.insert(MySQLiteHelper.TABLE_CONTACTS, null, values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_CONTACTS,allContactsColumns,MySQLiteHelper.COLUMN_CONTACTS_ID+" = "
+insertContactsId, null, null, null, null);
cursor.moveToFirst();
ContactModel newContact = cursorToContact(cursor);
cursor.close();
Log.d("written", "Info was written");
return newContact;
}
public void deleteContact(ContactModel contact){
long id = contact.getId();
System.out.println("Comment deleted with id: "+id);
database.delete(MySQLiteHelper.TABLE_CONTACTS,MySQLiteHelper.COLUMN_CONTACTS_ID
+" = "+id,null);
}
public ArrayList<ContactModel> getAllContacts(){
ArrayList<ContactModel> contacts = new ArrayList<>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_CONTACTS, allContactsColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
ContactModel contact = cursorToContact(cursor);
contacts.add(contact);
cursor.moveToNext();
}
cursor.close();
return contacts;
}
private ContactModel cursorToContact(Cursor cursor){
ContactModel contact = new ContactModel();
contact.setId(cursor.getLong(0));
contact.setName(cursor.getString(1));
contact.setUsername(cursor.getString(2));
contact.setPassword(cursor.getString(3));
return contact;
}}
You access the datasource as follows:
//Open the database
dataSource = new ContactsDataSource(this);
dataSource.open();
//use datasource functions like create and delete
datasource.close();
You can display the info in a listview by calling ContactsDataSource.getAllContacts(), and displaying the results using a custom listAdapter. The idea is that you will use the Data Source's functions to grab the data you want, and feed it into the model class. From there you can extract what you need for the listview. Let me know if you need more help with that.
You also mentioned wanting to make multiple tables in the database, and that is as easy as using the above code but just adding another variable, such as TABLE_CONTACTS2 = "contacts2", and duplicating the functions for that table.

Getting NULL value in foreign key column

I have two table (Information and WorkDetails) in SQLite where WorkDetails has a foreign key which refer to Information. When everytime the data inserted, the foreign key should follow the number of PK in Information. However, I get NULL value in foreign key column. The PK in Information and WorkDetails Table is auto-increment.
MyDatabaseAdapter.java
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table "+TABLE_INFO+"(ID INTEGER PRIMARY KEY ,Name TEXT)");
db.execSQL("create table"+TABLE_WORKDETAILS+"(ID INTEGER PRIMARY KEY , Project TEXT, WorkDescription TEXT, Per Text, TimeIn DATETIME, TimeOut DATETIME,TotalHours DATETIME, TableInfo_id INTEGER, FOREIGN KEY(TableInfo_id)REFERENCES TABLE_INFO(ID)");
}
WorkDetailsTable.java
WD= new com.example.project.project.API.WorkDetailsAPI(this);
ts= new com.example.project.project.API.InfoAPI(this);
Button btn1=(Button)findViewById(R.id.button2);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
W1=txtWork1.getText().toString();
W2=txtWork2.getText().toString();
W3=txtWork3.getText().toString();
W4=txtWork4.getText().toString();
a1 = spinnerTra.getSelectedItem().toString();
a2= spinnerTra2.getSelectedItem().toString();
a3 = spinnerTra3.getSelectedItem().toString();
a4=spinnerTra4.getSelectedItem().toString();
P1=per1.getText().toString();
P2=per2.getText().toString();
P3=per3.getText().toString();
P4=per4.getText().toString();
ts.insertTimeSheet(name); // refer to TimeSheetAPI
WD.insertWorkDetails(a1,W1,P1,b,c,th); // insert multiple row and refer to WorkDetailsAPI
WD.insertWorkDetails(a2,W2,P2,d,e1,th);
WD.insertWorkDetails(a3, W3, P3, f, g,th);
WD.insertWorkDetails(a4,W4,P4,h,i,th);
}
});
InfoAPI.java
public class InfoAPI {
private SQLiteDatabase database;
private MyDatabaseHelper dbHelper;
public String[] allColumns={MyDatabaseHelper.ID,MyDatabaseHelper.Name};
public InfoAPI(Context context)
{
dbHelper=new MyDatabaseHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public long insertTimeSheet(String name)
{
database=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(MyDatabaseHelper.Name,name);
database.insert(MyDatabaseHelper.TABLE_INFO,null,values);
database.close();
return 0 ;
}
}
WorkDetailsAPI.java
public class WorkDetailsAPI {
private SQLiteDatabase database;
private MyDatabaseHelper dbHelper;
public String[] allColumns={MyDatabaseHelper.ID2,MyDatabaseHelper.Project,MyDatabaseHelper.WorkDescription,MyDatabaseHelper.Per,MyDatabaseHelper.TimeIn,MyDatabaseHelper.TimeOut,MyDatabaseHelper.TotalHours,MyDatabaseHelper.TableInfo_id};
public WorkDetailsAPI(Context context)
{
dbHelper=new MyDatabaseHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public long insertWorkDetails(String project, String workDescription, String per,String timeIn,String timeOut,String totalHours)
{
database=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(MyDatabaseHelper.Project,project);
values.put(MyDatabaseHelper.WorkDescription,workDescription);
values.put(MyDatabaseHelper.Per,per);
values.put(MyDatabaseHelper.TimeIn,timeIn);
values.put(MyDatabaseHelper.TimeOut,timeOut);
values.put(MyDatabaseHelper.TotalHours, totalHours);
database.insert(MyDatabaseHelper.TABLE_WORKDETAILS,null,values);
database.close();
return 0 ;
}
}
change your insert method like this so you get your table_info id
public long insertTimeSheet(String name)
{
database=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(MyDatabaseHelper.Name,name);
database.insert(MyDatabaseHelper.TABLE_INFO,null,values);
Cursor cursor = database.rawQuery("SELECT MAX(ID) FROM Table_Info", null);
database.close();
return cursor.getLong(0) ;
}
and change your code
long id = ts.insertTimeSheet(name); // refer to TimeSheetAPI
WD.insertWorkDetails(a1,W1,P1,b,c,th,id);
your insertwd should
public long insertWorkDetails(String project, String workDescription, String per,String timeIn,String timeOut,String totalHours, long id)
{
database=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(MyDatabaseHelper.Project,project);
values.put(MyDatabaseHelper.WorkDescription,workDescription);
values.put(MyDatabaseHelper.Per,per);
values.put(MyDatabaseHelper.TimeIn,timeIn);
values.put(MyDatabaseHelper.TimeOut,timeOut);
values.put(MyDatabaseHelper.TotalHours, totalHours);
values.put("TableInfo_id", id);
database.insert(MyDatabaseHelper.TABLE_WORKDETAILS,null,values);
database.close();
return 0 ;
}
You need to pass the inserted parent row id (TABLE_INFO ID) to your "insertWorkDetails" method after you actually inserted the parent row in "insertTimeSheet" method.
public long insertWorkDetails(Integer id, String project, String workDescription, String per,String timeIn,String timeOut,String totalHours){ ... }
Foreign keys won't get updated by themselves.

Categories