Java, SQLite, Insert data to Database - java

I have a SQLite database, with these parameters
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String COL3 = "anything";
Here's how it's created:
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT, " + COL3 + "TEXT)" ;
I'm trying to add data to the db, for both columns, my code is here:
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, "item");
contentValues.put(COL3, "item2");
long result = db.insert(TABLE_NAME,null,contentValues);
if (result > 0) {
return true;
} else {
return false;
}
But it is not working, I have no idea why.
Please, any advice?

Your issue is that you have omitted a space so there is no column named anything, but instead a column named anythingTEXT
Change to use :-
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT, " + COL3 + " TEXT)" ;
Then delete the App's data, or uninstall the App and rerun.
This is required as the onCreate method only runs when the database is first created.

Related

Can't insert Data on SQLite Database Android

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

SQL - How to return a list of data

I have this SQL method below, it is suppose to return multiple rows of data, but it is only returning one item every time I try to display the data.
How do I fix that?
//Constant
public static final String COL_4 = "LikeSong";
//Database Table
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE UserInfo(ID INTEGER PRIMARY KEY AUTOINCREMENT, Users_Name TEXT, PlaylistName TEXT,likeAlbum TEXT,LikeSong TEXT)");
}
public String[] getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
String[] LikeSong = null;
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong = note.split(",");
}
cursor.close();
db.close();
return LikeSong;
}
Inside the while loop in each iteration you change the value of LikeSong, so when the loop ends, LikeSong has the last value assigned to it.
I think that you want a list of arrays returned by your method getLikedSongs() like this:
public List<String[]> getLikedSongs() {
SQLiteDatabase db = this.getReadableDatabase();
List<String[]> list = new ArrayList<>();
Cursor cursor = db.rawQuery(" SELECT " + COL_4 + " FROM " + Table_Name + " WHERE " + COL_4 + " IS NOT NULL", null);
while (cursor.moveToNext()) {
String note = cursor.getString(0);
LikeSong.add(note.split(","));
}
cursor.close();
db.close();
return LikeSong;
}
Okay...now I see. You are reassigning LikeSong for each iteration of the while loop and returning the String array after the while loop has completed. So obviously, you will get value of only the last row.

Foreign key in SQLite

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+"));";

Using SQLite in Android to get RowID

I am creating an app to record assignments for different classes. Each class has it's own unique ID so the assignments listed for each class don't overlap into other classes. Here is a method I made to find the rowid for a certain class.
public int getIdFromClassName(String className){
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
return res.getColumnIndex("id");
}
However, this always returns a value of -1.
Any thoughts on what to change to return the proper rowid value?
EDIT:
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table " + CLASSES_TABLE_NAME + " " +
"(id integer primary key, " + CLASSES_COLUMN_NAME + " text)"
);
db.execSQL(
"create table " + ASSIGNMENTS_TABLE_NAME + " " +
"(id integer primary key, " + ASSIGNMENTS_COLUMN_NAME + " text, " + ASSIGNMENTS_COLUMN_TOTAL_POINTS
+ " INTEGER, " + ASSIGNMENTS_COLUMN_CLASS_ID + " INTEGER)");
}
Try this query below to create a new column name rowID:
Cursor cursor= db.rawQuery("SELECT *,"+CLASSES_TABLE_NAME +".rowid AS rowID"+" FROM "+CLASSES_TABLE_NAME , null);
And after this query you can fetch the real rowid from the rowID column :
while (cursor.moveToNext()) {
long chatRow=cursor.getLong(
cursor.getColumnIndexOrThrow("rowID"));
}
The column returned by your query is called rowid, so you will not find a column called id.
Ensure that you use the same column name in the query and in the call to getColumnIndex.
And the index of this column is always zero; you also need to read the actual value from the column:
int colIndex = res.getColumnIndexOrThrow("rowid"); // = 0
if (res.moveToFirst()) {
return res.getInt(colIndex);
} else {
// not found
}
However, Android has an helper function that makes it much easier to read a single value:
public int getIdFromClassName(String className){
String query = "SELECT rowid" +
" FROM " + CLASSES_TABLE_NAME +
" WHERE " + CLASSES_COLUMN_NAME + " = ?;";
SQLiteDatabase db = this.getReadableDatabase();
return DatabaseUtils.longForQuery(db, query, new String[]{ className });
}
res.getColumnIndex("id") is going to get you the column index of the column with the name "id". and since you are getting -1, it cant find it.. are you sure your id column is not "_id"?
To get this to work you should do something like this..
res.getLong(res.getColumnIndex("_id"));
Cursor.getColumnIndex()
Cursor.getLong()
(I would recommend you use getLong() rather than getInt() because SQLite database ID's can get larger than int's).
You can try this:
public int getIdFromClassName(String className){
String query = "SELECT id FROM " + CLASSES_TABLE_NAME + " WHERE " + CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
int id=-1;
If(res!=null&&res.moveToFirst())
id=res.getInt(res.getColumnIndex("id"));
return id;
}
public int getIdFromClassName(String className) {
String query = "SELECT rowid FROM " + CLASSES_TABLE_NAME + " WHERE "
+ CLASSES_COLUMN_NAME + " = '" + className + "'";
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery(query, null);
if (res != null) {
if (res.moveToFirst()) {
do {
return Integer.parseInt(res.getString(res.getColumnIndex("id"))); // if your column name is rowid then replace id with rowid
} while (res.moveToNext());
}
} else {
Toast.makeText(context, "cursor is null", Toast.LENGTH_LONG).show();
}
}
Check your Cursor if its null check your Log that your table is created successfully and if its not null make sure your table has column id in it.

Android, Multiple Tables, SQLite Database

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

Categories