SQLite problems in Android, "no such table" error - java

I've searched around stack overflow for similar problems but none of them seems to apply or work when it comes to my problem. I have an app that creates a SQLite database, which is fully functional when it comes to the table "LOGIN", but everything else just crashes the app. My database consists of users along with projects and tasks that users can create, so when I try to list every project done by a specific user I get a "no such table" error even though the table absolutely exists and it works with LOGIN. I first thought I had an old database still in the cache, but I've tried factory resetting the device two times which wipes out the entire database but the error still persists. What's wrong?
The Database Helper:
package com.example.tasksketchgui;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
{
super(context, name, factory, version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(_db);
}
}
Here is an adapter which I use to access the database.
package com.example.tasksketchgui;
import java.util.ArrayList;
import java.util.List;
import com.example.tasksketchgui.sqlite.model.ProjectEntry;
import com.example.tasksketchgui.sqlite.model.UserEntry;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class LoginDataBaseAdapter
{
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
//Column for all tables
static final String KEY_ID = "_id";
static final String KEY_NAME = "name";
static final String KEY_DEADLINE = "deadline";
static final String KEY_USER_ID = "user_id";
static final String KEY_PROJECT_ID = "project_id";
//Column names for login
static final String KEY_USER_PASSWORD = "PASSWORD";
static final String KEY_USER_NAME = "USERNAME";
//Column names for user_task
static final String KEY_TASK_ID = "task_id";
//Table names
static final String TABLE_PROJECT = "projects";
static final String TABLE_TASK = "tasks";
static final String TABLE_TASK_USER = "task_user";
static final String TABLE_PROJECT_USER = "project_user";
//Create table for projects
static final String CREATE_TABLE_PROJECT = "CREATE TABLE IF NOT EXISTS " + TABLE_PROJECT + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME + " TEXT, "
+ KEY_DEADLINE + " TEXT, " + KEY_USER_ID + " INTEGER" + ") ;";
//Create table for tasks
static final String CREATE_TABLE_TASK = "CREATE TABLE IF NOT EXISTS " + TABLE_TASK + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME + " TEXT, "
+ KEY_PROJECT_ID + " INTEGER, " + KEY_DEADLINE + " DATETIME" + ") ;";
//Create table for taskUsers
static final String CREATE_TABLE_TASK_USER = "CREATE TABLE IF NOT EXISTS " + TABLE_TASK_USER + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+ KEY_TASK_ID +
" INTEGER, " + KEY_USER_ID + "INTEGER" + ") ;";
//Create table for projectUsers
static final String CREATE_TABLE_PROJECT_USER = "CREATE TABLE IF NOT EXISTS " + TABLE_PROJECT_USER + " ("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_PROJECT_ID + " INTEGER, "
+ KEY_USER_ID + " INTEGER" + ") ;";
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table IF NOT EXISTS "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); "
+ CREATE_TABLE_PROJECT + "; " + CREATE_TABLE_TASK + ";" + CREATE_TABLE_TASK_USER
+ ";" + CREATE_TABLE_PROJECT_USER + ";";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(UserEntry user)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", user.getUserName());
newValues.put("PASSWORD", user.getPassword());
db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public void insertEntry(String userName,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
db.insert("LOGIN", null, newValues);
///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteUser(String UserName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeUserPassword(String userName)
{
Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) // UserName Not Exist
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
//Returns all users in the database
public List<UserEntry> getAllUser(){
List<UserEntry> users = new ArrayList<UserEntry>();
String query = "SELECT * FROM LOGIN";
Cursor cursor = db.rawQuery(query, null);
//If there's at least one entry
if(cursor.moveToFirst()){
do{
UserEntry user = new UserEntry();
user.setUserName(cursor.getString(cursor.getColumnIndex("USERNAME")));
user.setPassword(cursor.getString(cursor.getColumnIndex("PASSWORD")));
//Add to list
users.add(user);
}while(cursor.moveToNext());
cursor.close();
}
return users;
}
//Returns all projects from the user
public List<ProjectEntry> getProjectsFromUser(String userName){
List<ProjectEntry> projects = new ArrayList<ProjectEntry>();
String selectQuery = "SELECT * FROM " + TABLE_PROJECT + " pr," +
"LOGIN lg, " + TABLE_PROJECT_USER + " pu WHERE LOGIN.USERNAME = '"
+ userName + "' AND pr." + KEY_ID + " = pu." + KEY_PROJECT_ID +
" AND pu." + KEY_USER_ID + " = LOGIN.ID";
Cursor c = db.rawQuery(selectQuery, null);
if(c.moveToFirst()){
do{
ProjectEntry project = new ProjectEntry();
project.setId(c.getInt(c.getColumnIndex(KEY_ID)));
project.setName(c.getString(c.getColumnIndex(KEY_NAME)));
project.setUserId(c.getInt(c.getColumnIndex(KEY_USER_ID)));
project.setDeadline(c.getString(c.getColumnIndexOrThrow(KEY_DEADLINE)));
projects.add(project);
}while(c.moveToNext());
}
return projects;
}
//Create project
public long createProject(ProjectEntry project, UserEntry user){
ContentValues valuesProject = new ContentValues();
ContentValues valuesProjectUser = new ContentValues();
valuesProject.put(KEY_USER_ID, user.getId());
valuesProject.put(KEY_NAME, project.getName());
valuesProject.put(KEY_DEADLINE, project.getDeadline().toString());
long id = db.insert(TABLE_PROJECT, null, valuesProject);
valuesProjectUser.put(KEY_PROJECT_ID, id);
valuesProjectUser.put(KEY_USER_ID, user.getId());
//Return the projects id, so that it can be found
return id;
}
public long createProject(ProjectEntry project, long user){
ContentValues values = new ContentValues();
values.put(KEY_USER_ID, user);
values.put(KEY_NAME, project.getName());
values.put(KEY_DEADLINE, project.getDeadline().toString());
long id = db.insert(TABLE_PROJECT, null, values);
//Return the projects id, so that it can be found
return id;
}
public void updateEntry(String userName,String password)
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD",password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}
}
This is the lines of code calling the query.
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
//Fill list of projects
List<ProjectEntry> projects = new ArrayList<ProjectEntry>();
projects = loginDataBaseAdapter.getProjectsFromUser("pontan");
And here's the stack trace:
08-08 15:28:07.101: D/libEGL(2213): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
08-08 15:28:07.101: D/libEGL(2213): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
08-08 15:28:07.109: D/libEGL(2213): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
08-08 15:28:07.187: D/OpenGLRenderer(2213): Enabling debug mode 0
08-08 15:28:07.312: D/dalvikvm(2213): GC_CONCURRENT freed 114K, 2% free 9097K/9240K, paused 6ms+17ms, total 53ms
08-08 15:28:38.179: D/dalvikvm(2213): GC_CONCURRENT freed 152K, 2% free 9341K/9520K, paused 2ms+5ms, total 23ms
08-08 15:28:39.695: E/SQLiteLog(2213): (1) no such table: projects
08-08 15:28:39.695: D/AndroidRuntime(2213): Shutting down VM
08-08 15:28:39.695: W/dalvikvm(2213): threadid=1: thread exiting with uncaught exception (group=0x41336930)
08-08 15:28:39.710: E/AndroidRuntime(2213): FATAL EXCEPTION: main
08-08 15:28:39.710: E/AndroidRuntime(2213): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tasksketchgui/com.example.tasksketchgui.ProjectListActivity}: android.database.sqlite.SQLiteException: no such table: projects (code 1): , while compiling: SELECT * FROM projects pr,LOGIN lg, project_user pu WHERE LOGIN.USERNAME = 'pontan' AND pr._id = pu.project_id AND pu.user_id = LOGIN.ID
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.os.Handler.dispatchMessage(Handler.java:99)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.os.Looper.loop(Looper.java:137)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.app.ActivityThread.main(ActivityThread.java:5039)
08-08 15:28:39.710: E/AndroidRuntime(2213): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 15:28:39.710: E/AndroidRuntime(2213): at java.lang.reflect.Method.invoke(Method.java:511)
08-08 15:28:39.710: E/AndroidRuntime(2213): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-08 15:28:39.710: E/AndroidRuntime(2213): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-08 15:28:39.710: E/AndroidRuntime(2213): at dalvik.system.NativeStart.main(Native Method)
08-08 15:28:39.710: E/AndroidRuntime(2213): Caused by: android.database.sqlite.SQLiteException: no such table: projects (code 1): , while compiling: SELECT * FROM projects pr,LOGIN lg, project_user pu WHERE LOGIN.USERNAME = 'pontan' AND pr._id = pu.project_id AND pu.user_id = LOGIN.ID
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253)
08-08 15:28:39.710: E/AndroidRuntime(2213): at com.example.tasksketchgui.LoginDataBaseAdapter.getProjectsFromUser(LoginDataBaseAdapter.java:167)
08-08 15:28:39.710: E/AndroidRuntime(2213): at com.example.tasksketchgui.ProjectListActivity.onCreate(ProjectListActivity.java:34)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.app.Activity.performCreate(Activity.java:5104)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-08 15:28:39.710: E/AndroidRuntime(2213): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-08 15:28:39.710: E/AndroidRuntime(2213): ... 11 more
08-08 15:28:42.421: I/Process(2213): Sending signal. PID: 2213 SIG: 9
08-08 15:28:42.656: D/libEGL(2253): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
08-08 15:28:42.664: D/libEGL(2253): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
08-08 15:28:42.664: D/libEGL(2253): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
08-08 15:28:42.742: D/OpenGLRenderer(2253): Enabling debug mode 0
08-08 15:28:42.765: D/dalvikvm(2253): GC_CONCURRENT freed 121K, 2% free 9097K/9248K, paused 3ms+6ms, total 24ms
And yes, a lot of this is code is completely ripped from a tutorial, along with comments, and will be rewritten soon. How the table "LOGIN" is created sure is random when considering the rest.
I appreciate all the help I could get! Thanks! :-)

execSQL() can only execute one statement at a time.
Do not combine your SQL into a single DATABASE_CREATEstring separated by ;. Instead, execSQL() the individual SQL statements separately.
Also uninstall your app so the old database with incorrect tables gets removed.

Have you added the tables all at once?
If you have not removed the app and reinstalled it, the onCreate of your SQLiteOpenHelper will not be called again.

you are using LOGIN lg, and using as LOGIN.USERNAME , this would also throw you no such column exception so instead of referencing it as
SELECT * FROM projects pr,LOGIN lg, project_user pu WHERE LOGIN.USERNAME = 'pontan' AND pr._id = pu.project_id AND pu.user_id = LOGIN.ID
use
SELECT * FROM projects pr,LOGIN lg, project_user pu WHERE lg.USERNAME = 'pontan' AND pr._id = pu.project_id AND pu.user_id = lg.ID
your query should be :
String selectQuery = "SELECT * FROM " + TABLE_PROJECT + " pr," +
"LOGIN lg, " + TABLE_PROJECT_USER + " pu WHERE lg.USERNAME = '"
+ userName + "' AND pr." + KEY_ID + " = pu." + KEY_PROJECT_ID +
" AND pu." + KEY_USER_ID + " = lg.ID";

Related

My app keep stopping after i added data base code - Android Studio

I don't know what is the problem of my database, my app keep stopping after i added the data base code.
Please can you help with to fix that.
I have tried many times to figure it out but still not getting anywhere.
This is my data base code :
public class databaseOpenHelper extends SQLiteOpenHelper{
// Country table name
private static final String TABLE_NAME= "contacts";
// Country Table Columns names
private static final String KEY_ID = "id";
private static final String NAME = "Name";
private static final String PHONENO = "PhoneNo";
public databaseOpenHelper(Context context){
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(username Text primary key,password Text)");
// create the table for the first time
String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + NAME + " TEXT,"
+ PHONENO + " TEXT" + ")";
myDB.execSQL(CREATE_COUNTRY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int i, int i1) {
myDB.execSQL("drop Table if exists users");
}
public Boolean isertData(String username,String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username",username);
contentValues.put("password",password);
long result = myDB.insert("users",null,contentValues);
if(result == -1){
return false;
}
else {
return true;
}
}
public Boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?",new String[] {username});
if (cursor.getCount()>0){
return true;
}
else {
return false;
}
}
public Boolean checkusernamePassword(String username,String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?",new String[] {username,password});
if (cursor.getCount()>0){
return true;
}
else{
return false;
}
}
// method to add the contact
public void addcontact(ContactModel contact){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues c=new ContentValues();
c.put(NAME,contact.getName());
c.put(PHONENO,contact.getPhoneNo());
db.insert(TABLE_NAME,null,c);
db.close();
}
// method to retrieve all the contacts in List
public List<ContactModel> getAllContacts(){
List<ContactModel> list=new ArrayList<>();
String query="SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.rawQuery(query,null);
if(c.moveToFirst()) {
do {
list.add(new ContactModel(c.getInt(0),c.getString(1),c.getString(2)));
} while (c.moveToNext());
}
return list;
}
// get the count of data, this will allow user
// to not add more that five contacts in database
public int count(){
int count=0;
String query="SELECT COUNT(*) FROM "+TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c=db.rawQuery(query,null);
if(c.getCount()>0){
c.moveToFirst();
count=c.getInt(0);
}
c.close();
return count;
}
// Deleting single country
public void deleteContact(ContactModel contact) {
SQLiteDatabase db = this.getWritableDatabase();
int i=db.delete(TABLE_NAME,KEY_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
db.close();
}
}
And this is my logcat :
FATAL EXCEPTION: main
Process: com.example.localisation, PID: 11700
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.localisation/com.example.localisation.phone}: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1047)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:654)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:590)
at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:62)
at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1546)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1485)
at com.example.localisation.databaseOpenHelper.getAllContacts(databaseOpenHelper.java:108)
at com.example.localisation.phone.onCreate(phone.java:81)
at android.app.Activity.performCreate(Activity.java:8051)
at android.app.Activity.performCreate(Activity.java:8031)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loopOnce(Looper.java:201) 
at android.os.Looper.loop(Looper.java:288) 
at android.app.ActivityThread.main(ActivityThread.java:7839) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003) 
The failure is saying that there is not a table called contacts as per
Caused by: android.database.sqlite.SQLiteException: no such table: contacts (code 1 SQLITE_ERROR): , while compiling: SELECT * FROM contacts
Running your code and then using the errant getAllContacts method, as indicated in the log by:-
at com.example.localisation.databaseOpenHelper.getAllContacts(databaseOpenHelper.java:108)
Works.
As such it is highly likely that you have added the contacts cable after previously running the App and that this has created the database. The database persists and thus will still exist from on run to the other. As such the onCreate method will not be called, as it is only called once when the database is created.
The easy fix is to uninstall the App and rerun. However, this will delete any existing data.
If you need to keep any data then you should a) increase the version number and then b) add code to the onUpgrade method to create the new table (same code).
For example:-
a)
public databaseOpenHelper(Context context){
super(context,"Login.db",null,2 /*<<<<<<<<<< CHANGED */);
}
b)
#Override
public void onUpgrade(SQLiteDatabase myDB, int i, int i1) {
//myDB.execSQL("drop Table if exists users");
if (i1 == 2) {
String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + NAME + " TEXT,"
+ PHONENO + " TEXT" + ")";
myDB.execSQL(CREATE_COUNTRY_TABLE);
}
}
You can the see that the contacts table has been created by using App Inspection e.g.
according to the error code you uploaded i noticed this SELECT * FROM contacts which means that you don't have table named contacts in you sqlite database so i recommend you, for testing you should use sqlite browser to create database and add data to it and then use it in your android studio project. if you get any problem fearther don't hesitate to ask it in comments thanks.

How to get info from Database according to the id

I am making an App that Adds Groceries to a list , I have a Product class which contains all of it's properties , so I am trying to get a product from the Database Table according to it's Id and return it ,but it keeps telling me that my app is stopping whenever i call my function , this is my code
public Product GetProductById(String id)
{
SQLiteDatabase db=this.ourHelper.getReadableDatabase();
Product p=null;
Cursor cr;
cr = db.query(PRODUCTS_TABLE, null, PRODUCT_ID+"="+id, null, null, null, null);
cr.moveToFirst();
if(!cr.isAfterLast()) {
p=new Product();
p.setId(cr.getInt(0));
p.setName(cr.getString(1));
p.setQuantity(cr.getInt(2));
p.setPrice(cr.getDouble(3));
p.setAllergens(cr.getString(4));
p.setPurchased(cr.getInt(5));
p.setImage(cr.getBlob(6));
p.setPriority(cr.getInt(7));
}
return p;
}
this code is not working and i don't know where the error is.
here are my Database columns(names and types...):
public static final String DB_NAME="db_groceries";
public static final int DB_VER=1;
public static final String PRODUCT_NAME = "name";
public static final String PRODUCT_QUANTITY = "quantity";
public static final String PRODUCT_PRICE = "price";
public static final String PRODUCT_ALLERGENS = "allergens";
public static final String PRODUCT_PRIORITY = "priority";
public static final String PRODUCT_ID = "_id";
public static final String PRODUCT_IMAGE = "image";
public static final String PRODUCTS_TABLE = "groceries";
public static final String PRODUCTS_PURCHASED = "purchased";
public static final String SCRIPT_CREATE_PRODUCTS_TABLE = "create table "
+ PRODUCTS_TABLE + "(" + PRODUCT_ID +
" integer primary key autoincrement," +
PRODUCT_NAME + " text not null," +
PRODUCT_QUANTITY + " integer not null," +
PRODUCT_PRICE + " real not null," +
PRODUCT_ALLERGENS + " text not null, " +
PRODUCTS_PURCHASED + " integer not null, " +
PRODUCT_IMAGE + " blob," +
PRODUCT_PRIORITY + " integer not null)";
can you figure out where my mistake is?
I believe that your issue is that you have not instantiated ourHelper before calling the GetProductById method.
If you haven't then you would get a null pointer exception similar to :-
11-01 19:54:35.925 1420-1420/axtest.axtest E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{axtest.axtest/axtest.axtest.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at axtest.axtest.MainActivity.GetProductById(MainActivity.java:134)
at axtest.axtest.MainActivity.onCreate(MainActivity.java:35)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
To resolve this you need to instantiate ourHelper along the lines of
**`ourHelper = new DatabaseHelper(this);`**
Noting that Databasehelper may be different (you haven't said what the class name is) and also that the signature may also be different (it will be dependent upon the code in the Database helper although frequently the signature is as above).
Otherwise you code works fine. However, it may also be that you have changed the structure of the table but not deleted the database. To rule out this delete the App's data and rerun the App.

sqlite for android, how to update table

I found a number of links on stack overflow dealing with this but none of the solutions have worked for me so here goes:
I am trying to add a column to hold a date (and may need to add a time column in future) but am having some trouble since the table had already been created. Here is the database code:
public class MyDatabase {
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "Date";
public static final String KEY_SYS = "Systolic";
public static final String KEY_DIA = "Diastolic";
private static final String DATABASE_NAME = "Blood Pressures";//Used to reference database
private static final String DATABASE_TABLE = "bloodPressureTable";//Tables can be stored in database
// this will be used to store ID, date, systolic and diastolic
private static final int DATABASE_VERSION = 9;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
public String getData() {
String[] columns = new String[]{KEY_ROWID, KEY_SYS, KEY_DIA};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iSys = c.getColumnIndex(KEY_SYS);
int iDia = c.getColumnIndex(KEY_DIA);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { //if cursor is after position of our last entry, then stop
result = result + c.getString(iRow) + //get ROW_ID column, get name of first row and hotness, create new string
" " + c.getString(iSys) + " " +
c.getString(iDia) + "\n";
}
return result;
}
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) { //This is only called when we first create a database
// when then we will just cycle through onUpgrade, passes a database in
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" + //create a table called table name
//adds columns inside parenthesise
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + //integer increment automatically, referenced by keyID
KEY_DATE + "TEXT NOT NULL, " + //SQL uses the word text rather than string
KEY_SYS + " INTEGER, " +
KEY_DIA + " INTEGER);"
);
}
#Override //called if oncreate has already been called
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); //If table name exists it is going
// to drop it and then all we have to do is call our onCreate method
//Removes table added by create table statement
//onCreate(db);
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE " + DATABASE_TABLE +
" ADD COLUMN " + KEY_DATE + " TEXT NOT NULL, ");
}
}
}
//Constructor below
public MyDatabase(Context c) {
ourContext = c;
}
//open() allows us to open and write to database
public MyDatabase open() {
ourHelper = new DbHelper(ourContext); // this is a new instance of that object passing in the context
ourDatabase = ourHelper.getWritableDatabase();//here we set up our database,
// getting the writeable database. This will open up our database through our helper
return this;
}
public void close() {
ourHelper.close(); //close our SQLiteOpenHelper
}
public long createEntry(int systolic, int diastolic) {
ContentValues cv = new ContentValues();
Calendar c = Calendar.getInstance();
String s = Integer.toString(c.get(Calendar.DAY_OF_MONTH)) + "/" + Integer.toString(c.get(Calendar.MONTH)) +
"/" + Integer.toString(c.get(Calendar.YEAR));
cv.put(KEY_DATE, s);
cv.put(KEY_SYS, systolic);
cv.put(KEY_DIA, diastolic);//Put the string in KEY_NAME column?
return ourDatabase.insert(DATABASE_TABLE, null, cv); //we want this method to return this line
}
}
Can someone advise me of a solution please? As you can see I have tried two different methods (one is commented out in onUpgrade). As you can see I am on version 10 from playing about with it already!
Here is the logcat:
03-02 16:03:48.416 1811-1811/com.dissertation.michael.biolog E/SQLiteLog﹕ (1) Cannot add a NOT NULL column with default value NULL
03-02 16:03:48.416 1811-1811/com.dissertation.michael.biolog D/AndroidRuntime﹕ Shutting down VM
03-02 16:03:48.416 1811-1811/com.dissertation.michael.biolog W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41696bd8)
03-02 16:03:48.416 1811-1811/com.dissertation.michael.biolog E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.dissertation.michael.biolog, PID: 1811
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1111, result=-1, data=Intent { (has extras) }} to activity {com.dissertation.michael.biolog/com.dissertation.michael.biolog.MainActivity}: android.database.sqlite.SQLiteException: Cannot add a NOT NULL column with default value NULL (code 1): , while compiling: ALTER TABLE bloodPressureTable ADD COLUMN DateTEXT NOT NULL
at android.app.ActivityThread.deliverResults(ActivityThread.java:3391)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3434)
at android.app.ActivityThread.access$1300(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: Cannot add a NOT NULL column with default value NULL (code 1): , while compiling: ALTER TABLE bloodPressureTable ADD COLUMN DateTEXT NOT NULL
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.executeSql(SQLiteDatabase.java:1672)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1603)
at com.dissertation.michael.biolog.MyDatabase$DbHelper.onUpgrade(MyDatabase.java:75)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:257)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.dissertation.michael.biolog.MyDatabase.open(MyDatabase.java:90)
at com.dissertation.michael.biolog.MainActivity.onActivityResult(MainActivity.java:170)
at android.app.Activity.dispatchActivityResult(Activity.java:5430)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3387)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3434)
at android.app.ActivityThread.access$1300(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
03-02 16:03:48.424 1811-1811/com.dissertation.michael.biolog I/Process: Sending signal. PID: 1811 SIG: 9
Alternatively (and preferably if it is simple) a method to delete my table entirely so that version 1 is created again would be ideal. (No useful data has been entered into the database at this point)... Cheers!
Your application is crashing due to java.lang.NumberFormatException: Invalid int: "300-400", it means you are passing invalid format of INTEGER and 300-400 is not a valid int.
P.S. If you want to enter 300-400 into db column use TEXT or VARCHAR(15) as Datatype of your column

SQLite Database wont compile correctly?

I am creating an android app which monitors attendance, although I am getting errors when I attempt to login with a users details from the sqlite database saying a column doesnt exist.
DBHelper.class
package uk.ac.qub.qubattend;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 6;
// Database Name
private static final String DATABASE_NAME = "QUBAttendanceDB";
// tasks table name
private static final String TABLE_StudentInfo = "studentinfo";
// Table Columns names
// id column
private static final String KEY_ID = "StudentId";
// question column
private static final String KEY_PASS = "password";
// answer column
private static final String KEY_WEEK1 = "Week1";
private static final String KEY_WEEK2 = "Week2";
private static final String KEY_WEEK3 = "Week3";
private static final String KEY_WEEK4 = "Week4";
private static final String KEY_WEEK5 = "Week5";
private static final String KEY_WEEK6 = "Week6";
private static final String KEY_WEEK7 = "Week7";
private static final String KEY_WEEK8 = "Week8";
private static final String KEY_WEEK9 = "Week9";
private static final String KEY_WEEK10 = "Week10";
private static final String KEY_WEEK11 = "Week11";
private static final String KEY_WEEK12 = "Week12";
// Database constant
private SQLiteDatabase dbase;
/**
* Method to check the db name and version
*
* #param context
*/
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase = db;
// Create Table method
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_StudentInfo + " ( "
+ KEY_ID + " TEXT," + KEY_PASS + " TEXT, " + KEY_WEEK1
+ "TEXT, " + KEY_WEEK2 + "TEXT, " + KEY_WEEK3 + "TEXT, "
+ KEY_WEEK4 + "TEXT, " + KEY_WEEK5 + "TEXT, " + KEY_WEEK6
+ "TEXT, " + KEY_WEEK7 + "TEXT, " + KEY_WEEK8 + "TEXT, "
+ KEY_WEEK9 + "TEXT, " + KEY_WEEK10 + "TEXT, " + KEY_WEEK11
+ "TEXT, " + KEY_WEEK12 + "TEXT" + ")";
db.execSQL(sql);
// implementing add questions method
addAttendance();
}
/**
* Add Questions Method using Question Object with question, 4 options and
* correct answer
*/
private void addAttendance() {
Student s1 = new Student("40023798", "letmeinhere", "90", "80", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0");
this.addStudent(s1);
}
// Checking that existing database table called TABLE_QUEST is dropped
#Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_StudentInfo);
// Create tables again
onCreate(db);
}
/**
* method for adding a new question into the database
*
* #param quest
*/
public void addStudent(Student student) {
ContentValues values = new ContentValues();
values.put(KEY_ID, student.getStudentId());
values.put(KEY_PASS, student.getPassword());
values.put(KEY_WEEK1, student.getWeek1());
values.put(KEY_WEEK2, student.getWeek2());
values.put(KEY_WEEK3, student.getWeek3());
values.put(KEY_WEEK4, student.getWeek4());
values.put(KEY_WEEK5, student.getWeek5());
values.put(KEY_WEEK6, student.getWeek6());
values.put(KEY_WEEK7, student.getWeek7());
values.put(KEY_WEEK8, student.getWeek8());
values.put(KEY_WEEK9, student.getWeek9());
values.put(KEY_WEEK10, student.getWeek10());
values.put(KEY_WEEK11, student.getWeek11());
values.put(KEY_WEEK12, student.getWeek12());
// Inserting Row with question
dbase.insert(TABLE_StudentInfo, null, values);
}
/**
* Method to move questions in database to an ArrayList
*
* #return
*/
public ArrayList<Student> getAllStudents() {
ArrayList<Student> studentList = new ArrayList<Student>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_StudentInfo;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Student student = new Student();
student.setStudentId(cursor.getString(0));
student.setPassword(cursor.getString(1));
student.setWeek1(cursor.getString(2));
student.setWeek2(cursor.getString(3));
student.setWeek3(cursor.getString(4));
student.setWeek4(cursor.getString(5));
student.setWeek5(cursor.getString(6));
student.setWeek6(cursor.getString(7));
student.setWeek7(cursor.getString(8));
student.setWeek8(cursor.getString(9));
student.setWeek9(cursor.getString(10));
student.setWeek10(cursor.getString(11));
student.setWeek11(cursor.getString(12));
student.setWeek12(cursor.getString(13));
studentList.add(student);
} while (cursor.moveToNext());
}
// return question list
return studentList;
}
/**
* Method to Check Database number of rows
*
* #return
*/
public int rowcount() {
int row = 0;
// select all query
String selectQuery = "SELECT * FROM " + TABLE_StudentInfo;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
row = cursor.getCount();
return row;
}
}
Below is the log which displays the error but I dont know why its throwing the error :
01-17 16:26:51.616: E/SQLiteLog(1667): (1) table studentinfo has no column named Week8
01-17 16:26:51.656: E/SQLiteDatabase(1667): Error inserting StudentId=40023798 Week8=0 Week9=0 Week4=0 Week5=0 password=letmeinhere Week6=0 Week7=0 Week3=0 Week2=80 Week12=0 Week1=90 Week11=0 Week10=0
01-17 16:26:51.656: E/SQLiteDatabase(1667): android.database.sqlite.SQLiteException: table studentinfo has no column named Week8 (code 1): , while compiling: INSERT INTO studentinfo(StudentId,Week8,Week9,Week4,Week5,password,Week6,Week7,Week3,Week2,Week12,Week1,Week11,Week10) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at uk.ac.qub.qubattend.DBHelper.addStudent(DBHelper.java:109)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at uk.ac.qub.qubattend.DBHelper.addAttendance(DBHelper.java:73)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at uk.ac.qub.qubattend.DBHelper.onCreate(DBHelper.java:62)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at uk.ac.qub.qubattend.DBHelper.onUpgrade(DBHelper.java:83)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:257)
01-17 16:26:51.656: E/SQLiteDatabase(1667): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
If anyone knows why it is not picking up column 8 I would really appreciate it!
All of the KEY_WEEK... values have "TEXT, " appended after them, not " TEXT, ", and so your column and datatype names should be running together.
You may be better served either using StringBuilder (faster) or String.format() (easier to read), rather than string concatenation.

Android getting Error inserting to databse and code 19: constraint failed

i'm wrote simple DataBaseHelper to use SQlite in android. after create class as :
public class DatabaseHandler extends SQLiteOpenHelper{
private static String DB_PATH = "";
private static final String DATABASE_NAME = "tsms";
private static String RECEIVE_FIELDS_TABLE = "ReceiveFields";
private static final String COLUMN_ID = "id";
private static final String COLUMN_LASTID = "lastId";
private static final String COLUMN_SMSNUMBER = "smsNumber";
private static final String COLUMN_MOBILENUMBER = "mobileNumber";
private static final String COLUMN_SENDERNAME = "senderName";
private static final String COLUMN_SMSBODY = "smsBody";
private static final String COLUMN_RECEIVEDATE = "receiveDate";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase mDataBase;
/* UPDATE DATABASE_CREATE FIELD*/
private static final String DATABASE_CREATE = "CREATE TABLE " + RECEIVE_FIELDS_TABLE + "("
+ COLUMN_ID + " INTEGER UNIQUE , "
+ COLUMN_LASTID + " INTEGER UNIQUE , "
+ COLUMN_SMSNUMBER + " VARCHAR UNIQUE , "
+ COLUMN_MOBILENUMBER + " VARCHAR , "
+ COLUMN_SENDERNAME + " VARCHAR , "
+ COLUMN_SMSBODY + " TEXT , "
+ COLUMN_RECEIVEDATE + " VARCHAR , PRIMARY KEY (" + COLUMN_ID + ", " + COLUMN_LASTID + ", " + "))";
private Context context;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + RECEIVE_FIELDS_TABLE);
// Create tables again
onCreate(sqLiteDatabase);
}
// Adding new fields
public void addToReceived(ReceiveFields fields) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_LASTID, fields.getLastId()); // ReceiveFields last ID
values.put(COLUMN_MOBILENUMBER, fields.getMobileNumber()); // ReceiveFields Mobile Number
values.put(COLUMN_SENDERNAME, fields.getSenderName()); // ReceiveFields Mobile Number
values.put(COLUMN_SMSBODY, fields.getSmsBody()); // ReceiveFields Mobile Number
values.put(COLUMN_SMSNUMBER, fields.getSmsNumber()); // ReceiveFields Mobile Number
values.put(COLUMN_MOBILENUMBER, fields.getMobileNumber()); // ReceiveFields Mobile Number
values.put(COLUMN_RECEIVEDATE, String.valueOf(fields.getReceiveDate())); // ReceiveFields Mobile Number
// Inserting Row
db.insert(RECEIVE_FIELDS_TABLE, null, values);
db.close(); // Closing database connection
}
}
I get Error Inserting to database with this way:
db.addToReceived(new ReceiveFields(
Long.valueOf(str1[0]),
str1[1],
str1[2],
URLDecoder.decode(str1[3], "UTF-8"),
URLDecoder.decode(str1[4], "UTF-8"),
ct.getGregorianDate()));
Log.i Result:
29904757 30007227 00120504001 00120504001 sssasaS 2014/8/3
full LogCate Result:
08-28 06:35:29.974 2698-2698/ir.tsms E/Database﹕ Error inserting lastId=29904755 receiveDate=2014/8/3 senderName=09127574751 mobileNumber=09127574751 smsNumber=30007227 smsBody=
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:55)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1549)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
at ir.tsms.DataBase.DatabaseHandler.addToReceived(DatabaseHandler.java:96)
at ir.tsms.wsdl.TSMS.getReceivedSMS(TSMS.java:141)
at ir.tsms.Receive.ResivedSMS.getResivedSMS(ResivedSMS.java:41)
at ir.tsms.Receive.ResivedSMS.<init>(ResivedSMS.java:36)
at ir.tsms.Activities.DashboardActivity.onTabSelected(DashboardActivity.java:160)
at android.support.v7.app.ActionBarImplBase.selectTab(ActionBarImplBase.java:486)
at android.support.v7.app.ActionBarImplBase.addTab(ActionBarImplBase.java:410)
at android.support.v7.app.ActionBarImplBase.addTab(ActionBarImplBase.java:401)
at ir.tsms.Activities.DashboardActivity.onCreate(DashboardActivity.java:68)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
at ir.tsms.wsdl.TSMS.getReceivedSMS(TSMS.java:141) line is :
db.addToReceived(new ReceiveFields(
Check these things, it may causes by these reason:
1- you did not add COLUMN_ID to values so it is null.
2-COLUMN_ID and COLUMN_LASTID are not UNIQUE (clear your database or android app data , maybe it stored in your db first time you ran it and now again you want to add you can not because it is not unique now, every time you run, your db is in memory and it is not clread, in order to clear it you must remove app data or run delete SQL statement)
so i suggest you to see your DB file, if you use eclipse try this:
http://www.tylerfrankenstein.com/browse-android-emulator-sqlite-database-eclipse
3-COLUMN_ID and COLUMN_LASTID are not int i mean fields.getLastId() may return String
check exactly your table defination and your values to insert !!!
It seems like you're trying to insert null as smsBody but your table does not allow you to do this as it has NOT NULL constraint for this column.

Categories