I've created a class which extends SQLiteOpenHelper class and trying to create a DB and insert a dummy record when my Android app launches.
However I get an error 'table gallery has no column named title'.
No error being thrown for the other columns and they're all created in the same way.
The error:
12-19 14:24:30.401 4801-4807/? E/art: Failed sending reply to debugger: Broken pipe
12-19 14:24:30.808 4801-4801/? E/SQLiteLog: (1) table gallery has no column named title
12-19 14:24:30.810 4801-4801/? E/SQLiteDatabase: Error inserting title=First pic artist=James Liscombe rank=3 year=1992
android.database.sqlite.SQLiteException: table gallery has no column named title (code 1): , while compiling: INSERT INTO gallery(title,artist,rank,year) VALUES (?,?,?,?)
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.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at com.example.jamesliscombe.cet325assignment.DBHandler.addPicture(DBHandler.java:59)
at com.example.jamesliscombe.cet325assignment.Home.onCreate(Home.java:35)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
The class I've created which extends SQLiteOpenHelper:
public class DBHandler extends SQLiteOpenHelper {
//DB Info
private static final int DB_VERSION = 2;
private static final String DB_NAME = "louvre";
private static final String TABLE_NAME = "gallery";
//Table column names
private static final String KEY_ID = "id";
private static final String KEY_RANK = "rank";
private static final String KEY_ARTIST = "artist";
private static final String KEY_TITLE = "title";
private static final String KEY_YEAR = "year";
public DBHandler(Context context) {
super(context, DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_GALLERY_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + "INTEGER PRIMARY KEY," + KEY_RANK + "INTEGER,"
+ KEY_ARTIST + "TEXT," + KEY_TITLE + "TEXT," + KEY_YEAR + "TEXT" + ")";
db.execSQL(CREATE_GALLERY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop older table if it exists
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
//Create table again
onCreate(db);
}
//Adding a new gallery record
public void addPicture(Picture picture) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RANK, picture.getRank());
values.put(KEY_ARTIST, picture.getArtist());
values.put(KEY_TITLE, picture.getTitle());
values.put(KEY_YEAR, picture.getYear());
//Insert row
db.insert(TABLE_NAME, null, values);
//Close db connection
db.close();
}
//Reading a single record
public Picture getPicture(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] {
KEY_ID,KEY_RANK,KEY_ARTIST,KEY_TITLE,KEY_YEAR
},KEY_ID + "=?", new String[] {
String.valueOf(id) }, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
Picture contact = new Picture(Integer.parseInt(cursor.getString(0)),Integer.parseInt(cursor.getString(1)),cursor.getString(2),cursor.getString(3), cursor.getString(4));
return contact;
}
//Reading all records
public List<Picture> getAllPictures() {
List<Picture> galleryList = new ArrayList<Picture>();
//Select all query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Loop through all rows and add to galleryList.
if(cursor.moveToFirst()) {
do {
Picture picture = new Picture();
picture.setId(Integer.parseInt(cursor.getString(0)));
picture.setRank(Integer.parseInt(cursor.getString(1)));
picture.setArtist(cursor.getString(2));
picture.setTitle(cursor.getString(3));
picture.setYear(cursor.getString(4));
galleryList.add(picture);
} while (cursor.moveToNext());
}
return galleryList;
}
//Get total number of records
public int getGallerySize() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
//Update gallery items
public int updateGallery(Picture picture) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_RANK, picture.getRank());
values.put(KEY_ARTIST, picture.getArtist());
values.put(KEY_TITLE, picture.getTitle());
values.put(KEY_YEAR, picture.getYear());
return db.update(TABLE_NAME, values, KEY_ID + " = ?", new String[]{String.valueOf(picture.getId())});
}
//Delete a gallery record
public void deletePicture(Picture picture) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?", new String[] {String.valueOf(picture.getId())});
db.close();
}
}
Where I'm using the class and inserting a dummy record:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Create our DB
DBHandler db = new DBHandler(this);
//Insert some test data into our db
db.addPicture(new Picture(1,3,"James","First pic","1992"));
You already have a database installed in your device that does not contain title column so when your try to add the dummy data with the value for Title column, you get the error.
This can be fixed by deleting the old already created database and then running your application again so that new database is created.
To delete the existing database, go to Android Device Monitor -> data -> data and then search for your app's package name. Click on your app's package name and then delete the database folder inside it and then run your app again.
Related
I'm making an Android Note Taking app, which save a note and display it in list of notes. if you touch each note it show a title and details of it in another layout. i can save note and i can show them in list but my problem is when i try to use intent to show that specific note's title and details.
what is do is use intent.putExtra("ID",...) and get that intent and show the note's detail and title with use of its ID. but i get "android.database.CursorIndexOutOfBoundsException" error and app crash.
this is part of my Note class:
public class Note {
private String Title, Content, Date, Time;
private long ID;
Note(){}
Note(String Title,String Content,String Date,String Time){
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
Note(long ID,String Title,String Content,String Date,String Time) {
this.ID = ID;
this.Title = Title;
this.Content = Content;
this.Date = Date;
this.Time = Time;
}
this is my NoteDataBase:
public class NoteDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "notedbs";
private static final String DATABASE_TABLE = "notestables";
//column name for database tables
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME = "time";
public NoteDataBase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
//create table
String query = "CREATE TABLE " + DATABASE_TABLE + "("+
KEY_ID + " INT PRIMARY KEY," +
KEY_TITLE + " TEXT," +
KEY_CONTENT + " TEXT," +
KEY_DATE + " TEXT," +
KEY_TIME + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion >= newVersion) {
return;
} else {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public long addNote(Note note) {
SQLiteDatabase db= this.getWritableDatabase();
ContentValues c = new ContentValues();
c.put(KEY_TITLE,note.getTitle());
c.put(KEY_CONTENT,note.getContent());
c.put(KEY_DATE,note.getDate());
c.put(KEY_TIME,note.getTime());
long ID = db.insert(DATABASE_TABLE,"null",c);
//c.put(KEY_ID,ID);
Log.d("Inserted", "addNote: note with id number " + KEY_ID + " has been inserted");
return ID;
}
public Note getNote(long ID){
//Select * from DatabaseTable where id = 1
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor != null)
cursor.moveToFirst();
return new Note(cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4));
}
public List<Note> getNotes() {
SQLiteDatabase db = getReadableDatabase();
List<Note> allNotes = new ArrayList<>();
// Select * from databaseTable
String query = "SELECT * FROM "+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do{
Note note = new Note();
note.setID(cursor.getLong(0));
note.setTitle(cursor.getString(1));
note.setContent(cursor.getString(2));
note.setDate(cursor.getString(3));
note.setTime(cursor.getString(4));
allNotes.add(note);
}while(cursor.moveToNext());
}
return allNotes;
}
}
this is my DetailActivity :
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Intent intent = getIntent();
Long id = intent.getLongExtra("ID",0);
NoteDataBase db = new NoteDataBase(this);
Note note = db.getNote(id);
Toast.makeText(this, "Title is "+ note.getTitle(), Toast.LENGTH_SHORT).show();
my error is in lines of both my Intent in DetailActivity and getNote method of NoteDataBase.
By defining the column id of your table as:
INT PRIMARY KEY
it is not defined as AUTOINCREMENT, so in every row that you add to the table, the column id is null, because you don't provide any value for it.
The value that is returned by the method addNote(), when you insert a new row, is the value of the column rowid and not the column id.
You must define the column as:
INTEGER PRIMARY KEY
You can also add AUTOINCREMENT in the above definition, if you don't want any deleted ids to be reused.
After you make this change you must uninstall the app from the device, so that the db is deleted and rerun to recreate the db and the table.
Also in the method getNote(), first check with moveToFirst() if the query returned any row:
public Note getNote(long ID){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,
new String []{KEY_ID,KEY_TITLE,KEY_CONTENT,
KEY_DATE,KEY_TIME},KEY_ID + "=?",
new String[]{String.valueOf(ID)},
null, null,null);
if(cursor.moveToFirst())
return new Note(
cursor.getLong(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3),cursor.getString(4)
);
else return null;
}
This question already has answers here:
Android column '_id' does not exist?
(8 answers)
Closed 4 years ago.
Can someone assist me in getting my list to populate using setMultiChoiceItems with a cursor? My AlertDialog pops up with the title and buttons, but nothing in the list. I have confirmed there is at least one item in the database and that should show up on the list but it doesn't currently. I think it has something to do with my cursor. Thank you.
String isCheckedColumn;
String labelColumn;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new MyDBHandler(this);
// CHECK INSERTION TO DATABASE WORKS AND PRINT TO LOGCAT
mydb.insertAllergy("Nuts", "0");
ArrayList<String> s = mydb.getAllAllergies();
System.out.println(s.get(0));
// INITIALIZE VARIABLES FOR LIST POPUP
isCheckedColumn = "selected";
labelColumn = "allergy";
}
/** LIST SELECTION POPUP */
public void selectAllergens() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Allergens");
builder.setMultiChoiceItems(cursor, isCheckedColumn, labelColumn, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId, boolean isSelected) {
if(isSelected) {
System.out.println("onClick if");
} else {
System.out.println("onClick else");
}
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
Dialog dialog = builder.create();
dialog.show();
}
Here's my database helper class, MyDBHandler. I thought maybe there should be a getCursor method here so when I need to initialize a cursor I can do it with that. It didn't work.
public class MyDBHandler extends SQLiteOpenHelper {
// DATABASE INFORMATION
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "AllergiesDB.db";
private static final String TABLE_NAME = "allergies_list";
private static final String COLUMN_ID = "allergy_id";
private static final String COLUMN_ALLERGY = "allergy";
private static final String COLUMN_SELECTED = "selected";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY, " +
COLUMN_ALLERGY + " TEXT, " + COLUMN_SELECTED + " TEXT)";
// INITIALIZE DATABASE
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertAllergy(String allergy, String isChecked) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ALLERGY, allergy);
contentValues.put(COLUMN_SELECTED, isChecked);
db.insert(TABLE_NAME, null, contentValues);
return true;
}
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where " + COLUMN_ID + "=" + id + "", null);
return cursor;
}
public boolean updateAllergies(Integer id, String allergy, String isChecked) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ALLERGY, allergy);
contentValues.put(COLUMN_SELECTED, isChecked);
db.update(TABLE_NAME, contentValues, "id = ? ", new String[] {Integer.toString(id)});
return true;
}
public Integer deleteAllergy(Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "id = ? ", new String[] {Integer.toString(id)});
}
public ArrayList<String> getAllAllergies() {
ArrayList<String> array_list = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
cursor.moveToFirst();
while(cursor.isAfterLast() == false) {
array_list.add(cursor.getString(cursor.getColumnIndex(COLUMN_ALLERGY)));
cursor.moveToNext();
}
return array_list;
}
public ArrayList<String> getSelectedAllergies() {
ArrayList<String> array_list = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
cursor.moveToFirst();
while(cursor.isAfterLast() == false) {
array_list.add(cursor.getString(cursor.getColumnIndex(COLUMN_SELECTED)));
cursor.moveToNext();
}
return array_list;
}
public Cursor getCursor() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
cursor.moveToFirst();
return cursor;
}
}
This is what the popup looks like:
AlertDialog Popup
Here's the error when using 'cursor = mydb.getCursor();'. Clicking on the button that opens the AlertDialog produces the error. The cursor initialization is in the onCreate method of the MainActivity so the initialization isn't causing the crash. The use of the cursor in setMultiChoiceItems is the cause, leading me to believe the cursor wasn't initialized properly.
--------- beginning of crash
08-24 20:53:50.330 11277-11277/com.healthydreams.lpa.allergyscanner E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.healthydreams.lpa.allergyscanner, PID: 11277
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalArgumentException: column '_id' does not exist. Available columns: [allergy_id, allergy, selected]
at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:340)
at android.widget.CursorAdapter.init(CursorAdapter.java:180)
at android.widget.CursorAdapter.<init>(CursorAdapter.java:144)
at android.support.v7.app.AlertController$AlertParams$2.<init>(AlertController.java:1009)
at android.support.v7.app.AlertController$AlertParams.createListView(AlertController.java:1009)
at android.support.v7.app.AlertController$AlertParams.apply(AlertController.java:965)
at android.support.v7.app.AlertDialog$Builder.create(AlertDialog.java:982)
at com.healthydreams.lpa.allergyscanner.MainActivity.selectAllergens(MainActivity.java:148)
at com.healthydreams.lpa.allergyscanner.MainActivity.openProfiles(MainActivity.java:85)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I assume when you first ran your code you would have got colum_id exception. column '_id' does not exist and the app would have crashed. What this means is you would have to create your primary key like this _columnId. See the underscore at the start. You can read more about the why here. But for now, remember sqllite needs the _ at the start of the primary key column.
About "_id" field in Android SQLite
Once you have done that change, next you would face a problem with the select query in your getCursor() method. Sometimes the * does not work as it needs the explicit name of your columns, so change the query to
select " + COLUMN_ID + "," + COLUMN_ALLERGY + "," + COLUMN_SELECTED + " from " + TABLE_NAME
I am posting these changes below, I have not called any other method as I wanted to give you a start where you are not seeing crashes in the app.
private static final String COLUMN_ID = " _columnId";
private static final String COLUMN_ALLERGY = "allergy";
private static final String COLUMN_SELECTED = "selected";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" + COLUMN_ID " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_ALLERGY + ", " + COLUMN_SELECTED + ")";
......
public Cursor getCursor() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select " + COLUMN_ID + "," +
COLUMN_ALLERGY + "," + COLUMN_SELECTED + " from " + TABLE_NAME,
null);
cursor.moveToFirst();
return cursor;
}
You can call the method which would populate data in the database and then call the getCursor method. Once you have that, entries would appear in the dialog box.
Let me know if you face any issue.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Im trying to store data from some editTexts on a local android database and then eventually show it on a listview, but right now Im getting an error that says a column doesnt exist, I was following a tutorial on android hive so some of the variable names might look weird, but everything should be accurate.
StackTrace
2038-12038/com.example.adrian.legioncheck_in E/SQLiteLog﹕ (1) table contacts has no column named Longitude
08-25 12:12:19.121 12038-12038/com.example.adrian.legioncheck_in E/SQLiteDatabase﹕ Error inserting Latitude=-85 Longitude=50 POnumber=255902
android.database.sqlite.SQLiteException: table contacts has no column named Longitude (code 1): , while compiling: INSERT INTO contacts(Latitude,Longitude,POnumber) VALUES (?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:923)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:534)
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:1523)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1395)
at com.example.adrian.legioncheck_in.DatabaseHandler.addContact(DatabaseHandler.java:67)
at com.example.adrian.legioncheck_in.MapsActivity.SaveAction(MapsActivity.java:67)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3850)
at android.view.View.performClick(View.java:4470)
at android.view.View$PerformClick.run(View.java:18593)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5867)
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:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Database Handle.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "POnumber";
private static final String KEY_PH_NO = "Latitude";
private static final String KEY_LONG = "Longitude";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_LONG + " TEXT" +")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
/* line 67 */ void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO, KEY_LONG }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setPO(cursor.getString(1));
contact.setLat(cursor.getString(2));
contact.setLong(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getPO());
values.put(KEY_PH_NO, contact.getLat());
values.put(KEY_LONG, contact.getLong());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
contact.java
public class Contact {
//private variables
int _id;
String _PO;
String _lat;
String _longi;
// Empty constructor
public Contact(){
}
// constructor
public Contact(int id, String PO, String _lat, String _longi){
this._id = id;
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// constructor
public Contact(String PO, String _lat, String _longi){
this._PO = PO;
this._lat = _lat;
this._longi = _longi;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getPO(){
return this._PO;
}
// setting name
public void setPO(String PO){
this._PO = PO;
}
// getting phone number
public String getLat(){
return this._lat;
}
// setting phone number
public void setLat(String lat){
this._lat = lat;
}
public String getLong()
{
return this._longi;
}
public void setLong(String longi)
{
this._longi = longi;
}
}
Button that saves data to database:
public void SaveAction(View view)
{
EditText po = (EditText)findViewById(R.id.POnumber);
String PO = po.getText().toString();
EditText textlat = (EditText)findViewById(R.id.textLat);
String LAT = textlat.getText().toString();
EditText textlong = (EditText)findViewById(R.id.textLong);
String LONG = textlong.getText().toString();
DatabaseHandler db = new DatabaseHandler(MapsActivity.this);
db.addContact(new Contact(PO,LAT,LONG));
// Reading all Data
Log.d("Reading: ", "Reading all inputs..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,PO number: " + cn.getPO() + " ,Latitude: " + cn.getLat() + " ,Longitude: " + cn.getLong();
// Writing Data to log
Log.d("Name: ", log);
}
}
KEY_PH_NO + " TEXT" + KEY_LONG + " TEXT" +")"
Add the missing , before KEY_LONG:
KEY_PH_NO + " TEXT," + KEY_LONG + " TEXT" +")"
Uninstall your app so the onCreate() is run again. See
When is SQLiteOpenHelper onCreate() / onUpgrade() run?
for more about that.
I have been working with a few different database examples.
Every example i am using to try to learn about SQLite databases i am
getting the exact same error. I have already tried to research this and cannot
find my exact error anywhere.
Thanks for any help below is the code and the error i am getting
DatabaseHandler db = new DatabaseHandler(this);
I am getting unreachable code.
in my Database Handler.java file i do have the public class Database Handler (one word).
Thanks again.
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact("Ravi", "9100000000"));
db.addContact(new Contact("Srinivas", "9199999999"));
db.addContact(new Contact("Tommy", "9522222222"));
db.addContact(new Contact("Karthik", "9533333333"));
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
}
}
this is my Database Handler
package com.example.databasetutorial;
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.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Thanks for your help
Unreachable code error tells you that that particular line can never be executed because there exists no control flow path to the code from the rest of the program. So the error is that the location where you are writing this statement is never reachable and that piece code would never be executed. This can be because of logical problems such as if you have statements written after the return statement inside a function, then none of those would be executed because the function would always return the value before those statements gets executed.
Hope this makes you understand the reason of the error.
Show more code if you want to more help.
Update
As I said in your MainActivity inside onCreateOptionsMenu function, put the return true; statement at the end of just before closing the parenthesis after Lod.d.. line. You are returning from the function before hand.
I'm implementing SQLite db in my android application i want retrieve data from JSON and store in into SQLite db .I saw one of the example of using SQLite but I'm using different column name wchi is store into SQLite db .
But when i run the app I'm getting Error like =
((1) table contacts has no column named cost ,
Error inserting phone_number=9533333333 cost=46456 name=Karthik ,
android.database.sqlite.SQLiteException: table contacts has no column named cost (code 1): , while compiling: INSERT INTO contacts(phone_number,cost,name) VALUES (?,?,?))
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_COST = "cost";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_COST + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact._name); // Contact Name
values.put(KEY_COST, contact._cost); // Contact Phone
values.put(KEY_PH_NO, contact._mobile); //Contact phone no
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_COST, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),cursor.getString(3));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.set_id(Integer.parseInt(cursor.getString(0)));
contact.set_name(cursor.getString(1));
contact.set_cost(cursor.getString(2));
contact.set_mobile(cursor.getString(3));
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.get_name());
values.put(KEY_COST, contact.get_cost());
values.put(KEY_PH_NO, contact.get_mobile());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.get_id()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.get_id()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Change this line
private static final int DATABASE_VERSION = 1;
to this
private static final int DATABASE_VERSION = 2;
And check your work again.
Try clear your app data then rerun the app, you may have had a different column before and run the app once (meaning the create table would not be called again).