SQLite column name is not unique error? - android

I am creating a database for my application using a Database helper class, I then try to insert data into it within another class. But I am getting an error.
I am getting the following error in Logcat and dont know how to solve it? :
07-15 16:20:30.348: E/SQLiteDatabase(16270): Error inserting score=0 date=1405437630327 name=ry
07-15 16:20:30.348: E/SQLiteDatabase(16270): android.database.sqlite.SQLiteConstraintException: column name is not unique (code 19)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:976)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1591)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1461)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at com.example.multapply.DatabaseHelper.addScore(DatabaseHelper.java:84)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at com.example.multapply.RandomTest.onClick(RandomTest.java:161)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.view.View.performClick(View.java:4633)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.view.View$PerformClick.run(View.java:19330)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.os.Handler.handleCallback(Handler.java:733)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.os.Handler.dispatchMessage(Handler.java:95)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.os.Looper.loop(Looper.java:157)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at android.app.ActivityThread.main(ActivityThread.java:5356)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at java.lang.reflect.Method.invokeNative(Native Method)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at java.lang.reflect.Method.invoke(Method.java:515)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-15 16:20:30.348: E/SQLiteDatabase(16270): at dalvik.system.NativeStart.main(Native Method)
Related Code:
Database helper class:
package com.example.multapply;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 3;
// Database Name
private final static String DATABASE_NAME = "MultapplyDatabase";
// Contacts table name
private static final String TABLE_SCORE = "scores";
// Contacts Table Columns names
private static final String COL_NAME = "name";
private static final String COL_SCORE = "score";
private static final String COL_DATE = "date";
/**
* Constructor
* #param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Method that creates the database
*/
#Override
public void onCreate(SQLiteDatabase db) {
//NOTE: may need to alter the below to take out everything after INTEGER
String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "("
+ COL_NAME + " STRING PRIMARY KEY," + COL_SCORE + " INTEGER," + COL_DATE + " LONG" + ")";
db.execSQL(CREATE_TABLE_SCORE);
}
/**
* Method that upgrades the database
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE);
// Create tables again
onCreate(db);
}
/**
* All CRUD operations
*/
// Adding new score details (Name, score, date)
void addScore(Score score) {
SQLiteDatabase db = this.getWritableDatabase();
//ContentValues- holds the values.
ContentValues values = new ContentValues();
values.put(COL_NAME, score.getName());
values.put(COL_SCORE, score.getScore());
values.put(COL_DATE, score.getDate());
// Inserting Row (i.e. the values that were entered from above
db.insert(TABLE_SCORE, null, values);
db.close(); // Closing database connection
}
/**
* Method will return a single Name and score
* #param id
* #return
*/
// Getting single contact
Score getScore(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_SCORE, new String[] { COL_NAME,
COL_SCORE, COL_DATE}, COL_NAME + "=?",
new String[] { String.valueOf(name) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Score score = new Score(cursor.getString(0),Integer.parseInt(cursor.getString(1)),cursor.getLong(2));
// return contact
return score;
}
/**
* Method will return a list of all the scores
* #return
*/
// Getting All Contacts
public List<Score> getAllScores() {
List<Score> scoreList = new ArrayList<Score>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_SCORE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Score score = new Score();
score.setName(cursor.getString(0));
score.setScore(Integer.parseInt(cursor.getString(1)));
score.setDate(cursor.getLong(2));
// Adding contact to list
scoreList.add(score);
} while (cursor.moveToNext());
}
// return contact list
return scoreList;
}
}
Code relating to entering data into the database:
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addScore(new Score(UserName.getUserName(), score, System
.currentTimeMillis()));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Score> scores = db.getAllScores();
for (Score s : scores) {
String log = "Name: " + s.getName() + " ,Score: "
+ s.getScore() + "Date: " + s.getDate();
// Writing Contacts to log
Log.d("Details: ", log);
}
}
}

This means that you are trying to use a parameter in the "name" column that has already saved or used in your database because "name" is a primary key

You are violating UNIQUE constraint because your column name is primary key. This is reason of SQLiteConstraintException.

Related

Android Studio : E/SQLiteLog: (1) table places has no column named description_place

I keep getting this error "table places has no clumn named description_place" still pretty new to android so no clue why this happens, can anyone spot the error?
This is my Database class:
public class BDManager {
private static final String TABLE_NAME = "places";
public static final String KEY_ID_PLACE = "_id";
public static final String KEY_NOM_PLACE = "nom_place";
public static final String KEY_TYPE_PLACE = "type_place";
public static final String KEY_ADDRESS_PLACE = "address_place";
public static final String KEY_DESCRIPTION_PLACE = "description_place";
public static final String CREATE_TABLE_PLACES = "CREATE TABLE "
+ TABLE_NAME + "("
+ KEY_ID_PLACE + " INTEGER PRIMARY KEY, "
+ KEY_NOM_PLACE +" TEXT, "
+ KEY_TYPE_PLACE +" TEXT, "
+ KEY_ADDRESS_PLACE +" TEXT, "
+ KEY_DESCRIPTION_PLACE +" TEXT);";
private MySQLite maBaseSQLite;
private SQLiteDatabase db;
public BDManager(Context context){
maBaseSQLite = MySQLite.getInstance(context);
}
public void open() {
db = maBaseSQLite.getWritableDatabase();
}
public void close() {
db.close();
}
public long addPlace(BD place){
ContentValues values = new ContentValues();
values.put(KEY_NOM_PLACE, place.getNom_place());
values.put(KEY_TYPE_PLACE, place.getType_place());
values.put(KEY_ADDRESS_PLACE, place.getAddress_place());
values.put(KEY_DESCRIPTION_PLACE, place.getDescription_place());
return db.insert(TABLE_NAME,null,values);
}
public int modPlace(BD place){
ContentValues values = new ContentValues();
values.put(KEY_NOM_PLACE, place.getNom_place());
values.put(KEY_TYPE_PLACE, place.getType_place());
values.put(KEY_ADDRESS_PLACE, place.getAddress_place());
values.put(KEY_DESCRIPTION_PLACE, place.getDescription_place());
String where = KEY_ID_PLACE+" = ?";
String[] whereArgs = {place.getId_place()+""};
return db.update(TABLE_NAME, values, where, whereArgs);
}
public BD getPlace(int id){
BD p = new BD("","","","");
Cursor c = db.rawQuery("SELECT * FROM "+TABLE_NAME+" WHERE "+KEY_ID_PLACE+"="+id, null);
if (c.moveToFirst()){
p.setId_place(c.getInt(c.getColumnIndex(KEY_ID_PLACE)));
p.setNom_place(c.getString(c.getColumnIndex(KEY_NOM_PLACE)));
p.setType_place(c.getString(c.getColumnIndex(KEY_TYPE_PLACE)));
p.setAddress_place(c.getString(c.getColumnIndex(KEY_ADDRESS_PLACE)));
p.setDescription_place(c.getString(c.getColumnIndex(KEY_DESCRIPTION_PLACE)));
c.close();
}
return p;
}
public Cursor getPlaces(){
return db.rawQuery("SELECT * FROM "+TABLE_NAME, null);
}
}
It makes the error when I try tu save a place with the addplace function here :
public void savePlace(View view) {
final EditText name = (EditText) findViewById(R.id.NomPlace);
final Spinner type = (Spinner) findViewById(R.id.TypePlace);
final EditText address = (EditText) findViewById(R.id.AdressePlace);
final EditText description = (EditText) findViewById(R.id.DescriptionPlace);
BDManager sav = new BDManager(this);
sav.open();
sav.addPlace(new BD(name.getText().toString() ,type.getSelectedItem().toString() , address.getText().toString(),description.getText().toString()));
sav.close();
name.setText("");
type.setSelection(0);
address.setText("");
description.setText("");
}
Here is the complete error :
table places has no column named description_place
Error inserting description_place= nom_place=fyeyryfu address_place=dure type_place=Default
android.database.sqlite.SQLiteException: table places has no column named description_place (code 1): , while compiling: INSERT INTO places(description_place,nom_place,address_place,type_place) VALUES (?,?,?,?)
#################################################################
Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(table places has no column named description_place (code 1): , while compiling: INSERT INTO places(description_place,nom_place,address_place,type_place) VALUES (?,?,?,?))
#################################################################
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1607)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1479)
at com.myfavoriteplaces.myfavoriteplaces.BDManager.addPlace(BDManager.java:49)
at com.myfavoriteplaces.myfavoriteplaces.SavePlaces.savePlace(SavePlaces.java:124)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5076)
at android.view.View$PerformClick.run(View.java:20279)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5910)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Can someone help me please ?
Dude i was gonna ask for a magic wand but then.... eureka (no nudity like the greek dude is involved :-) ) I once had similar problem
A SINGLE SPACE BETWEEN THE WORD "TEXT AND THE BRACE IS NEEDED
KEY_DESCRIPTION_PLACE +" TEXT );";
I trust AN UPVOTE IS THE LEAST U CAN OFFER
mostly when a missing column error is crushing android success dream... its the cause of typing error.
Heil Android!!!
when you change database information you need to Drop table in OnOpdate()
if you want shere your onCreate and OnUpdate (MySQLite) code and i fix it

Apps crashed with fatal exception

my friends help me do this android app, but i dont really know what is the actual problems here. Can you guys help me? I try to run the code in the android, but when i try to login in my app login menu, it crashes
Here is my Database Helper
package com.example.ikramhs.shoerack;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "login";
private static final int DB_VERSION = 1;
private static final String DB_TABLE = "create table user (id integer primary key autoincrement, " + "username text not null,password text not null;";
public DatabaseHelper(Context context){
super(context, DB_NAME, null,DB_VERSION) ;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade (SQLiteDatabase database, int oldVersion, int newVersion ){
Log.w(DatabaseHelper.class.getName(),
"Upgrading database from version" + oldVersion + "to " + newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS user");
onCreate(database);
}
}
and here is my Database Adapter file
package com.example.ikramhs.shoerack;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseAdapter {
private static final String LOGIN_TABLE = "user";
public static final String COL_ID = "id";
public static final String COL_USERNAME = "username";
public static final String COL_PASSWORD = "password";
private Context context;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
public DatabaseAdapter(Context context) {
this.context = context;
}
public DatabaseAdapter open() {
dbHelper = new DatabaseHelper(context) ;
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public long createUser (String username, String password)
{
ContentValues initialValues = createUserTableContentValues ( username,password );
return database.insert(LOGIN_TABLE,null,initialValues);
}
public Cursor fetchUser(String username, String password)
{
Cursor myCursor = database.query(LOGIN_TABLE, new String[] {COL_ID, COL_USERNAME, COL_PASSWORD},
COL_USERNAME + "=" + username + "'AND" + COL_PASSWORD + "='" + password + "'", null,null,null,null);
if (myCursor != null) {
myCursor.moveToFirst();
}
return myCursor;
}
private ContentValues createUserTableContentValues(String username, String password) {
ContentValues values = new ContentValues();
values.put(COL_USERNAME, username);
values.put(COL_PASSWORD, password);
return values;
}
}
Here's the logcat in Android Monitor
02-02 01:55:48.439 2659-2659/com.example.ikramhs.shoerack I/art: Not late-enabling -Xcheck:jni (already on)
02-02 01:55:48.585 2659-2659/com.example.ikramhs.shoerack W/System: ClassLoader referenced unknown path: /data/app/com.example.ikramhs.shoerack-2/lib/x86
02-02 01:55:48.639 2659-2672/com.example.ikramhs.shoerack D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-02 01:55:48.725 2659-2672/com.example.ikramhs.shoerack I/OpenGLRenderer: Initialized EGL, version 1.4
02-02 01:55:48.770 2659-2672/com.example.ikramhs.shoerack W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 01:55:48.770 2659-2672/com.example.ikramhs.shoerack W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad920680, error=EGL_SUCCESS
02-02 01:55:49.803 2659-2665/com.example.ikramhs.shoerack W/art: Suspending all threads took: 23.765ms
02-02 01:55:53.288 2659-2672/com.example.ikramhs.shoerack E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab9c45a0
02-02 01:55:54.230 2659-2665/com.example.ikramhs.shoerack W/art: Suspending all threads took: 8.143ms
02-02 01:55:54.294 2659-2672/com.example.ikramhs.shoerack W/EGL_emulation: eglSurfaceAttrib not implemented
02-02 01:55:54.294 2659-2672/com.example.ikramhs.shoerack W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad926e60, error=EGL_SUCCESS
02-02 01:56:08.158 2659-2659/com.example.ikramhs.shoerack E/SQLiteLog: (1) near "'ANDpassword='": syntax error
02-02 01:56:08.159 2659-2659/com.example.ikramhs.shoerack D/AndroidRuntime: Shutting down VM
02-02 01:56:08.159 2659-2659/com.example.ikramhs.shoerack E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ikramhs.shoerack, PID: 2659
android.database.sqlite.SQLiteException: near "'ANDpassword='": syntax error (code 1): , while compiling: SELECT id, username, password FROM user WHERE username=therhaman'ANDpassword='091192'
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
at com.example.ikramhs.shoerack.DatabaseAdapter.fetchUser(DatabaseAdapter.java:42)
at com.example.ikramhs.shoerack.welcome.LogMeIn(welcome.java:68)
at com.example.ikramhs.shoerack.welcome.access$000(welcome.java:17)
at com.example.ikramhs.shoerack.welcome$1.onClick(welcome.java:46)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
02-02 01:56:09.955 2659-2659/? I/Process: Sending signal. PID: 2659 SIG: 9
android.database.sqlite.SQLiteException: near "'ANDpassword='": syntax error (code 1): , while compiling: SELECT id, username, password FROM user WHERE username=therhaman'ANDpassword='091192'
You need a space between AND and password.
Your Logcat is clearly said it "near "'ANDpassword='": syntax error (code 1)".
You have SQL syntax error and I believe it should be "AND password=". Change below line such that it becomes (space after COL_PASSWORD):
COL_USERNAME + "=" + username + "' AND " + COL_PASSWORD + "='" + password + "

android.database.sqlite.SQLiteException: no such table

I know that there are a lot of topics on this error but I tried a lot of solutions and still I am stuck whit this error.
It´s my first time playing around with SQLite, and I don´t understand what is happening wrong there.
05-26 08:34:20.369 23124-23124/com.danynuria.fmp D/ODOperations﹕ Overall Table Created
05-26 08:34:20.373 23124-23124/com.danynuria.fmp E/SQLiteLog﹕ (1) no such table: database_info
05-26 08:34:20.374 23124-23124/com.danynuria.fmp E/SQLiteDatabase﹕ Error inserting date=26 / 4 / 2015 county=Bedfordshire co2_saved=149 distance=1245 distance_type=run user_id=1
android.database.sqlite.SQLiteException: no such table: database_info (code 1): , while compiling: INSERT INTO database_info(date,county,co2_saved,distance,distance_type,user_id) 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.danynuria.fmp.OverallDatabaseOperations.putInformation(OverallDatabaseOperations.java:73)
at com.danynuria.fmp.MainActivity$1.onClick(MainActivity.java:121)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
05-26 08:34:20.374 23124-23124/com.danynuria.fmp D/ODOperations﹕ One row inserted
And my code:
package com.danynuria.fmp;
import android.app.DownloadManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.danynuria.fmp.OverallTableData.OverallTableinfo;
import java.sql.SQLException;
public class OverallDatabaseOperations extends SQLiteOpenHelper {
// Create integer that register version of database
private static final int overallDatabase_version = 1;
// Create query
public String CREATE_QUERY = "CREATE TABLE "+OverallTableinfo.OVERALL_TABLE_NAME+"( "+OverallTableinfo.USER_ID+" INTEGER, "+OverallTableinfo.DISTANCE+
" INTEGER, "+OverallTableinfo.DISTANCE_TYPE+" TEXT, "+OverallTableinfo.COUNTY+" TEXT, "+OverallTableinfo.CO2_SAVED+
" INTEGER, "+OverallTableinfo.DATE+" TEXT);";
// Creating the database using SQLiteOpenHelper constructor
public OverallDatabaseOperations(Context context) {
super(context, OverallTableinfo.OVERALL_DATABASE_NAME, null, overallDatabase_version);
}
public void onCreate(SQLiteDatabase odb ){
odb.execSQL(CREATE_QUERY);
Log.d("ODOperations", "Overall Table Created");
}
public void onUpgrade(SQLiteDatabase arg0,int arg1, int arg2){
}
// Create a method to insert data into database
public void putInformation(OverallDatabaseOperations dop, Integer id, Integer distance, String type, String county, Integer co2saved, String date) {
// Create a SQLite database object
SQLiteDatabase OSQ = dop.getWritableDatabase();
// Create an object for content values
ContentValues ncv = new ContentValues();
// Passing the first column value
ncv.put(OverallTableinfo.USER_ID, id);
ncv.put(OverallTableinfo.DISTANCE, distance);
ncv.put(OverallTableinfo.DISTANCE_TYPE, type);
ncv.put(OverallTableinfo.COUNTY, county);
ncv.put(OverallTableinfo.CO2_SAVED, co2saved);
ncv.put(OverallTableinfo.DATE, date);
// Inserting data into table
OSQ.insert(OverallTableinfo.OVERALL_DATABASE_NAME, null, ncv);
Log.d("ODOperations", "One row inserted");
}
}
And the other class:
package com.danynuria.fmp;
import android.provider.BaseColumns;
public class OverallTableData {
// Create constructor
public OverallTableData() {
}
// Create abstract class
public static abstract class OverallTableinfo implements BaseColumns {
// Create first column in database
public static final String USER_ID = "user_id";
// Create second column in database
public static final String DISTANCE = "distance";
// Create third column in database
public static final String DISTANCE_TYPE = "distance_type";
// Create forth column in database
public static final String COUNTY = "county";
// Create fifth column in database
public static final String CO2_SAVED = "co2_saved";
// Create sixth column in database
public static final String DATE = "date";
// Define database name
public static final String OVERALL_DATABASE_NAME = "database_info";
// Define table name
public static final String OVERALL_TABLE_NAME = "overall_info";
}
}
Any suggestions are highly appreciated
you have to use OVERALL_TABLE_NAME instead of OVERALL_DATABASE_NAME in your insert:
OSQ.insert(OverallTableinfo.OVERALL_TABLE_NAME, null, ncv);

near "null": syntax error (code 1): , while compiling: INSERT INTO

I am learning how to create and insert values into SQLite DB. the application has a button and chronometer. clicking the button starts the timer and clicking it again stops it. On stop, the values are to be stored into the DB. I can see from the file explorer in Android Studio that the DB and the table is getting created. There is evidence in the Log to suggest the start and stop time is also getting captured, but the values are not getting inserted into the DB. I am pasting snippet of the code used to create the DB and then to insert the record. I am also pasing snippet of the log where the error is output. Please help.
import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.content.Context; import android.util.Log; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Feeds.db";
public static String TIMESTAMP_START;
public static String TIMESTAMP_END;
public static int _ID = 0;
public static final String DATABASE_TABLE = "T_FEEDRECORDS";
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE T_FEEDRECORDS ( _ID INTEGER primary key autoincrement, TIMESTAMP_START TEXT, TIMESTAMP_END TEXT)" ;
public DBHelper(Context context)
{
super(context,DATABASE_NAME, null, DATABASE_VERSION );
}
public void onCreate(SQLiteDatabase db)
{
Log.d("onCreate", "before DB Create");
try {
db.execSQL(SQL_CREATE_ENTRIES);
} catch(SQLException ex){ Log.d("onCreate", "DB creation exception:"+ ex.getMessage()); }
Log.d("onCreate", "after DB Create" + db.toString());
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF IT EXISTS " + DATABASE_TABLE);
Log.d("onUpgrade", "dropping table");
onCreate(db);
}
public void createFeedRecord (FeedRecords feedRecord){
ContentValues feedContent = new ContentValues();
feedContent.put(TIMESTAMP_START, feedRecord.getStartTime());
feedContent.put(TIMESTAMP_END, feedRecord.getEndTime());
try {
SQLiteDatabase db = this.getWritableDatabase();
Log.d("createFeedRecord values before insert", "start time : " + feedRecord.getStartTime() + " Timer end:" + feedRecord.getEndTime());
db.insertOrThrow(DATABASE_TABLE,null, feedContent );
db.close();
} catch(SQLException ex) {Log.d("SQL Exdception in create feed record", "" + ex.getLocalizedMessage());}
Log.d("createFeedRecord", "after content values");
}
}
LOG SNIPPET
02-04 09:57:43.287 2213-2213/? D/onClick......﹕ Timer Start time: 150204_095743
....
02-04 10:01:25.738 2213-2213/? D/onClick......﹕ Timer Stop time: 150204_100125
02-04 10:01:25.738 2213-2213/? D/inster Time Record﹕ after create Feed
02-04 10:01:25.754 1239-1293/? W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
02-04 10:01:25.763 2213-2213/? D/createFeedRecord values before insert﹕ start time : 150204_095743 Timer end:150204_100125
02-04 10:01:25.763 2213-2213/? E/SQLiteLog﹕ (1) near "null": syntax error
02-04 10:01:25.763 2213-2213/? D/SQL Exdception in create feed record﹕ near "null": syntax error (code 1): , while compiling: INSERT INTO T_FEEDRECORDS(null) VALUES (?)
02-04 10:01:25.763 2213-2213/? D/createFeedRecord﹕ after content values
You need to assign
public static String TIMESTAMP_START="TIMESTAMP_START";
public static String TIMESTAMP_END="TIMESTAMP_END";
OR
Directly provide column name
ContentValues feedContent = new ContentValues();
feedContent.put("TIMESTAMP_START", feedRecord.getStartTime());
feedContent.put("TIMESTAMP_END", feedRecord.getEndTime());

Android: SQLiteConstraintException: error code 19: constraint failed

I checked other examples in SO and I searched a lot, nothing is working for me. The database file is this (after suggested edit).
Error
E/Database(274): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
E/Database(274): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
E/Database(274): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:55)
E/Database(274): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1549)
E/Database(274): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
E/Database(274): at com.example.nycgasstationhunter.userRegister$2.onClick(userRegister.java:51)
E/Database(274): at android.view.View.performClick(View.java:2408)
E/Database(274): at android.view.View$PerformClick.run(View.java:8816)
E/Database(274): at android.os.Handler.handleCallback(Handler.java:587)
E/Database(274): at android.os.Handler.dispatchMessage(Handler.java:92)
E/Database(274): at android.os.Looper.loop(Looper.java:123)
E/Database(274): at android.app.ActivityThread.main(ActivityThread.java:4627)
E/Database(274): at java.lang.reflect.Method.invokeNative(Native Method)
E/Database(274): at java.lang.reflect.Method.invoke(Method.java:521)
E/Database(274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/Database(274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/Database(274): at dalvik.system.NativeStart.main(Native Method)
Code
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
public class userRegister extends Activity{
//database
SQLiteDatabase db;
DBHelper dbhelper;
Context ourContext;
ContentValues cv;
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_register);
//database
dbhelper=new DBHelper(this);
db=dbhelper.getWritableDatabase();
cv=new ContentValues();
//editText
final EditText userEdit=(EditText) findViewById(R.id.userEdit);
final EditText emailEdit=(EditText) findViewById(R.id.emailEdit);
final EditText passwordEdit=(EditText) findViewById(R.id.passwordEdit);
final EditText retypePassEdit=(EditText) findViewById(R.id.retypePassEdit);
//Register button
Button regButton = (Button) findViewById(R.id.regButton);
regButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//string
final String userName=userEdit.getText().toString();
final String emailAddress=emailEdit.getText().toString();
final String password=passwordEdit.getText().toString();
final String retypePassword=retypePassEdit.getText().toString();
if (userName.length()!=0){
if (emailAddress.length()!=0){
if (password.length()!=0){
if (retypePassword.equals(password)){
//save in DB
cv.put(DBHelper.USER, userName);
cv.put(DBHelper.EMAIL,emailAddress);
cv.put(DBHelper.PASSWORD, retypePassword);
db.insert(DBHelper.USER_TABLE, null, cv);
Intent intent = new Intent (userRegister.this,Profile.class);
startActivity(intent);
}
else
Toast.makeText(userRegister.this,"Password mismatch", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(userRegister.this,"Invalid password", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(userRegister.this,"Invalid email", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(userRegister.this,"Invalid user name", Toast.LENGTH_SHORT).show();
}
});
}
}
When I insert information and press regButton, it sends me to Profile activity. There is no information being saved in database. I don't understand the error in LogCat and how can I solve that? Why there is nothing in database? (I am using SQLite Database Browser to check data.) Thank you
The error SQLiteConstraintException indicates that an integrity constraint was violated.
From your Create Table SQL command I think the first problem is your primary key. It should be declare as autoincrement
Change String createDB:
public final String createDB="create table "+USER_TABLE+"("
+ C_ID + " integer primary key autoincrement, "
+ USER + " text not null,"
+ EMAIL + " text not null,"
+ PASSWORD + " text not null,"
+ TIME + " text not null);";
Also, all fields are declared not null, you should test if retypePassword is not null and you must set a value to field TIME.
EDIT
In order the autoincrement take effect, the database version value need to be incremented.
In DBHelper class change DATABASE_VERSION=1; to DATABASE_VERSION=2;
If the database schema is as follows as you mention in comments (from this question)...
public final String createDB="create table "+USER_TABLE+"("
+C_ID+" integer primary key, "
+USER+" text not null,"
+EMAIL+ " text not null,"
+PASSWORD+ " text not null,"
+TIME+ " text not null);";
... then you have not specified a value for the TIME column which has the not null constraint.
Some options:
Add a TIME value to the ContentValues before insert().
Change the schema and provide a suitable default such as
TIME + " text not null default current_timestamp"
As always, when changing the database schema, remove the old database so that onCreate() gets called with the new code (clear app data or just uninstall the app).
In my case I made two HTTP-requests and got two lists. Then wrote them to two tables. But first in a child table and then in parent. Strange, but a problem appeared on Android 4.4.2, but not on Android 5.0.

Categories

Resources