How to save Integer to Database(SQLite) - android

In my program, I have a database and there is a table in my database in the name of the student , In the student table, there is a column named StudentID that should save ten numbers now my problem is The Student ID column can not save the numbers,When I enter numbers less than ten it shows the save message but in logcat have error and when I enter the ten numbers, it will be out from the program.
Sorry for my poor English language.
SQLite Code For Student Table :
create table student(student_id integer(10) primary key not null , class_id int , student_name nvarchar(50) , FOREIGN KEY (class_id) REFERENCES class(class_id))
Save Student Method :
public void SaveStudent(int studentId , int classID , String studentName)
{
ContentValues values = new ContentValues();
values.put("student_id" , studentId);
values.put("class_id" , classID);
values.put("student_name" , studentName);
database.insert("student" , null , values);
Toast.makeText(context, "Save!" , Toast.LENGTH_SHORT).show();
}
Get Student Information :
Button saveStudent_btn = (Button)viewLayout.findViewById(R.id.item_btn_SaveStudent);
saveStudent_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, Object> obj = (HashMap<String, Object>) adapter.getItem(position);
int classId = (int) obj.get("class_id");
EditText studentName_et = (EditText)viewLayout.findViewById(R.id.item_et_StudentName);
String studentName = studentName_et.getText().toString();
EditText studentId_et = (EditText)viewLayout.findViewById(R.id.item_et_StudentId);
int studentId = Integer.parseInt(studentId_et.getText().toString());
database.OpenDatabase();
database.SaveStudent(studentId , classId , studentName);
database.close();
}
});
Logcat error for when entered 10 numbers:
02-23 19:05:07.850 1896-1896/com.example.user.classmanager E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.classmanager, PID: 1896
java.lang.NumberFormatException: Invalid int: "4318659489"
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:413)
at java.lang.Integer.parseInt(Integer.java:367)
com.example.user.classmanager.SecondTab$1$1$1.onClick(SecondTab.java:94)
at android.view.View.performClick(View.java:5225)
at android.view.View$PerformClick.run(View.java:21195)
at android.os.Handler.handleCallback(Handler.java:739)
logcat error for less then 10 numbers :
02-23 19:42:32.502 10388-10388/com.example.user.classmanager E/SQLiteDatabase: Error inserting
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: student.student_id (code 1555)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:780)
at com.example.user.classmanager.DatabaseHandler.SaveStudent(DatabaseHandler.java:189)
at com.example.user.classmanager.SecondTab$1$1$1.onClick(SecondTab.java:97)

The problem is the length of int, your number overflow.
Use Long instead .
Long studentId = Long.parseLong(studentId_et.getText().toString());
int range in java from -2,147,483,648 To 2,147,483,647 . and your number overflows it .
And for UNIQUE constraint failed you violates the primary key constraints. Make sure the id generated is unique and not null always.

UNIQUE constraint failed this mean you are trying to insert id value which is already exists and that violates the primary key's uniqueness..to a void that make the StudentID auto increment.

Related

Unable to add data to SQLite table in android

I'm working on a simple SQLite CRUD application and I want to add data to manually created database in SQLite. But when I'm adding data, the app stops and shows the below error message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sqlitecrudexample, PID: 14124
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: employees.id (code 1299 SQLITE_CONSTRAINT_NOTNULL)
at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:890)
at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:756)
at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:66)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1920)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1897)
at com.example.sqlitecrudexample.MainActivity.addEmployee(MainActivity.kt:70)
at com.example.sqlitecrudexample.MainActivity.access$addEmployee(MainActivity.kt:13)
at com.example.sqlitecrudexample.MainActivity$onCreate$1.onClick(MainActivity.kt:30)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 14124 SIG: 9
Here is my code for creating and adding data to the table
private fun addEmployee(){
var name:String = editTextName.text.toString().trim()
var salary:String = editTextSalary.text.toString().trim()
var dept = spinnerDepartment.selectedItem.toString()
var calendar = Calendar.getInstance()
var simpleDateFormat = SimpleDateFormat("yyyy-mm-dd hh:mm:ss")
var joiningDate = simpleDateFormat.format(calendar.time)
if(inputsAreCorrect(name,salary)){
val insertSQL = """
INSERT INTO employees
(name, department, joiningdate, salary)
VALUES
(?, ?, ?, ?);
""".trimIndent()
mDatabase.execSQL(insertSQL, arrayOf(name, dept, joiningDate, salary))
Toast.makeText(this,"Employee Added Successfully",Toast.LENGTH_SHORT).show()
}
}
private fun createEmployeeTable() {
mDatabase.execSQL(
"""CREATE TABLE IF NOT EXISTS employees (
id int PRIMARY KEY AUTOINCREMENT NOT NULL,
name varchar(200) NOT NULL,
department varchar(200) NOT NULL,
joiningdate datetime NOT NULL,
salary double NOT NULL
);"""
)
}
And this is my data class
data class Employee(
var id: Int,
var name: String,
var dept: String,
var joiningDate: String,
var salary: Double
)
Change SQL statement to 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL` for id row. You need to use primitive type
You are using incorrect syntax while defining id row, You have to use Integer as keyword AUTOINCREMENT can be used with INTEGER field only. Change your create table syntax as below and it will work
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
If you really tried to create the table with this statement:
CREATE TABLE IF NOT EXISTS employees (
id int PRIMARY KEY AUTOINCREMENT NOT NULL,
..........................
);
the result would be this error:
AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY
So, my guess is that the table was not created by that statement, but by a previous statement on which you made changes later. These changes though were not actually reflected to the database, because the table already existed.
What you have to do is either uninstall the app from the device so the db is deleted, or change the version of the db in your SQLiteOpenHelper class so the onUpgrade() method is called which will delete and recreate the table.
So change the CREATE statement to:
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY AUTOINCREMENT,
..........................
);
Also, don't use execSQL() to insert rows in the table.
The recommended method is insert():
val cv = ContentValues()
cv.put("name", name)
cv.put("department", dept)
cv.put("joiningdate", joiningDate)
cv.put("salary", salary)
mDatabase.insert("employees", null, cv)

Insert into sqlite with default value

I'm working on a android program with SQLite. I'm trying to create a datebase with two tables related by a foreign key, and I want to automaticaly populate one entry of the mother table using the insert funcion. But this generate an SQLite error.
Here is the funcion to insert an entry into the mother class
private long new_event(SQLiteDatabase db)
{
ContentValues values = new ContentValues();
long id = db.insert("EVENT",null,values);
return id;
}
Here is the function to insert an entry into the child class
public long new_specific_event(SQLiteDatabase db)
{
long id_event = new_event(db);
ContentValues values = new ContentValues();
values.put("id_event", id_event);
values.put("whatsoever", "whatsoever");
long id = db.insert("SPECIFIC_EVENT",null,values);
return id;
}
Here is the mother table
CREATE TABLE EVENT (id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
and here is the child table
CREATE TABLE SPECIFIC_EVENT (id INTEGER PRIMARY KEY AUTOINCREMENT, id_event NUMBER,whatsoever TEXT,FOREIGN KEY(id_event) REFERENCES EVENT(id));
This result into the following error
android.database.sqlite.SQLiteException: near "null": syntax error (code 1): , while compiling: INSERT INTO EVENT(null) VALUES (NULL)
I could do it using this and the db.execSQL() funcion, but then I have no access to the id of the entry I just create.
So, how can I use the insert funcion to insert an entry with just default value?
With ContentValues you need to put at least one value. To get a default value, put a null for a value for a column:
ContentValues values = new ContentValues();
values.putNull("_id");
long id = db.insert("EVENT",null,values);
Inserting a completely empty row is not possible, so the insert() method has the parameter nullColumnHack to allow you to specify a column that gets a NULL value in this case:
ContentValues values = new ContentValues();
long id = db.insert("EVENT", "_id", values);

android.database.sqlite.SQLiteException: no such column: personal (code 1):

I have a table created by this sql command ->
CREATE TABLE messages( id integer primary key autoincrement, senderNum String, messagebody String, label String );
In this Table I have a row having senderNum equal to 123.In order to apply label to it i call method which looks like this ->
public void ApplyLabel(String senderNum){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("update messages set label=personal where senderNum=" + senderNum,null);
}
where the variable senderNum have value 123.Now when this method is called it throws error like this ->
android.database.sqlite.SQLiteException: no such column: personal (code 1): , while compiling: update messages set label=personal where senderNum=123
I don't know why it gives this error ??
You are missing the string delimiters (') surrounding your string value.
As it's now, you are comparing a column named label to another column named personal, which doesn't exist.
Try:
Cursor res = db.rawQuery("update messages set label='personal' where senderNum=" + senderNum,null);
If you want to use a variable, you can concatenate the string like so:
Cursor res = db.rawQuery("update messages set label='" + strPersonal + "' where senderNum=" + senderNum,null);

Android-SQLiteConstraintException error code 19: constraint failed

I know you have many questions on here about this error, but I cannot understand why all the fields appears to be filled correctly on Logcat, but even so the failure occurs.
Here is the creation of the table:
public void onCreate(SQLiteDatabase db) {
String ddl = "CREATE TABLE Politician (id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE , idpolitician INTEGER NOT NULL, name TEXT NOT NULL, picture TEXT , position TEXT NOT NULL, country TEXT NOT NULL, state TEXT NOT NULL, city TEXT NOT NULL);";
db.execSQL(ddl);
}
Here is where I tried to save.
public void savePolitician(Politician politician) {
ContentValues values = new ContentValues();
values.put("idpolitician", politician.getId());
values.put("name", politician.getName());
values.put("picture", politician.getPictureFilename());
values.put("position", politician.getPosition());
values.put("country", politician.getCountry());
values.put("state", politician.getState());
values.put("city", politician.getCity());
mDatabase.insert("Politician", null, values);
}
And here is the LogCat:
01-08 04:03:31.149 32633-32633/? E/Database﹕ [SQLiteDatabase.java:1428:insert()] Error inserting
state=SP position=governador picture=example idpolitician=1 city=Sao Paulo country=Brasil name=Alckmin
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1582)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1426)
at com.politify.dao.DbManegament.savePolitician(DbManegament.java:44)
As you can see all the fields are filled. Anyone can help and tell what i`m doing wrong
try remove AUTOINCREMENT UNIQUE inyour create table script
This is your mistake id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE
When you are defining any column as Primary Key then you do not need to specify it as UNIQUE. Primary Key is by default UNIQUE.

syntax error while compiling sqlite

I'm trying to make a new table for my database with sqlite:
String CREATE_ARCHIVE_TABLE =
"CREATE TABLE {0} ({1} INTEGER PRIMARY KEY AUTOINCREMENT," +
" {2} TEXT NOT NULL, {3} TEXT NOT NULL, {4} TEXT NOT NULL, {5} INTEGER);";
db.execSQL(MessageFormat.format(CREATE_ARCHIVE_TABLE,AItext.TABLE_NAME,AItext._ID,
AItext.TITLE,AItext.MESSAGE,AItext.DATE,AItext.TYPE));
with the interface:
public interface AItext extends BaseColumns {
String TABLE_NAME = "table_name";
String TITLE = "title";
String MESSAGE = "message";
String DATE = "date";
String TYPE = "type";
String[] COLUMNS = new String[]
{ _ID, TITLE, MESSAGE, DATE, TYPE };
}
but I have the following exception and I can't see the error
android.database.sqlite.SQLiteException: near "INTEGER": syntax error: ,
while compiling: CREATE TABLE archive_contacts_name (_id INTEGER PRIMARY KEY
AUTOINCREMENT, message INTEGER, name TEXT NOT NULL, phone TEXT NOT NULL,
check INTEGER, note TEXT NOT NULL);
As #aim has said, CHECK is in fact a SQLite Keyword that cannot be used as a column name.
A CHECK constraint may be attached to a column definition or specified as a table constraint. In practice it makes no difference. Each time a new row is inserted into the table or an existing row is updated, the expression associated with each CHECK constraint is evaluated and cast to a NUMERIC value in the same way as a CAST expression. If the result is zero (integer value 0 or real value 0.0), then a constraint violation has occurred. If the CHECK expression evaluates to NULL, or any other non-zero value, it is not a constraint violation. The expression of a CHECK constraint may not contain a subquery.
CHECK constraints have been supported since version 3.3.0. Prior to version 3.3.0, CHECK constraints were parsed but not enforced.

Categories

Resources