handling table in SQLITE (android) - java

I want to manage (create/delete/update) a table with 18 columns. Normally, for creating table, I use below codes. Is there any smarter way, like putting the column names in an array etc.? How people handle large tables?
Thanks for your help, as always.
private static final String COL1 = "col1";
private static final String COL2 = "col2";
private static final String COL3 = "col3";
........
........
private static final String COL18 = "col18";
public dbhandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ COL1 + " INTEGER PRIMARY KEY," + COL2 + " TEXT,"
+ COL3 + " TEXT," + .............................+ COL18 + " TEXT")";
db.execSQL(CREATE_TABLE);
}

A smarter way doing so is using db4o (database 4 objects). While creating a database like this has the following advantages:
It is purely based on object database.
No such mapping of tables like in sqlite.
Saves time and volume of code.
Reuse objects by saving and retrieving them as many times as you want.
Benefit from Native Queries.
For more info refer to: http://www.sohailaziz.com/2012/09/using-database-for-objects-db4o-in.html

You can make tuples (column name and type), and store these in an Array. In the onCreate you can loop over it and add it to the CREATE_TABLE string.
But unless you are going to change the columns a lot, a simple copy and paste of lines is more than enough.

If you are use the large table the best way is use the SQLiteManager browser. Remaining all operation do in the normal .java file.If you are use 2 or more table use the SQLiteManager plug-in.

Related

Can't add row to DB using ContentValues.insert() Android Studio (SQLiteLog: (1) no such table: ....)

I'm newbie with Java and Android Studio.I'm currently trying to create a to do list application. For that, I need to store the user's input into a database. However I can create the database and the table without any problem. But each time I try to add new row into the database, an error occurs.
D/DatabaseHandler: ===Inside DatabaseHandler constructor===
D/DatabaseHandler: ===Inside onCreate from DatabaseHandler===
D/MainActivity: ==addToDatabase==
/SQLiteLog: (1) no such table: test_database
E/SQLiteDatabase: Error inserting STATE=14 TASK=13 ID =1
android.database.sqlite.SQLiteException: no such table: test_database (code 1): , while compiling: INSERT INTO test_database(STATE,TASK,ID ) VALUES (?,?,?)
create the database (DatabaseHandler) and create the table (onCreate()):
public class DatabaseHandler extends SQLiteOpenHelper {
public DatabaseHandler(Context context) {
super(context, "test_database", null, 1);
Log.d(TAG, "===Inside DatabaseHandler constructor===");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "===Inside onCreate from DatabaseHandler===");
// String database_table = "CREATE TABLE task(" + COLUMN_ID + " INT NOT NULL," + COLUMN_TASK + " INT NOT NULL," + COLUMN_STATE + " INT NOT NULL)";
String database_table = "CREATE TABLE task(ID INT NOT NULL, TASK INT NOT NULL, STATE INT NOT NULL)";
db.execSQL(database_table);
}
}
and finally the function I used for add new row into the DB:
public int addToDatabase(SQLiteDatabase access, String task) {
Log.d(TAG, "==addToDatabase==");
if (access.isOpen() == false) {
Log.d(TAG, "[addToDatabase] Database is not Open");
return (-1);
}
ContentValues values = new ContentValues();
values.put("ID ", 1);
values.put("TASK", 13);
values.put("STATE", 14);
access.insert("test_database", null, values);
return (1);
I already try to solve the problem by myself by looking on the other existing post. It seem that it may be cause because the database wasn't create correctly. Nonetheless as you can there's any error while creating the database, only when I'm trying to add new stuff.
I also read that it could be in report with the version of the database...However, I don't really understand why..(I'm still looking into the official documentation).
Does anyone can explain me and tell me how can I fix the problem ?
Thanks :)
Use this
access.insert("task", null, values)
instead of this
access.insert("test_database", null, values);
or
if you have updated your app table name then uninstall your app manually and try running again.
Your table name is apparently wrong. Change the table creation query.
String database_table = "CREATE TABLE test_database(ID INT NOT NULL, TASK INT NOT NULL, STATE INT NOT NULL)";
This might help you Android Sqlite Database Tutorial
You may edit your "DatabaseHandler" and run the project so that the change in your database doesn't occur.
I simply removed data from the application, to be opened for the first time
and it worked for we:

SQLite Manager not correctly generating query

This is my query and associative variables:
public static final String DATABASE_NAME = "HDL_db";
public static final String TABLE_NAME = "HDL_table";
public static final String COL_3 = "Arrival_Time";
public static final int database_version = 1;
public String CREATE_QUERY = "CREATE TABLE " + TABLE_NAME + " (" +
COL_3 + " DATE)";
This is the resultant query format in SQLite Manager (Mozilla Firefox add-on):
CREATE TABLE HDL_table(Arrival TimeDATE)
should be:
CREATE TABLE HDL_table (Arrival_Time DATE) [based on spaces I have added in original query]
and so leaves me with the following table structure in SQLite Manager:
SQLite Manager Table Structure
I want to have the 'Name' column set to 'Arrival_Time' and the 'Type' set to 'DATE' .. because it will be a date that workers arrive on site.
Personally, I think the spaces in the query are the problem, however when I add in the spaces in the original query, export and run the database file through SQLite Manager and check the resultant table structure .. it is in the wrong format.
Any help with this would be great, thanks.
In your column's name must not contain spaces. SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
"CREATE TABLE IF NOT EXISTS HDL_table (_id integer primary key, arrival_time text)"
Source: https://www.sqlite.org/datatype3.html

SQLite Table not being created

I have a database created in android studio to save data to . The table is not being created in the database . The error I'm getting is :
03-04 00:55:45.783 25787-25787/com/SQLiteLog: (1) no such table: TableName
03-04 00:55:45.783 25787-25787/com.E/SQLiteDatabase: Error inserting
My code for creating the table is :
#Override
public void onCreate(SQLiteDatabase db) {
db = SQLiteDatabase.openOrCreateDatabase("DB.ad",null);
Log.v(TAG, "*TABLE ");
// create TableName table
db.execSQL(CREATE_TableName_TABLE);
this.checkDataBase();
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
// database doesn't exist yet.
}
return checkDB != null;
}
I was wondering if anyone can tell me why I am getting this error?
String CREATE_TableName_TABLE = "CREATE TABLE TableNames( " +
"Id INT( 30 ) PRIMARY KEY AUTOINCREMENT, " +
"TagNo TEXT, " +
"Description TEXT, " +
"WeeksGone INTEGER( 10 ) NOT NULL DEFAULT 0 );";
Here is an example how to create your database. First your class should extends from SQLiteOpenHelper
Then use super to SQLiteOpenHelper class with your db name and version,
public YourClassName(Context context) {
super(context, "YourDatabaseName", null, 1); // 1 is the version of the database, after each change in your db you should ++.
}
Then create your table:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_BLABLA_TABLE = "CREATE TABLE " + "TableNameHere" + " (" +
"_id" + " INTEGER PRIMARY KEY," +
"name" + " TEXT NOT NULL);";
sqLiteDatabase.execSQL(SQL_CREATE_BLABLA_TABLE);
}
And finally in case you need to upgrade your db version, because you make any change override the onUpgrade method, in order to create again the table.
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + "TableNameHere");
onCreate(sqLiteDatabase);
}
For more information of how to implement SQLite please read this.
Please review the following types in order to create your table:
1.0 Storage Classes and Datatypes
Each value stored in an SQLite database (or manipulated by the database engine) has one of the following storage classes:
NULL. The value is a NULL value.
INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).
BLOB. The value is a blob of data, stored exactly as it was input.
For more information of datatypes please see this link.
So your table should be create like this:
String CREATE_TableName_TABLE = "CREATE TABLE TableNames (Id INTEGER PRIMARY KEY AUTOINCREMENT, TagNo TEXT,
Description TEXT, WeeksGone INTEGER NOT NULL DEFAULT 0 );";

SQLite One-to-Many Relationship Set/Get Foreign Key

I am building an android app project with SQLite DB.
I got stuck on One-To-Many RelationShip.
This is One
private static final String createTableOrders =
"CREATE TABLE " + TABLE_ORDER + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
...
+ KEY_COLUMN_FORMATS + " INTEGER REFERENCES " + TABLE_FORMATS + "(" + KEY_ID + ")"
+ ");";
This is Many
private static final String createTableFormats =
"CREATE TABLE " + TABLE_FORMATS + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
...
+ ");";
My problems is with set/get methods.
Lets say that I would need to get list of ids of all Formats that are in one Order.
I guess same thing goes for set method.
I tried to find this kind of question on SO but most of the question were just for SQL part.
P.S. Spent 3 hours trying to make it by myself but the only thing I got to was using GSON to code list of ids into String but it was just a dead-end.
EDIT: I need to get that information inside the code.
P.S.S I have been doing this for 18 hours so sorry if this is uber-stupid question.
A one-to-many relationship requires the foreign key column in the "many" table:
CREATE TABLE Orders (
ID PRIMARY KEY
);
CREATE TABLE Formats (
ID PRIMARY KEY,
OrderID REFERENCES Orders(ID)
);
To get all formats belonging to an order, you just look up rows with the ID of that order:
SELECT * FROM Formats WHERE OrderID = ?
In Jave:
Cursor cursor = db.query(TABLE_FORMATS,
new String[] { whatever columns you need },
"OrderID = " + orderID,
null, null, null, null, null);
while (cursor.moveToNext()) {
// read one order from the cursor
}
cursor.close();

Synax Error When Trying To Create SQLite Database

I am receiving this error when trying to create my database Failure 1 (near "CREATE_TABLE": syntax error) on 0x367f80 when preparing 'CREATE_TABLE cattletypes (_id INTEGER PRIMARY KEY AUTOINCREMENT , cattle_type TEXT);'.
The code I use is
db.execSQL("CREATE_TABLE " + CattleType.CATTLETYPE_TABLE_NAME + " ("
+ CattleType._ID + " INTEGER PRIMARY KEY AUTOINCREMENT , "
+ CattleType.CATTLE_TYPE_NAME + " TEXT"
+ ");");
I've been reading it and rereading it and can't for the life of me figure out where my error is -
my class code is
public static final class CattleType implements BaseColumns{
private CattleType() {}
public static final String CATTLETYPE_TABLE_NAME = "cattletypes";
public static final String CATTLE_TYPE_NAME = "cattle_type";
public static final String DEFAULT_SORT_ORDER = "cattle_type ASC";
}
What am I missing?
Thanks
There is a '_' between CREATE and TABLE. Remove that and it should work.
Remove the _ between CREATE and TABLE.
As I mentioned in my comment, an extraneous underscore has found its way between CREATE and TABLE.

Categories

Resources