Getting NULL value in foreign key column - java

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.

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);
}

How to insert values with Foreign KEY in SQLite?

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.

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.

Android - using variable from another activity

I'm quite new to Android and I guess it's a stupid question but i'll be glad to recieve help. I've got a code in one activity which set a database to SQLite. In another activity I want to refer to this SQLite code in order to enter it into a json and send it to a remote server.
The problem is that it's not recognizing the variable from the other activity. here is the code which creates the data from the db into a string.
In this example I want to create an ArrayList from the db, but it couldnt find the set functions I developed or the table name. Am I missed something ? Here is the code of the ArrayList :
GpsPage.java
public class PersonsDatabaseHandler extends SQLiteOpenHelper {
//Database Name
private static final String DATABASE_NAME = "RecordsDB";
//Table names
private static final TABLE_RECORD = "record";
//Get all Persons
public ArrayList<Record> getAllPersons() {
ArrayList<Record> localList = new ArrayList<Record>();
String selectQuery = "SELECT * FROM " + TABLE_RECORD;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Loops through all rows and adds them to the local list
if(cursor.moveToFirst())
{
do {
//Get person information
Record record = new Record();
Record.setpLong(cursor.getString(0));
Record.setpLat(cursor.getString(1));
Record.setpAcc(cursor.getString(2));
Record.setpTime(cursor.getString(3));
//Add person to list
localList.add(record);
} while (cursor.moveToNext());
}
return localList;
}
}
And here are the codes from the two other java pages (activities), the first one define the get and set of the records :
Record.Java
package com.program.android.taskir;
public class Record {
//private variables
private int id;
private double pLong;
private double pLat;
private float pAcc;
private long pTime;
public Record(){}
// Empty constructor
// constructor
public Record( double pLong, double pLat, float pAcc, long pTime){
super();
this.pLong = pLong;
this.pLat= pLat;
this.pAcc= pAcc;
this.pTime= pTime;
}
#Override
public String toString() {
return "Record [id=" + id + ", Longtitude=" + pLong + ", Latitude=" + pLat + ", Accuracy" + pAcc + ", Time" +pTime
+ "]";
}
// getting ID
public int getID(){
return this.id;
}
// setting id
public void setID(int id){
this.id = id;
}
// getting pLong
public double getpLong(){
return this.pLong;
}
// setting pLong
public void setpLong(double pLong){
this.pLong = pLong;
}
// getting pLat
public double getpLat(){
return this.pLat;
}
// setting pLat
public void setpLat(double pLat){
this.pLat = pLat;
}
// getting pAcc
public float getpAcc(){
return this.pAcc;
}
// setting pAcc
public void setpAcc(float pAcc){
this.pAcc = pAcc;
}
// getting pTime
public long getpTime(){
return this.pTime;
}
// setting pTime
public void setpTime(long pTime){
this.pTime = pTime;
}
}
and the activity which creates the db :
MySQLiteHelper.java
package com.program.android.taskir;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.LinkedList;
import java.util.List;
public class MySQLiteHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "RecordsDB";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create record table
String CREATE_RECORD_TABLE = "CREATE TABLE RECORD ( " +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"latitude TEXT NOT NULL, " +
"longtitude TEXT NOT NULL, " +
"accuracy TEXT NOT NULL, " +
"time TEXT NOT NULL )";
// create books table
db.execSQL(CREATE_RECORD_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older books table if existed
db.execSQL("DROP TABLE IF EXISTS Records");
// create fresh record table
this.onCreate(db);
}
// Books table name
private static final String TABLE_RECORD = "record";
// Books Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_LONG = "longtitude";
private static final String KEY_LAT = "latitude";
private static final String KEY_ACC = "accuracy";
private static final String KEY_TIME = "time";
private static final String[] COLUMNS = {KEY_ID, KEY_LONG, KEY_LAT, KEY_ACC, KEY_TIME};
public void addRecord(Record record) {
//for logging
Log.d("addBook", record.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(KEY_LONG, record.getpLong());
values.put(KEY_LAT, record.getpLat());
values.put(KEY_ACC, record.getpAcc());
values.put(KEY_TIME, record.getpTime());
// 3. insert
db.insert(TABLE_RECORD, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
// 4. close
db.close();
}
public Record getRecord(int id) {
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_RECORD, // a. table
COLUMNS, // b. column names
" id = ?", // c. selections
new String[]{String.valueOf(id)}, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
// 4. build book object
Record record = new Record();
record.setID(Integer.parseInt(cursor.getString(0)));
record.setpLat(cursor.getDouble(1));
record.setpLong(cursor.getDouble(2));
record.setpAcc(cursor.getFloat(2));
record.setpTime(cursor.getLong(2));
//log
Log.d("getBook(" + id + ")", record.toString());
// 5. return book
return record;
}
public List<Record> getAllRecords() {
List<Record> records = new LinkedList<Record>();
// 1. build the query
String query = "SELECT * FROM " + TABLE_RECORD;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each row, build book and add it to list
Record record = null;
if (cursor.moveToFirst()) {
do {
record = new Record();
record.setID(Integer.parseInt(cursor.getString(0)));
record.setpLat(cursor.getDouble(1));
record.setpLong(cursor.getDouble(2));
record.setpAcc(cursor.getFloat(2));
record.setpTime(cursor.getLong(2));
// Add book to books
records.add(record);
} while (cursor.moveToNext());
}
Log.d("getAllRecords()", record.toString());
// return books
return records;
}
public int UpdateRecords(Record record) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("Latitude", record.getpLat()); //
values.put("Longtitude", record.getpLong());
values.put("Accuracy", record.getpAcc());
values.put("Time", record.getpTime());
// 3. updating row
int i = db.update(TABLE_RECORD, //table
values, // column/value
KEY_ID + " = ?", // selections
new String[]{String.valueOf(record.getID())}); //selection args
// 4. close
db.close();
return i;
}
public void deleteRecords(Record record) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete(TABLE_RECORD, //table name
KEY_ID + " = ?", // selections
new String[]{String.valueOf(record.getID())}); //selections args
// 3. close
db.close();
//log
Log.d("deleteBook", record.toString());
}
}
Thank you!
What you are looking for is a Bundle. It's used to pass data between activities. Take a look at What is a "bundle" in an Android application and you can understand how it's done.

Only allow unique data entry with Android SQLite?

Before I get into describing by problem I'd like to point out I am aware of the other threads asking this question, however none for me have been able to solve my issue.
I've been working on a sharing app using the BumpAPI, which upon receiving the chunk, saves it to an SQLite database for retrieval in a list view activity, this is all working fine and the data is saved, however if the same text is sent twice it will be saved again and again and the list view will show this, from what I've read I need the 'UNIQUE' identifier? however being completely new to SQL I am at a loss with regards to achieving this, here is my DataHelper class which im using to create and add the entries, would anyone be kind enough to modify it or inform me of a possible solution?
Thanks very much
public class DataHelper {
private static final String DATABASE_NAME = "tags.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "TagTable";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public List<String> selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)" + "text unique, " + "ON CONFLICT REPLACE");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Add the unique keyword to the column.
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT unique);
looks like you should first add unique index on Table Create statement
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)" + "**name** unique, " + "ON CONFLICT REPLACE");
it will prevent from having two entries with the same names
the second you could make select to check for existence of the data before making actually insert

Categories