So I guess it is a very common issue, searching the web I found that I am not the only one who faced a such issue and yes I know that there is a question with almost the same title, however that did not help to solve the issue I am facing ... so let's start from the beginning
I am simply trying to insert into a table that I created.
This table has three columns: "id", "name", "value", and was created as following
public static final String TABLE_NAME = "cookie";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_VALUE = "val";
private static final String DATABASE_NAME = "commments.db";
private static final int DATABASE_VERSION = 2;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_NAME + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_VALUE + "text not null, "
+ COLUMN_NAME + " text not null"
+ ");";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
Now I am trying to insert into this table as following
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_NAME, "username");
values.put(MySQLiteHelper.COLUMN_VALUE, username);
long insertId = database.insert(MySQLiteHelper.TABLE_NAME, null, values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_NAME, allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
cursor.moveToFirst();
nameValuePair newComment = cursorToNameValuePair(cursor);
cursor.close();
However I am getting this error
table cookie has no column named val
I searched for similar issues online, most of the solution where talking about a change happened to the database so I need to either
1- Un-install the application before trying to run in debugging mode again
2- update the database version from 1 to 3
However that did not help .. So looking forward for your solutions :)
Problem is here
+ COLUMN_VALUE + "text not null, "
into DATABASE_CREATE String. You missed space between column name and column type.
It should be
+ COLUMN_VALUE + " text not null, "
Related
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)");
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.
I have three columns in my database id ,message and message status and I only want to select only those rows from the list whose message status is 'r' and want to return the cursor from query for only id and message. I am new to databases,Please help.
My current code which is selecting all the rows is:
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,MySQLiteHelper.COLUMN_MESSAGE };
public List<Message> getAllMessages() {
List<Message> message = new ArrayList<Message>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_NAME,allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Message message1 = cursorToMessage(cursor);
message.add(message1);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return message;
}
SQLiteDatabase database = this.getReadableDatabase();
String queryz = "SELECT " + COLUMN_ID + "," + COLUMN_MESSAGE + " FROM " + TABLE_NAME + " WHERE " + COLUMN_MESSAGE_STATUS + "= 'r'";
Cursor c = database.rawQuery(queryz, null);
You need to pass a Where clause yo your query. It is the 4th parameter of the query(). It takes a String, and you should not include the Sqlite3 keyword WHERE (Android does that for you). The clause can be structured like MySQLiteHelper.COLUMN_MESSAGE+"="+"r"
Try this code,
public static final String KEY_ROWID = "row";
public static final String KEY_NAME = "name";
public Cursor fetchNamesByConstraint(String filter) {
Cursor cursor = mDb.query(true, DATABASE_NAMES_TABLE, null, "row LIKE '%" + filter + "%' or name LIKE '%" + filter + "%'",null, null, null, null);
}
I'm setting up an SQLite Database and I've got most things set up how I think they're supposed to be. The main error has to with a column not being where it should be. I initialized the database column names in strings like so:
public static final String KEY_ROWID = "_id";
public static final String KEY_SPORT = "given_sport";
public static final String KEY_NAME = "given_name";
public static final String KEY_DATE = "given_date";
public static final String KEY_TIME = "given_time";
public static final String KEY_PERIOD = "given_period";
public static final String KEY_LOCATION = "given_location";
When it was time to create a table with the column names:
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_SPORT + " TEXT NOT NULL, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_DATE + " TEXT NOT NULL, " +
KEY_TIME + " TEXT NOT NULL, " +
KEY_PERIOD + " TEXT NOT NULL, " +
KEY_LOCATION + "TEXT NOT NULL);"
);
The problem now is that I'm getting the following error:
05-27 04:13:01.448: E/Database(273): android.database.sqlite.SQLiteException: table groupTable has no column named given_location: , while compiling: INSERT INTO groupTable(given_location, given_time, given_date, given_period, given_sport, given_name) VALUES(?, ?, ?, ?, ?, ?);
It seems like the table names are being reordered and that's what is causing the error in insertion. I'm clueless though and I'd really appreciate some help with this.
EDIT: here's the INSERT command
ContentValues cv = new ContentValues();
cv.put(KEY_SPORT, sportInput);
cv.put(KEY_NAME, nameInput);
cv.put(KEY_DATE, dateInput);
cv.put(KEY_TIME, timeInput);
cv.put(KEY_PERIOD, periodInput);
cv.put(KEY_LOCATION, locationInput);
return dbSQL.insert(DATABASE_TABLE, null, cv);
The problem is probably that you've changed the database structure but not the database version. It's a weird issue that I had to spend a lot of time figuring out the first time.
In your DatabaseHelper class there should be a version number, just increment it by one anytime you change any table schema etc.
EDIT
You're missing a space before the "TEXT" in your SQL table creation.
It should be:
...
+ KEY_LOCATION+ " TEXT" ...
once you fix that, increment the version number again.
The order of the table columns will not create "no column" error. If you have added the column to your table after running your app at least once but haven't incremented the database version, this is one way to cause this error.
The order of these columns:
INSERT INTO groupTable(given_location, given_time, given_date, given_period, given_sport, given_name) ...
depends on the order of the columns when you write your INSERT statement, it is not a fixed order based off of the CREATE command.