I'm getting error like this while inserting item details :
09-28 16:30:32.558 9471-9471/com.example.android.inventoryapp E/SQLiteDatabase: Error inserting quantity=1 name=Chocolate phone num=9112 price=5 supp name=Venu
android.database.sqlite.SQLiteException: near "num": syntax error (code 1): , while compiling: INSERT INTO inventory(quantity,name,phone num,price,supp name) VALUES (?,?,?,?,?)
DATABASE HELPER is:
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String SQL_CREATE_PRODUCTS_TABLE = "CREATE TABLE " + InventoryContract.InventoryEntry.TABLE_NAME + " ("
+ InventoryContract.InventoryEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ InventoryContract.InventoryEntry.COLUMN_Product_Name + " TEXT NOT NULL, "
+ InventoryContract.InventoryEntry.COLUMN_PRICE + " INTEGER NOT NULL, "
+ InventoryContract.InventoryEntry.COLUMN_Quantity + " INTEGER NOT NULL DEFAULT 0, "
+ InventoryContract.InventoryEntry.COLUMN_SUPPLIER_NAME + " TEXT NOT NULL, "
+ InventoryContract.InventoryEntry.COLUMN_SUPPLIER_Phno + " INTEGER NOT NULL);";
// Execute the SQL statement
//COLUMN_USERNAME + " TEXT "
sqLiteDatabase.execSQL(SQL_CREATE_PRODUCTS_TABLE);
}
Contract class is:
public final static class InventoryEntry implements BaseColumns{
public final static String TABLE_NAME="inventory";
public final static String _ID = BaseColumns._ID;
public final static String COLUMN_Product_Name="name";
public final static String COLUMN_PRICE="price";
public final static String COLUMN_Quantity="quantity";
public final static String COLUMN_SUPPLIER_NAME="supp name";
public final static String COLUMN_SUPPLIER_Phno="phone num";
}
logcat response is:
com.example.android.inventoryapp E/SQLiteLog: (1) near "num": syntax error
09-28 16:30:32.558 9471-9471/com.example.android.inventoryapp E/SQLiteDatabase: Error inserting quantity=1 name=Chocolate phone num=9112 price=5 supp name=Venu
android.database.sqlite.SQLiteException: near "num": syntax error (code 1): , while compiling: INSERT INTO inventory(quantity,name,phone num,price,supp name) VALUES (?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.android.inventoryapp.CatalogActivity.insertpet(CatalogActivity.java:104)
at com.example.android.inventoryapp.CatalogActivity.onOptionsItemSelected(CatalogActivity.java:118)
at android.app.Activity.onMenuItemSelected(Activity.java:2885)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:407)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)`
Column names can't have spaces in them. If you want to use spaces, like you do with phone num, you should escape the names by surrounding them with double quotes ("):
INSERT INTO inventory("quantity", "name", "phone num", "price", "supp name")
VALUES (?, ?, ?, ?, ?)
Create a method and write the code to insert the data into table as below...
public boolean insertPetition1(String cap_date, String cap_time, String image_str, String latitude, String longitude,
String upload_status) {
SQLiteDatabase db = getWritableDatabase();
try {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_IMAGE_PATH, image_str);
contentValues.put(COLUMN_CAPTURE_DATE, cap_date);
contentValues.put(COLUMN_CAPTURE_TIME, cap_time);
contentValues.put(COLUMN_LATITUDE, latitude);
contentValues.put(COLUMN_LONGITUDE, longitude);
contentValues.put(COLUMN_UPLOAD_STATUS, upload_status);
if (db.insert(MAIN_TABLE, null, contentValues) > 0) {
Log.e("Parameters", "Parameters:" + contentValues);
isInserted = true;
}
} catch (Exception e) {
Log.v("TAG", e.toString());
}
return isInserted;
}
Call this method where ever you want to insert data in the tabel ....
public void dbChanges() {
DatabaseHelper1 databaseMain = new
DatabaseHelper1(OfflineAttendanceChildWithOutAuto.this);
boolean status = false;
status = databaseMain.insertPetition1(date, currentTime, encodedImage, latitude, longitude, "", "", "", awccode, "", "", mainaddress, usercode, "", "", "1");
databaseMain.close();
}
It will work for sure try like this....
Related
This question already has an answer here:
android.database.sqlite.SQLiteException: no such column or name
(1 answer)
Closed 3 months ago.
I am stuck on an "SQLiteException: no such column:" error. I am trying to make some code to check if an item exists in the database before storing it, I don't know if it's the best way or not but it does the job. Or not really, when I use all numbers for the data in the particular column that I'm searching it works fine. But if there is any letter in the column data it crashes.
The MainActivity
private ConversationsDatabaseHelper db;
//onCreate stuff here
db = new ConversationsDatabaseHelper(this);
String threadId = "886";
Log.d(TAG, "dbTest: EXISTS; " + db.conversationExists(threadId));
and in the databaseHelper class is the converstionExists function
public boolean conversationExists(String threadId) {
// Select All Query
String selectQuery = "SELECT * FROM " + Conversations.TABLE_NAME + " WHERE " +
Conversations.COLUMN_THREAD_ID + " LIKE " + threadId;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
boolean returnValue = false;
// Check if this message exists
if (cursor.moveToFirst()) {
returnValue = true;
}
// close db connection
db.close();
return returnValue;
}
So if I use for example "886" as the threadId value then all is fine. If I create a row with matching threadId then it returns true. In this case I did not so hence false.
stack trace...
dbTest: EXISTS; false
but using a886 results in
Caused by: android.database.sqlite.SQLiteException: no such column: a886 (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM conversations WHERE thread_id LIKE a886
and 88a6 results in this
Caused by: android.database.sqlite.SQLiteException: unrecognized token: "88a6" (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM conversations WHERE thread_id LIKE 88a6
It almost looks like mixing letters and numbers might be part of the reason here but should not be as the column was created to hold TEXT datatype. here is the database create table query string.
public static final String TABLE_NAME = "conversations";
public static final String COLUMN_ID = "id";
public static final String COLUMN__ID = "_id";
public static final String COLUMN_GROUP_ID = "group_id";
public static final String COLUMN_LAST_MESSAGE_ID = "last_message_id";
public static final String COLUMN_THREAD_ID = "thread_id";
public static final String COLUMN_ADDRESS = "address";
public static final String COLUMN_CONTACT = "contact";
public static final String COLUMN_BODY = "body";
public static final String COLUMN_DATE = "date";
public static final String COLUMN_TYPE = "type";
public static final String COLUMN_STATE = "state";
public static final String COLUMN_READ = "read";
public static final String COLUMN_STATUS = "status";
public static final String COLUMN_CT = "ct";
// Create table SQL query
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY ,"
+ COLUMN_LAST_MESSAGE_ID + " TEXT,"
+ COLUMN__ID + " TEXT,"
+ COLUMN_GROUP_ID + " TEXT,"
+ COLUMN_THREAD_ID + " TEXT,"
+ COLUMN_ADDRESS + " TEXT,"
+ COLUMN_CONTACT + " TEXT,"
+ COLUMN_BODY + " TEXT,"
+ COLUMN_DATE + " TEXT,"
+ COLUMN_TYPE + " TEXT,"
+ COLUMN_STATE + " TEXT,"
+ COLUMN_READ + " TEXT,"
+ COLUMN_STATUS + " TEXT,"
+ COLUMN_CT + " TEXT"
+ ")";
I am "up a creek" with this and any help would be greatly appreciated.
The value a886 should be a text/string literal not a numeric literal. Therefore it should be enclosed in single quotes. The errors are because:-
a886 fails with no column found as it's taken to be a column name as it's not a literal.
whilst 88a6 is first not a valid literal (due to the a) and therefore a column name but then an invalid column (cannot start with a numeric unless enclosed) name and thus not a known token.
See Literal Values (Constants)
You could fix this using (enclosing the threadId in single quotes ) :-
String selectQuery = "SELECT * FROM " + Conversations.TABLE_NAME + " WHERE " +
Conversations.COLUMN_THREAD_ID + " LIKE '" + threadId + "'";
However, it is recommended to use bound parameters to protect against SQL Injection.
Thus it would be recommended to use :-
String selectQuery = "SELECT * FROM " + Conversations.TABLE_NAME + " WHERE " +
Conversations.COLUMN_THREAD_ID + " LIKE ?";
along with :-
Cursor cursor = db.rawQuery(selectQuery, new String[]{threadId});
i.e. the ? is replaced by the threadId value properly enclosed.
You may wish to consider using the convenience query method rather than rawQuery, this would be :-
Cursor cursor = db.query(Conversations.TABLE_NAME,null,Conversations.COLUMN_THREAD_ID + " LIKE ?", new String[]{theadId},null,null, null);
The SQL is built for you.
It almost looks like mixing letters and numbers might be part of the reason here but should not be as the column was created to hold TEXT datatype.
SQlite has no issue storing any value in any type. The type, which itself can be virtually anything (rules are used to determine the resultant type), is only an indication of the value that will be stored. The only exception is that a rowid or an alias of the rowid MUST be an integer value (your id column is an alias of the rowid column).
This might be impossible but I couldn't seem to find a clear answer. When I delete a row in my database I want the other row's IDs to essentially move up, so if I deleted row 2, then row 3's ID would become 2. Is this possible? I am using AUTOINCREMENT so didn't know if there was almost a reverse of that?
Here is my full SQLite Code.
public class ProfileDatabaseHelper extends SQLiteOpenHelper {
public static final String PROFILE_TABLE = "PROFILE_TABLE";
public static final String PROFILE_ID = "ID";
public static final String PROFILE_IMAGE = "PROFILE_IMAGE";
public static final String RADAR_DATA_ONE = "DATA_ONE";
public static final String RADAR_DATA_TWO = "DATA_TWO";
public static final String RADAR_DATA_THREE = "DATA_THREE";
public static final String RADAR_DATA_FOUR = "DATA_FOUR";
public static final String RADAR_DATA_FIVE = "DATA_FIVE";
public static final String RADAR_DATA_SIX = "DATA_SIX";
public ProfileDatabaseHelper(#Nullable Context context) {
super(context, "profiles.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + PROFILE_TABLE + " (" + PROFILE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + PROFILE_IMAGE + " TEXT, "
+ RADAR_DATA_ONE + " INT, " + RADAR_DATA_TWO + " INT, " + RADAR_DATA_THREE + " INT, " + RADAR_DATA_FOUR + " INT, " + RADAR_DATA_FIVE
+ " INT, " + RADAR_DATA_SIX + " INT)";
db.execSQL(createTableStatement);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean updateData(Integer id,String profilePhoto,Integer dataOne, Integer dataTwo, Integer dataThree, Integer dataFour, Integer dataFive, Integer dataSix){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(PROFILE_ID,id);
contentValues.put(PROFILE_IMAGE,profilePhoto);
contentValues.put(RADAR_DATA_ONE,dataOne);
contentValues.put(RADAR_DATA_TWO,dataTwo);
contentValues.put(RADAR_DATA_THREE,dataThree);
contentValues.put(RADAR_DATA_FOUR,dataFour);
contentValues.put(RADAR_DATA_FIVE,dataFive);
contentValues.put(RADAR_DATA_SIX,dataSix);
db.update(PROFILE_TABLE,contentValues,"ID = ?",new String[] {id.toString()});
return true;
}
public boolean addOne(ProfileModel profileModel){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(PROFILE_IMAGE, profileModel.getProfilePhoto());
cv.put(RADAR_DATA_ONE, profileModel.getDataOne());
cv.put(RADAR_DATA_TWO, profileModel.getDataTwo());
cv.put(RADAR_DATA_THREE, profileModel.getDataThree());
cv.put(RADAR_DATA_FOUR, profileModel.getDataFour());
cv.put(RADAR_DATA_FIVE, profileModel.getDataFive());
cv.put(RADAR_DATA_SIX, profileModel.getDataSix());
long insert = db.insert(PROFILE_TABLE, null, cv);
if (insert == -1){
return false;
}
else{
return true;
}
}
public Cursor alldata(){
SQLiteDatabase dataBaseHelper = this.getWritableDatabase();
Cursor cursor = dataBaseHelper.rawQuery("select * from PROFILE_TABLE ", null);
return cursor;
}
public boolean delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
String queryString = "DELETE FROM " + PROFILE_TABLE + " WHERE " + PROFILE_ID + " = " + id;
//deleting row
Cursor cursor = db.rawQuery(queryString, null);
if(cursor.moveToFirst()){
return true;
}
else {
return false;
}
}
}
I am using AUTOINCREMENT so didn't know if there was almost a reverse of that?
First AUTOINCREMENT doesn't increase the rowid (or alias thereof) value rather it is a constraint (rule) that says that the rowid MUST be greater than any that have ever been allocated (if sqlite_sequence hasn't been modified outside of SQLite's management of the table).
It is using INTEGER PRIMARY KEY that allows a value, typically 1 greater than the highest current rowid value, to be automatically assigned. However, if the value + 1 is greater than the maximum possible value (9223372036854775807) then :-
With AUTOINCREMENT you get an SQLITE_FULL error.
Without AUTOINCREMENT attempts are made to find an unused number.
It is extremely unlikely that (9223372036854775807) will be reached/used.
AUTOINCREMENT is less efficient as it has to record the highest ever assigned rowid and does so by using the sqlite_sequence table. In the SQLite documentation it says :-
The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.
see SQLite Autoincrement
It is a very bad idea to utilise the rowid or an alias thereof for anything other than it's intended use that is for unique identifying a row from another row such as when forming a relationship, updating or deleting a row.
e.g. what if you sort (ORDER BY) the data by another column or columns other than the ID column? Does the id have any meaning to a user of the App?
However, even though this it NOT recommended, the following would do what you wish :-
private void rationaliseCol1Values() {
ContentValues cv = new ContentValues();
Cursor csr = mDB.query(PROFILE_TABLE,null,null,null,null,null,PROFILE_ID + " ASC");
int rowcount = csr.getCount();
long expected_id = 1;
long current_id;
String where_clause = PROFILE_ID + "=?";
String[] args = new String[1];
while (csr.moveToNext()) {
current_id = csr.getLong(csr.getColumnIndex(PROFILE_ID));
if (current_id != expected_id) {
cv.clear();
cv.put(PROFILE_ID,expected_id);
args[0] = String.valueOf(current_id);
mDB.update(PROFILE_TABLE,cv,where_clause,args);
}
expected_id++;
}
csr.close();
// Now adjust sqlite_sequence
where_clause = "name=?";
args[0] = PROFILE_TABLE;
cv.clear();
cv.put("seq",String.valueOf(rowcount));
mDB.update("sqlite_sequence",cv,where_clause,args);
}
Note the code has been taken from the answer here Android Studio Sqllite autoincrement reset
and has been amended to suit but has not been compiled or run and therefore may contain some errors.
My app works (generate a code and a relative barcode from some user's data in input), but I wanted to store data in a Db with sqlite. This is my DatabaseOpenHelper class:
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "cf_db.db";
public static final String TABLE_NAME = "cf_table";
public static final String CF = "CF";
public static final String COL1 = "Name";
public static final String COL2 = "Surname";
public static final String COL3 = "Sex";
public static final String COL4 = "Birthday";
public static final String COL5 = "PlaceOfBirth";
public DatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
//SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME +
"(" + CF + "TEXT PRIMARY KEY, " + COL1 + "TEXT NOT NULL, " +
COL2 + "TEXT NOT NULL," + COL3 + "TEXT NOT NULL," + COL4 +
"TEXT NOT NULL," + COL5 + "TEXT NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(String cf, String name, String surname, String sex, String year,
String month, String day, String place) {
String date = day + "/" + month + "/" + year;
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(CF, cf);
contentValues.put(COL1, name);
contentValues.put(COL2, surname);
contentValues.put(COL3, sex);
contentValues.put(COL4, date);
contentValues.put(COL5, place);
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
}
}
There is something wrong with the insert statement at the end. I got below error:
E/SQLiteLog: (1) table cf_table has no column named Birthday
E/SQLiteDatabase: Error inserting Birthday=22/08/21 CF=GGUTUU21M22I754G Surname= ggu Name=uut Sex=M PlaceOfBirth=Siracusa
android.database.sqlite.SQLiteException: table cf_table has no column named Birthday (code 1 SQLITE_ERROR): , while compiling: INSERT INTO cf_table(Birthday,CF,Surname,Name,Sex,PlaceOfBirth) VALUES (?,?,?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:901)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:512)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1562)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at com.example.valerio.androidcodesgenerator.DatabaseOpenHelper.insertData(DatabaseOpenHelper.java:53)
at com.example.valerio.androidcodesgenerator.MainActivity.AddData(MainActivity.java:136)
at com.example.valerio.androidcodesgenerator.MainActivity$1.onClick(MainActivity.java:98)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25883)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6642)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
The columns are in a random order that I don't understand, and when I used some print statement to analyze the issue I realized that the various contentValues has no value at all. I just did
Log.d("code", contentValues.getAsString(cf))
And the error was like "println needs something to print", so basically the put statement of the contentValues doesn't put anything in. In fact in the error message the values are (??????)...
In the call instead the print tests goes well and the various editText and textView have their proper content.
This is the insertData call:
public void AddData() {
boolean inserted = myDb.insertData(textView_cf.getText().toString(),
editText_name.getText().toString(),
editText_surname.getText().toString(),
editText_sex.getText().toString(),
editText_aa.getText().toString(),
editText_mm.getText().toString(),
editText_gg.getText().toString(),
autoCompleteTextView_place.getText().toString());
}
(I also need a boolean control over the insertion, but the insertion just doesn't happen right now)
Maybe it's newbie errors but I'm just new at Android Studio and not a Java expert at all...
One thing you must do is uninstall the app from the emulator/device where you test it and then run it again to recreate the database. If it still shows the error about the Birthday field then the problem is somewhere else.
Use this insert method:
public boolean insertData(String cf, String name, String surname, String sex, String year,
String month, String day, String place) {
String date = day + "/" + month + "/" + year;
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(CF, cf);
contentValues.put(COL1, name);
contentValues.put(COL2, surname);
contentValues.put(COL3, sex);
contentValues.put(COL4, date);
contentValues.put(COL5, place);
int id = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
sqLiteDatabase.close();
return (id != -1);
}
I'm not sure that this will solve the problem, but by the signature of the method it must return boolean.
You are missing spaces in your CREATE TABLE statement
sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + "(" +
CF + " TEXT PRIMARY KEY, " +
COL1 + " TEXT NOT NULL, " +
COL2 + " TEXT NOT NULL, " +
COL3 + " TEXT NOT NULL, " +
COL4 + " TEXT NOT NULL, " +
COL5 + " TEXT NOT NULL)");
I am learing to code and made a stopwatch that saves the laptimes in a String and gets the date as a String as well. I want to put those in a SQLite database (so i can later display the date in a listview and open it in another activity that shows all the laptimes.) I've followed some of the codes on the internet and try to put stuff together so I might look over some things in my code. I've commented on the parts I think i understand so you can follow my thinking a bit.
The problem: when i press save the following code is executed and returns the toastmessage: Somehting went wrong.
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String dateStamp = getCurrentTimeStamp();
AddData(dataInput, dateStamp);
//DatabaseHelper.deleteAll();
}
}); //save data though AddData method as input the listText
The method AddData is as follows:
public void AddData(String time, String date) {
boolean insertData = DatabaseHelper.addData(time, date);
if (insertData) {
toastMessage(dataInput);
} else {
toastMessage("Something went wrong");
}
}
The boolean method in the DatabaseHelper class is this:
public boolean addData(String times, String date) { //addData that takes a string
SQLiteDatabase db = this.getWritableDatabase(); //database called db and use getWritableDatabase method
ContentValues contentValues = new ContentValues(); //make a new object of ContentValues
contentValues.put(COL_2, times); //put COL_2 and the String in the ContentValues object
contentValues.put(COL_3, date);
long result = db.insert(TABLE_NAME, null, contentValues); //insert contentValues object into the table
//if date as inserted incorrectly it will return -1
if (result == -1) {
db.close();
return false;
} else {
return true;
}
}
It works when i input just 1 variable in addData() but not with 2 that I later implemented. I think it should work. Below I also put the code that is used to make the SQLite Database.
public static final String TABLE_NAME = "stopwatch"; //make a table with name
public static final String COL_1 = "ID"; //make an ID for every colomn
public static final String COL_2 = "times"; //make a 2nd colomn for data
public static final String COL_3= "date";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) { //make the onCreate method that takes the database as input
String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_2 +" TEXT" + COL_3 +" TEXT)"; //create the table with SQL statements to input the data correctly
db.execSQL(createTable); //input the SQL statements in the DB
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //make upgrade method that takes the database and the versions
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME); //execute SQL statements drop table and which one
onCreate(db); //run through create method
}
I hope someone can help me to find the problem so I can learn more.
Your create table query is missing a comma after the COL_2 +" TEXT"
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_2 +" TEXT, " + COL_3 +" TEXT)"; // Added a comma after the COL_2
db.execSQL(createTable);
}
I can see one problem from a quick glance and that is a missing comma in your creation statement which would mean that your database was not created as you intended. Try the below amendment.
String createTable = "CREATE TABLE " + TABLE_NAME + " ( " + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_2 +" TEXT," + COL_3 +" TEXT)";
So i have this app I'm making for my school project. it has a custom listview with a custom arrayadapter and it's populated by clicking a button. here is the Room class
public class Room {
private int xBtn;
private int _id;
private int roomImage;
private String name;
private String type;
public Room(String name, String type, int roomImage){
this.name = name;
this.type = type;
this.roomImage = roomImage;
}
here is my DBHandling onCreate(), addRoom() and deleteRoom() Methods:
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_TYPE + " TEXT " +
");";
db.execSQL(query);
}
public void addRoom(Room room){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, room.getName());
values.put(COLUMN_TYPE, room.getType());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
public void removeRoom(String roomsName){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_NAME + "=\"" + roomsName + "\";");
}
My questing is, let say, we have 5 rooms, room1(id=0), room2(id=1) and so on.
and i delete room room3(#2) will the new order become 0,1,3,4 or 0,1,2,3.
if it didn't become 0,1,2,3 , how can i make it work? and if it did become 0,1,2,3 , will the _id in Room itself change as well or will it only be changed in the table? In short, i want the _id in the class Room to adjust itself automatically with the id in the table. how do i make this work?
When you have a primary key auto increment the first entry will be at 0 then 1 them 2 so on on if you update say row at id 1 it stays 1. Now let's say row row gets deleted, but uh oh you need out back in. It will bout be 2 or 3 or wherever is after your last id.