java.lang.IllegalArgumentException: column 'foo' does not exist android - java

Numerous StackOverflow problems are similar, but it is not an issue of incorrect spacing in the query string. I have two tables, one for peers and one for messages, which has foreign keys associated with ids in the peer table.
Here are my creation strings:
private static final String DATABASE_CREATE = "CREATE TABLE " + PEER_TABLE + " ("
+ PeerContract._ID + " INTEGER PRIMARY KEY, "
+ PeerContract.NAME + " TEXT NOT NULL, "
+ PeerContract.ADDRESS + " TEXT NOT NULL, "
+ PeerContract.PORT + " TEXT NOT NULL);";
private static final String MESSAGE_TABLE_CREATE = "CREATE TABLE " + MESSAGE_TABLE + " ("
+ MessageContract._ID + " INTEGER PRIMARY KEY, "
+ MessageContract.MESSAGE_TEXT + " TEXT NOT NULL, "
+ MessageContract.SENDER + " TEXT NOT NULL, "
+ MessageContract.PEER_FOREIGN_KEY + " INTEGER NOT NULL, "
+ "FOREIGN KEY ("+ MessageContract.PEER_FOREIGN_KEY+") " +
"REFERENCES "+PEER_TABLE+"("+PeerContract._ID+") ON DELETE CASCADE);";
private static final String CREATE_INDEX = "CREATE INDEX " + INDEX + " ON " +
MESSAGE_TABLE + "(" + MessageContract.PEER_FOREIGN_KEY + ");";
I want to query a list of all received messages so I did this:
public Cursor fetchAllMessages(){
String query = "SELECT " + MESSAGE_TABLE + "." + MessageContract._ID + ", "
+ MessageContract.MESSAGE_TEXT + ", "
+ MessageContract.SENDER
+ " FROM " + MESSAGE_TABLE + " JOIN " + PEER_TABLE + " ON "
+ MESSAGE_TABLE + "." + MessageContract.PEER_FOREIGN_KEY
+ "=" + PEER_TABLE + "." + PeerContract._ID;
return db.rawQuery(query, null);
}
Which makes sense to me. And the spacing so far is alright there is no errors.
In my main activity I have a SimpleCursorAdapter:
listView = (ListView) findViewById(R.id.msgList);
dbAdapter = new ServerDbAdapter(this);
dbAdapter.open();
String[] from = new String[] {PeerContract.NAME, MessageContract.MESSAGE_TEXT};
int[] to = new int[] {android.R.id.text1, android.R.id.text2};
cursorAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, from, to);
listView.setAdapter(cursorAdapter);
cursor = dbAdapter.fetchAllMessages();
cursorAdapter.swapCursor(cursor);
I get "column 'name' does not exist" and it is driving me crazy!
I properly defined it in DATABASE_CREATE as PeerContract.NAME. I'm guessing its happening because of fetchAllMessages but I am not sure how to fix it.

You are not selecting the PeerContract.NAME, MessageContract.MESSAGE_TEXT in your fetchAllMessages() method. Change it to this:
public Cursor fetchAllMessages(){
String query = "SELECT " + MESSAGE_TABLE + "." + MessageContract._ID + ", "
+ MessageContract.MESSAGE_TEXT + ", "
+ PeerContract.NAME + ", "
+ PeerContract.MESSAGE_TEXT + ", "
+ MessageContract.SENDER
+ " FROM " + MESSAGE_TABLE + " JOIN " + PEER_TABLE + " ON "
+ MESSAGE_TABLE + "." + MessageContract.PEER_FOREIGN_KEY
+ "=" + PEER_TABLE + "." + PeerContract._ID;
return db.rawQuery(query, null);
}

Related

income_amount (code 1): , while compiling: SELECT SUM(income_amount) FROM INCOME WHERE month = '24'

This is my first app and I'm having lots of problems I'm trying to use this code total all the income transactions for a month by comparing month field to month now but I get the above error code. No idea what to do. Code below.
//Create Table Income
private static final String CREATE_TABLE_INCOME = "CREATE TABLE " + TABLE_INCOME
+ "(" + COL_ID + "INTEGER PRIMARY KEY," + COL_INCOME_SOURCE + "TEXT,"
+ COL_INCOME_AMOUNT + "NUMERIC," + COL_ACCOUNT_TYPE + "TEXT," + COL_DATE + "DATE," +
COL_DESCRIPTION + "TEXT," + COL_MONTH + "NUMERIC)";
Method
public double income_month(double month_income) {
Calendar cal = Calendar.getInstance();
int month_now = cal.get(Calendar.MONTH + 1);
SQLiteDatabase mDatabaseManager = this.getReadableDatabase();
Cursor c = mDatabaseManager.rawQuery("SELECT SUM(income_amount) FROM " +
TABLE_INCOME + " WHERE " + COL_MONTH + " = '" + month_now+ "'", null);
if (c!=null)
c.moveToFirst();
do {
assert c != null;
month_income = c.getDouble(0);
}
while (c.moveToNext());
c.close();
return month_income;
}
And the call in main activity
double month_income = 0;
mDatabase = new DatabaseManager(this.getApplicationContext());
month_income = mDatabase.income_month(month_income);
final TextView incomeview = findViewById(R.id.income);
incomeview.setText("" + month_income);
The CREATE statement is wrong because there are no spaces between the column names and their data types.
Change to this:
private static final String CREATE_TABLE_INCOME = "CREATE TABLE " + TABLE_INCOME
+ "(" + COL_ID + " INTEGER PRIMARY KEY," + COL_INCOME_SOURCE + " TEXT,"
+ COL_INCOME_AMOUNT + " NUMERIC," + COL_ACCOUNT_TYPE + " TEXT," + COL_DATE + " DATE," + COL_DESCRIPTION + " TEXT," + COL_MONTH + " NUMERIC)";
You will have to uninstall the app from the device so the database is deleted and rerun to recreate the table with the correct column names and data types.
Also use the constants for column names everywhere in the code to avoid mistakes, so instead of income_amount use COL_INCOME_AMOUNT and use ? placeholders to pass parameters in rawQuery() instead of concatenating single quotes:
Cursor c = mDatabaseManager.rawQuery("SELECT SUM(" + COL_INCOME_AMOUNT + ") FROM " + TABLE_INCOME + " WHERE " + COL_MONTH + " = ?", new String[] {month_now});

Syntax to create unique composite column - Android SQLiteOpenHelper

I have this onCreate method in my SQLiteOpenHelper
class, and I would like to add a unique constraint on these two columns (composite unique columns):
SongContract.SongEntry.COLUMN_TITLE
SongContract.SongEntry.COLUMN_RELEASEDATE
But I am getting an error:
Cannot resolve method UNIQUE
Here is my code:
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_SONG_TABLE = "CREATE TABLE " + SongContract.SongEntry.TABLE_SONG + " (" +
SongContract.SongEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
SongContract.SongEntry.COLUMN_TITLE + " TEXT NOT NULL, " +
SongContract.SongEntry.COLUMN_RELEASEDATE + " INTEGER, " +
UNIQUE(SongContract.SongEntry.COLUMN_TITLE, SongContract.SongEntry.COLUMN_RELEASEDATE) +
SongContract.SongEntry.COLUMN_RATING + " TEXT);";
db.execSQL(SQL_CREATE_SONG_TABLE);
}
What is the correct syntax to achieve my goal?
I found the corrrect syntax after playing around sqllite:
final String SQL_CREATE_SONG_TABLE = "CREATE TABLE " + SongContract.SongEntry.TABLE_SONG + " (" +
SongContract.SongEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
SongContract.SongEntry.COLUMN_TITLE + " TEXT NOT NULL, " +
SongContract.SongEntry.COLUMN_RELEASEDATE + " INTEGER NOT NULL, " +
SongContract.SongEntry.COLUMN_RATING + " TEXT, " + "UNIQUE" + "(" +
SongContract.SongEntry.COLUMN_TITLE + "," + SongContract.SongEntry.COLUMN_RELEASEDATE + ") " + ");";

Android: SQLite says a column doesn't exist

I am trying to get all the values in a table that have column _parentbook set to a certain value. When I try to retrieve the entries I get the error shown below.
E/SQLiteLog: (1) table recipes has no column named _parentbook
E/SQLiteDatabase: Error inserting _parentbook=Test _recipemethod=Stir in pot for 20 mins _recipeingredients=No bugs, freedom _recipedescription=Test recipe _recipename=Recipe 1 in Test _recipenotes=Do on Android Studio
The error refers to the method below that I use to add a recipe to the database
public void addRecipe(Recipe recipe) {
ContentValues values = new ContentValues();
values.put(COLUMN_RECIPE_NAME, recipe.getRecipeTitle());
values.put(COLUMN_RECIPE_DESCRIPTION, recipe.getRecipeDescription());
values.put(COLUMN_RECIPE_INGREDIENTS, recipe.getIngredients());
values.put(COLUMN_RECIPE_METHOD, recipe.getMethod());
values.put(COLUMN_RECIPE_NOTES, recipe.getNotes());
//values.put(COLUMN_IMAGE_ID, recipe.getImageId());
values.put(COLUMN_PARENT_BOOK, recipe.getParentBook());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_RECIPES, null, values);
db.close();
}
Code used to initialise TABLE_RECIPES:
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER " +
COLUMN_PARENT_BOOK + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
Log.e(TAG, "OnCreate() called");
db.execSQL(CREATE_TABLE_RECIPES);
}
Method for getting the recipes from the table:
List<Recipe> recipes;
public List<Recipe> getRecipes(String bookName) {
recipes = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
//String query = "SELECT "+ COLUMN_PARENT_BOOK +" FROM " + TABLE_RECIPES + " WHERE " + COLUMN_PARENT_BOOK + "=" + bookName;
String query = "SELECT * FROM " + TABLE_RECIPES;// + " WHERE 1";
// Cursor going to point to a location in the results
Cursor c = db.rawQuery(query, null);
// Move it to the first row of your results
c.moveToFirst();
if (c.moveToFirst()) {
do {
if (c.getString(c.getColumnIndex(COLUMN_RECIPE_NAME)) != null) {
recipes.add(new Recipe(
c.getString(c.getColumnIndex(COLUMN_RECIPE_NAME)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_DESCRIPTION)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_INGREDIENTS)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_METHOD)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_NOTES)),
// Add image here if required
c.getString(c.getColumnIndex(COLUMN_PARENT_BOOK))
));
}
} while (c.moveToNext());
}
db.close();
//c.close();
return recipes;
}
I have tried upgrading the database version and looking at other similar questions on StackOverflow, neither helped.
Thanks.
You forgot to put comma(,) in create table statement.
Instead of
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER " +
COLUMN_PARENT_BOOK + " TEXT" +
");";
It should be
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER, " + // Here you forgot to put comma(,) in this line
COLUMN_PARENT_BOOK + " TEXT" +
");";

"No such column" when running update on SQLite

I'm trying to update a row in my database. Here is the code I am trying to use to update:
public void addFBComments(int id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS+"="+"HELLO" + " WHERE " + COL_FB_ID+"="+id;
db.execSQL(query);
}
When I run the command, it throws this error:
08-18 15:42:10.145: E/AndroidRuntime(10493): FATAL EXCEPTION: Thread-922
08-18 15:42:10.145: E/AndroidRuntime(10493): android.database.sqlite.SQLiteException: no such column: HELLO (code 1): , while compiling: UPDATE fb_feed SET fb_comments= HELLO WHERE _id=3
Here is the TABLE_FB_FEED:
private static final String TABLE_FB_FEED_CREATE = "create table " + TABLE_FB_FEED +
" ("
+ COL_FB_ID + " integer primary key autoincrement not null,"
+ COL_FB_MESSAGE + " text,"
+ COL_FB_CAPTION + " text,"
+ COL_FB_POSTER_ID + " text,"
+ COL_FB_POST_ID + " text,"
+ COL_FB_LIKES + " text,"
+ COL_FB_POSTER_NAME + " text,"
+ COL_FB_COMMENTS + " text," // this is the column i want to update
+ COL_FB_LIKES_NUM + " text,"
+ COL_FB_TIMESTAMP + " text,"
+ COL_FB_PROFILE_PICTURE_URI + " text,"
+ COL_FB_PICTURE_URI + " text,"
+ COL_FB_NAME + " text,"
+ COL_FB_PREVIOUS_PAGE_URI + " text,"
+ COL_FB_NEXT_PAGE_URI + " text,"
+ COL_FB_POST_TYPE + " text,"
+ COL_FB_LINK_NAME + " text,"
+ COL_FB_COMMENTS_NUM + " text,"
+ COL_FB_STORY + " text,"
+ COL_FB_DESCRIPTION + " text,"
+ COL_FB_COMMENTS_BEFORE + " text,"
+ COL_FB_COMMENTS_AFTER + " text,"
+ COL_FB_LIKES_PROFILE_PIC + " text,"
+ COL_FB_COMMENTS_PROFILE_PIC + " text);";
Why is it throwing the query? I thought I was doing everything correctly.
in your code you need to add single quotes:
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS
+"="+"'HELLO'" + " WHERE " + COL_FB_ID+"="+id
or
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS
+"='HELLO' WHERE " + COL_FB_ID+"="+id
this is another example
"UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=myidValue");
In SQL, string values must be quoted:
String query = "..." + COL_FB_COMMENTS+"= 'HELLO' WHERE ...";
Anyway, formatting problems such as this (which get worse when the string itself contains quotes) can be avoided by using parameters:
String query = "... SET " + COL_FB_COMMENTS+"= ? WHERE " + COL_FB_ID+"="+id;
db.execSQL(query, new Object[] { "HELLO" });
You need to escape your String literal,
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS
+"="+"HELLO" + " WHERE " + COL_FB_ID+"="+id
Could be
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS
+"="+"'HELLO'" + " WHERE " + COL_FB_ID+"="+id
Or, you could use a bind parameter.
something like
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS+"="+"'HELLO'" + " WHERE " + COL_FB_ID+"="+id;
would work

Sql lite max dont find column name

Using:
SQLiteDatabase db = this.getWritableDatabase();
int max_request_code = 0;
final String MY_QUERY = "SELECT MAX(" + REQUEST_CODE + ") FROM " + TABLE_TASKS;
Cursor mCursor = db.rawQuery(MY_QUERY, null);
if (mCursor.getCount() > 0)
{
mCursor.moveToFirst();
max_request_code = mCursor.getInt(mCursor.getColumnIndex(REQUEST_CODE));
}
else
return 0;
return max_request_code;
gives me an exception:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.
on the line containing mCursor.getInt.
This is how i create the table:
String CREATE_TASKS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + "("
+UUID + " TEXT,"+ REQUEST_CODE + " INT,"+ ACTION + " TEXT,"
+ TIME + " TEXT," + DAY + " TEXT," + RECEPIENTS+ " TEXT," +BODY + " TEXT," +SUBJECT +
" TEXT," +STATUS + " TEXT," +REPEAT + " TEXT," +TASK_NAME + " TEXT" +")";
db.execSQL(CREATE_TASKS_TABLE);
Use the word AS to assign a column name to the returned MAX value:
final String MY_QUERY = "SELECT MAX(" + REQUEST_CODE + ") AS maxRequest_Code FROM " + TABLE_TASKS;
Then get value from cursor:
max_request_code = mCursor.getInt(mCursor.getColumnIndex("maxRequest_Code"));
or use:
max_request_code = mCursor.getInt(0);

Categories

Resources