Attempting to use insert_last_rowid() - java

I am attempting to assign the plan_recipe variable in the createPlan method with teh autoincremented id of the createPlanRecipe method. I've attempted to use the insert_last_rowid() method but am getting the error of Couldn't read row 0, col -1 from CursorWindow. Have I not done this correctly or is there another method I could use to do this?
Essentially how do I insert the id created from createPlanRecipe into variable plRecipe in createPlan()?
Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
RecipeListAdapter.OnRecipeClickListener listener = new RecipeListAdapter.OnRecipeClickListener() {
public void onRecipeClicked(int position, String recName) {
Log.d("Recipe selected", recName);
recipe_name = recName;
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreatePlan();
}
});
}
public void ListRecipes() {
listRecipe.clear();
SQLiteDatabase db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
public void CreatePlan(){
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
Log.d("Recipe name", recipe_name);
db.createPlanRecipe(d_name, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, plan_recipe);
}
}
Database snippet
public void createPlanRecipe(Integer date, String dayOfWeek, String recipe_name) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(getINSERT_PLAN_RECIPE(date, dayOfWeek, recipe_name));
}
public void createPlan(String plan_name, Integer plRecipe) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("select last_insert_rowid()",null);
c.moveToFirst();
if (c != null && (c.getCount() > 0)) {plRecipe = c.getInt(c.getColumnIndex("id"));}
db.execSQL(getInsertPlan(plan_name, plRecipe));
}
Database
public static final String TABLE_CATEGORY = "CATEGORY";
public static final String TABLE_RECIPE = "RECIPE";
public static final String TABLE_MEAL_PLAN = "MEAL_PLAN";
public static final String TABLE_QUANTITY = "QUANTITY";
public static final String TABLE_SHOPPING_LIST = "SHOPPING_LIST";
public static final String TABLE_PLAN_RECIPES = "PLAN_RECIPES";
public static final String TABLE_COURSE = "COURSE";
public static final String TABLE_INGREDIENTS = "INGREDIENTS";
public static final String TABLE_MEASUREMENT = "MEASUREMENT";
public static final String TABLE_INGREDIENT_TYPE = "INGREDIENT_TYPE";
public static final String TABLE_ALLERGENS = "ALLERGENS";
public static final String TABLE_RECIPES_ALLERGENS = "RECIPES_ALLERGENS";
public static final String TABLE_FAVOURITES = "FAVOURITES";
// Common column names
private static final String COL_ID = "id";
private static final String COL_MEASUREMENT = "measurement";
private static final String COL_INGREDIENT_TYPE = "ingredient_type";
private static final String COL_DESCRIPTION = "description";
private static final String COL_IMAGE = "image";
// Category column names
private static final String COL_CATEGORY_NAME = "category_name";
// Recipe column names
private static final String COL_RECIPE_NAME = "recipe_name";
private static final String COL_SERVINGS = "servings";
private static final String COL_CALORIES = "calories";
private static final String COL_PREPARATION_TIME = "preparation_time";
private static final String COL_METHOD = "method";
private static final String COL_COURSE = "course";
private static final String COL_CATEGORY = "category";
private static final String COL_COST = "cost";
private static final String COL_IMAGE2 = "image2";
//Quantity column names
private static final String COL_INGREDIENT_QUANTITY = "ingredient_quantity";
private static final String COL_RECIPE = "recipe";
private static final String COL_INGREDIENT = "ingredient";
//Meal Plan column names
private static final String COL_PLAN_NAME = "plan_name";
private static final String COL_PLAN_RECIPE = "plan_recipe";
//Shopping List column names
private static final String COL_QUANTITY = "quantity";
private static final String COL_PLANID = "planID";
//Plan Recipes column names
private static final String COL_DATE = "date";
private static final String COL_DAY_OF_WEEK = "dayOfWeek";
//Course column names
private static final String COL_COURSE_NAME = "course_name";
//Ingredients column names
private static final String COL_INGREDIENT_NAME = "ingredient_name";
//Measurement column names
private static final String COL_MEASUREMENT_NAME = "measurement_name";
//Ingredient Type column names
private static final String COL_TYPE_NAME = "type_name";
//Allergens column names
private static final String COL_ALLERGEN_NAME = "allergen_name";
/* *************************************************************************************
************************* CREATE TABLE STATEMENTS **************************************
****************************************************************************************
*/
// Create Table Category
private static final String CREATE_TABLE_CATEGORY = "CREATE TABLE "
+ TABLE_CATEGORY + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_CATEGORY_NAME
+ " TEXT," + COL_IMAGE + " INTEGER)";
// Create Table Meal Plan
private static final String CREATE_TABLE_MEAL_PLAN = "CREATE TABLE "
+ TABLE_MEAL_PLAN + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_PLAN_NAME
+ " TEXT," + COL_PLAN_RECIPE + " NUMERIC," + " FOREIGN KEY (" + COL_PLAN_RECIPE + ") REFERENCES " + TABLE_PLAN_RECIPES + "(" + COL_ID + "))";
// Create Table Recipe
private static final String CREATE_TABLE_RECIPE = "CREATE TABLE " + TABLE_RECIPE + "(" + COL_ID +
" INTEGER PRIMARY KEY AUTOINCREMENT," + COL_RECIPE_NAME + " TEXT," + COL_DESCRIPTION
+ " TEXT," + COL_COURSE + " TEXT," + COL_SERVINGS + " INTEGER," + COL_CALORIES + " NUMERIC,"
+ COL_PREPARATION_TIME + " NUMERIC," + COL_METHOD + " TEXT," + COL_CATEGORY + " TEXT,"
+ COL_IMAGE + " INTEGER," + COL_IMAGE2 + " TEXT," + COL_COST + " NUMERIC," + " FOREIGN KEY (" + COL_CATEGORY + ") REFERENCES " +
TABLE_CATEGORY + "(" + COL_CATEGORY_NAME + "), FOREIGN KEY (" + COL_COURSE + ") REFERENCES " +
TABLE_COURSE + "(" + COL_COURSE_NAME + "))";
// Create Table Quantity
public static final String CREATE_TABLE_QUANTITY = "CREATE TABLE " + TABLE_QUANTITY + "(" + COL_ID +
" INTEGER PRIMARY KEY AUTOINCREMENT," + COL_INGREDIENT_QUANTITY + " NUMERIC, " +
COL_RECIPE + " TEXT," + COL_INGREDIENT + " TEXT, FOREIGN KEY (" + COL_RECIPE + ") " +
"REFERENCES " + TABLE_RECIPE + "(" + COL_RECIPE_NAME + "), FOREIGN KEY (" + COL_INGREDIENT + ") " +
"REFERENCES " + TABLE_INGREDIENTS + "(" + COL_INGREDIENT_NAME + "))";
// Create Table Shopping List
private static final String CREATE_TABLE_SHOPPING_LIST = "CREATE TABLE " + TABLE_SHOPPING_LIST +
"(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_INGREDIENT_TYPE + " INTEGER,"
+ COL_QUANTITY + " INTEGER," + COL_MEASUREMENT + " INTEGER," + COL_PLANID + " INTEGER," +
" FOREIGN KEY (" + COL_INGREDIENT_TYPE + ") REFERENCES " + TABLE_INGREDIENT_TYPE + "(" + COL_ID + "), " +
"FOREIGN KEY (" + COL_QUANTITY + ") REFERENCES " + TABLE_QUANTITY + "(" + COL_ID + "), " +
"FOREIGN KEY (" + COL_MEASUREMENT + ") REFERENCES " + TABLE_MEASUREMENT + "(" + COL_ID + "), " +
"FOREIGN KEY (" + COL_PLANID + ") REFERENCES " + TABLE_MEAL_PLAN + "(" + COL_ID + "))";
// Create Table Course
private static final String CREATE_TABLE_COURSE = "CREATE TABLE " + TABLE_COURSE + "(" + COL_ID +
" INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_COURSE_NAME + " TEXT," + COL_IMAGE + " INTEGER)";
// Create Table Ingredients
public static final String CREATE_TABLE_INGREDIENTS = "CREATE TABLE " + TABLE_INGREDIENTS + "("
+ COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_INGREDIENT_NAME + " TEXT,"
+ COL_DESCRIPTION + " TEXT," + COL_MEASUREMENT_NAME + " TEXT," + COL_INGREDIENT_TYPE + " TEXT, " +
"FOREIGN KEY (" + COL_MEASUREMENT_NAME + ") REFERENCES " + TABLE_MEASUREMENT + "(" + COL_MEASUREMENT_NAME + "), " +
"FOREIGN KEY (" + COL_INGREDIENT_TYPE + ") REFERENCES " + TABLE_INGREDIENT_TYPE + "(" + COL_TYPE_NAME + "))";
// Create Table Measurement
private static final String CREATE_TABLE_MEASUREMENT = "CREATE TABLE " + TABLE_MEASUREMENT + "(" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_MEASUREMENT_NAME + " TEXT)";
// Create Table Ingredient Type
private static final String CREATE_TABLE_INGREDIENT_TYPE = "CREATE TABLE " + TABLE_INGREDIENT_TYPE +
"(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_TYPE_NAME + " TEXT)";
// Create Table Plan Recipes
private static final String CREATE_TABLE_PLAN_RECIPES = "CREATE TABLE " + TABLE_PLAN_RECIPES + "(" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_DATE + " DATE," +
COL_DAY_OF_WEEK + " TEXT," + COL_RECIPE_NAME + " TEXT, FOREIGN KEY (" + COL_RECIPE_NAME + ") " +
"REFERENCES " + TABLE_RECIPE + "(" + COL_RECIPE_NAME + "))";
// Create Table Allergens
private static final String CREATE_TABLE_ALLERGENS = "CREATE TABLE " + TABLE_ALLERGENS +
"(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_ALLERGEN_NAME + " TEXT)";
// Create Table Recipes_Allergens
private static final String CREATE_TABLES_RECIPES_ALLERGENS = "CREATE TABLE " + TABLE_RECIPES_ALLERGENS +
"(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_ALLERGEN_NAME + " TEXT," +
COL_RECIPE + " TEXT," + "FOREIGN KEY (" + COL_ALLERGEN_NAME + ") REFERENCES " + TABLE_ALLERGENS +
"(" + COL_ALLERGEN_NAME +"), " + "FOREIGN KEY (" + COL_RECIPE + ") REFERENCES " + TABLE_RECIPE +
"(" + COL_RECIPE_NAME + "))";
// Create Table Favourites
private static final String CREATE_TABLE_FAVOURITES = "CREATE TABLE " + TABLE_FAVOURITES + "(" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_RECIPE_NAME + " TEXT," +
"FOREIGN KEY (" + COL_RECIPE_NAME + ") REFERENCES " + TABLE_RECIPE + "(" + COL_RECIPE_NAME + "))";
public final String INSERT_MEASUREMENT =
"INSERT INTO " + TABLE_MEASUREMENT + "("
+ COL_MEASUREMENT_NAME + ") values ";
public final String INSERT_INGREDIENT_TYPE =
" INSERT INTO " + TABLE_INGREDIENT_TYPE + "("
+ COL_TYPE_NAME + ") values ";
public final String INSERT_INGREDIENT =
" INSERT INTO " + TABLE_INGREDIENTS + "("
+ COL_INGREDIENT_NAME + "," + COL_DESCRIPTION + ","
+ COL_MEASUREMENT_NAME + "," + COL_INGREDIENT_TYPE + ") values ";
public final String INSERT_CATEGORY =
" INSERT INTO " + TABLE_CATEGORY + "("
+ COL_CATEGORY_NAME + "," + COL_IMAGE + ") values ";
public final String INSERT_COURSE =
" INSERT INTO " + TABLE_COURSE + "("
+ COL_COURSE_NAME + "," + COL_IMAGE + ") values ";
public final String INSERT_RECIPE =
" INSERT INTO " + TABLE_RECIPE + "("
+ COL_RECIPE_NAME + "," + COL_DESCRIPTION + ","
+ COL_COURSE + "," + COL_SERVINGS + ","
+ COL_CALORIES + "," + COL_PREPARATION_TIME + ","
+ COL_METHOD + "," + COL_CATEGORY + ","
+ COL_IMAGE + ","
+ COL_IMAGE2 + ","
+ COL_COST + ") values";
public final String INSERT_QUANTITY =
" INSERT INTO " + TABLE_QUANTITY + "("
+ COL_INGREDIENT_QUANTITY + ","
+ COL_RECIPE + ","
+ COL_INGREDIENT + ") values";
public final String INSERT_ALLERGEN =
" INSERT INTO " + TABLE_ALLERGENS + "("
+ COL_ALLERGEN_NAME + ") values";
public final String INSERT_RECIPES_ALLERGENS =
" INSERT INTO " + TABLE_RECIPES_ALLERGENS + "("
+ COL_ALLERGEN_NAME + ","
+ COL_RECIPE + ") values";
public final String INSERT_FAVOURITE =
" INSERT INTO " + TABLE_FAVOURITES + "("
+ COL_RECIPE_NAME + ") values";
public final String INSERT_PLAN_RECIPE =
" INSERT INTO " + TABLE_PLAN_RECIPES + "("
+ COL_DATE + ","
+ COL_DAY_OF_WEEK + ","
+ COL_RECIPE_NAME + ") values";
public final String INSERT_PLAN =
" INSERT INTO " + TABLE_MEAL_PLAN + "("
+ COL_PLAN_NAME + ","
+ COL_PLAN_RECIPE + ") values";

You must use an alias like id for the column that is returned by last_insert_rowid():
Cursor c = db.rawQuery("select last_insert_rowid() as id", null);
Then instead of:
if (c != null && (c.getCount() > 0)) {plRecipe = c.getInt(c.getColumnIndex("id"));}
do this:
if (c.moveToFirst()) {plRecipe = c.getInt(c.getColumnIndex("id"));}
Without the alias of the column, you should directly use 0 inside c.getInt():
if (c.moveToFirst()) {plRecipe = c.getInt(0);}

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});

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

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);
}

App crashes when I try to get the _id in my SQLite Table?

Hi guys so here is my problem, I need to be able to access the unique ID of a row that is created because I created a second table that will "Connected" through the IDs. However here is my issue, whenever I try calling this method, my app crashes.. I was hoping the community could help me out here. Many Thanks.
public void addExerciseToDatabase(Exercises exercises){
SQLiteDatabase db = myDBHelper.getWritableDatabase();
ContentValues values = new ContentValues();
ContentValues nuValues = new ContentValues();
values.put(myDBHelper.COLUMN_BODYPARTNAME, exercises.get_bodyPart());
values.put(myDBHelper.COLUMN_EXERCISENAME, exercises.get_exerciseName());
long ID = db.insert(myDBHelper.TABLE_EXERCISES, null, values);
//FOR THE NEW TABLE VALUES
nuValues.put(myDBHelper.COLUMN_EXERCISENAME_ID, ID);
nuValues.put(myDBHelper.COLUMN_NUMSETS, exercises.get_numSets());
nuValues.put(myDBHelper.COLUMN_NUMWEIGHT, exercises.get_numWeight());
nuValues.put(myDBHelper.COLUMN_NUMREPS, exercises.get_numReps());
db.insert(myDBHelper.TABLE_EXERCISES_VALUE, null, nuValues);
db.close();
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
THIS method returns the EXERCISE ID, that corresponds to the exercise
passed and Bodypart passed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
public int getExerciseID(String exercise, String bodyPart) {
SQLiteDatabase db = myDBHelper.getWritableDatabase();
String query = "SELECT " + myDBHelper.COLUMN_ID + " FROM " + myDBHelper.TABLE_EXERCISES + " WHERE " +
myDBHelper.COLUMN_BODYPARTNAME + " = " + bodyPart + " AND " +
myDBHelper.COLUMN_EXERCISENAME + " = " + exercise ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
int exerciseID = Integer.parseInt(c.getString(0));
/*int exerciseID = c.getInt(c.getColumnIndex(myDBHelper.COLUMN_ID));*/
c.close();
db.close();
return exerciseID;
}
HERES MY TABLE:
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "exercises.db";
public static final String TABLE_EXERCISES = "exercises";
public static final String TABLE_EXERCISES_VALUE = "exercises_value";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_BODYPARTNAME = "bodypartname";
public static final String COLUMN_EXERCISENAME = "exercisename";
public static final String COLUMN_EXERCISENAME_ID = "exerciseid";
public static final String COLUMN_NUMSETS = "numsets";
public static final String COLUMN_NUMWEIGHT = "numweight";
public static final String COLUMN_NUMREPS = "numreps";
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_EXERCISES + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_BODYPARTNAME + " TEXT NOT NULL," +
COLUMN_EXERCISENAME + " TEXT NOT NULL" +
");";
db.execSQL(query);
query = "CREATE TABLE " + TABLE_EXERCISES_VALUE + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_EXERCISENAME_ID + " INTEGER NOT NULL," +
COLUMN_NUMSETS + " INTEGER NOT NULL," +
COLUMN_NUMWEIGHT + " INTEGER NOT NULL," +
COLUMN_NUMREPS + " INTEGER NOT NULL" +
");";
db.execSQL(query);
}
Update your query as your query not contains spaces in SELECT and FROM
String query = "SELECT " + myDBHelper.COLUMN_ID + " FROM " + myDBHelper.TABLE_EXERCISES + " WHERE " +
myDBHelper.COLUMN_BODYPARTNAME + " = " + bodyPart + " AND " +
myDBHelper.COLUMN_EXERCISENAME + " = " + exercise ;
Also can you post your logcat error.
public int getExerciseID(String exercise, String bodyPart) {
int exerciseID = 0;
SQLiteDatabase db = myDBHelper.getWritableDatabase();
String query = "SELECT " + myDBHelper.COLUMN_ID + " FROM " + myDBHelper.TABLE_EXERCISES + " WHERE " +
myDBHelper.COLUMN_BODYPARTNAME + " = " + bodyPart + " AND " +
myDBHelper.COLUMN_EXERCISENAME + " = " + exercise ;
Cursor c = db.rawQuery(query, null);
if(c.getCount()>0){
c.moveToFirst();
exerciseID = Integer.parseInt(c.getString(0));
/*exerciseID = c.getInt(c.getColumnIndex(myDBHelper.COLUMN_ID));*/
}
c.close();
db.close();
return exerciseID;
}

What to do when cursor.movetofirst is false (SQLite)

I'm working on a project using SQLite.
I did create my db a while ago and so on but yesterday i uninstall my app from the phone and tryed to run it again via eclipse and it seems that since that moment, it doesn't work anymore.
first the code :
my SQLHelper :
public class SQLHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "listopresto";
public static final String TABLE_CATEGORIES = "categories";
public static final String CATEGORY_NAME = "name";
public static final String CATEGORY_ID = "id";
public static final String CATEGORY_ID_PARENT = "parent_id";
public static final String CATEGORY_URL_IMAGE = "image_url";
public static final String TABLE_SHOPPING_LIST = "shopping_list";
public static final String SHOPPING_LIST_ID = "shopping_list_id";
public static final String SHOPPING_LIST_NAME = "shopping_list_name";
public static final String SHOPPING_LIST_DATE_CREATION = "shopping_list_date_creation";
public static final String TABLE_SHOPPING_LIST_ITEMS = "shopping_list_items";
public static final String SHOPPING_LIST_ITEMS_LIST_ID = "shopping_list_items_list_id";
public static final String SHOPPING_LIST_ITEMS_ID = "shopping_list_items_id";
public static final String SHOPPING_LIST_ITEMS_NB_ITEMS = "shopping_list_items_nb_items";
public static final String SHOPPING_LIST_ITEMS_CHECKED = "shopping_list_items_checked";
public static final String TABLE_INFOS = "infos";
public static final String INFOS_AGE = "age";
public static final String INFOS_MAIL = "mail";
public static final String INFOS_DISPLAY_PRICE = "display_price";
public static final String INFOS_TOKEN = "token";
public static final String INFOS_REFRESH_TOKEN = "refresh_token";
public static final String INFOS_TOKEN_EXPIRATION = "token_expiration";
public static final String INFOS_REFRESH_TOKEN_EXPIRATION = "refresh_token_expiration";
public static final String INFOS_APP_VERSION = "app_version";
public static final String TABLE_ITEMS = "items";
public static final String ITEM_ID = "id";
public static final String ITEM_NAME = "name";
public static final String ITEM_CATEGORY_ID = "item_category_id";
public static final String ITEM_PRICE = "item_price";
public SQLHelper(Context context){
super(context, DATABASE_NAME, null, 25);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_CATEGORIES = "CREATE TABLE " + TABLE_CATEGORIES + "(" + CATEGORY_NAME + " TEXT," + CATEGORY_ID + " INTEGER, " + CATEGORY_ID_PARENT + " INTEGER," + CATEGORY_URL_IMAGE + " TEXT" + ")" ;
String CREATE_TABLE_INFOS = "CREATE TABLE " + TABLE_INFOS + "(" + INFOS_AGE + " INTEGER," + INFOS_MAIL + " TEXT," + INFOS_DISPLAY_PRICE + " TEXT," + INFOS_TOKEN + " TEXT," + INFOS_REFRESH_TOKEN + " TEXT," + INFOS_TOKEN_EXPIRATION + " TEXT, " + INFOS_REFRESH_TOKEN_EXPIRATION + " TEXT, " + INFOS_APP_VERSION + " TEXT" + ")";
String CREATE_TABLE_ITEMS = "CREATE TABLE " + TABLE_ITEMS + "(" + ITEM_ID + " INTEGER," + ITEM_NAME + " TEXT," + ITEM_CATEGORY_ID + " INTEGER," + ITEM_PRICE + " REAL" + ")";
String CREATE_TABLE_SHOPPING_LIST = "CREATE TABLE " + TABLE_SHOPPING_LIST + "(" + SHOPPING_LIST_ID + " INTEGER," + SHOPPING_LIST_NAME + " TEXT," + SHOPPING_LIST_DATE_CREATION + " TEXT" + ")";
String CREATE_TABLE_SHOPPING_LIST_ITEMS = "CREATE TABLE " + TABLE_SHOPPING_LIST_ITEMS + "(" + SHOPPING_LIST_ITEMS_LIST_ID + " INTEGER," + SHOPPING_LIST_ITEMS_ID + " INTEGER," + SHOPPING_LIST_ITEMS_NB_ITEMS + " INTEGER," + SHOPPING_LIST_ITEMS_CHECKED + " INTEGER" + ")";
db.execSQL(CREATE_TABLE_CATEGORIES);
db.execSQL(CREATE_TABLE_INFOS);
db.execSQL(CREATE_TABLE_ITEMS);
db.execSQL(CREATE_TABLE_SHOPPING_LIST);
db.execSQL(CREATE_TABLE_SHOPPING_LIST_ITEMS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORIES);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_INFOS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHOPPING_LIST);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SHOPPING_LIST_ITEMS);
onCreate(db);
}
/*
*
* METHODES TABLE INFOS
* z
*/
public void addInfos(InfosModel infos){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(INFOS_AGE, infos.getAge());
values.put(INFOS_MAIL, infos.getMail());
values.put(INFOS_DISPLAY_PRICE, infos.getDisplayPrice());
values.put(INFOS_TOKEN, infos.getToken());
values.put(INFOS_REFRESH_TOKEN, infos.getRefreshToken());
values.put(INFOS_TOKEN_EXPIRATION, infos.getTokenExpiration());
values.put(INFOS_REFRESH_TOKEN_EXPIRATION, infos.getRefreshTokenExpiration());
values.put(INFOS_APP_VERSION, infos.getAppVersion());
db.insert(TABLE_INFOS, null, values);
db.close();
}
public void updateInfos(InfosModel allInfos){
String Query = "UPDATE " + TABLE_INFOS +
" SET " + INFOS_AGE + "=" + allInfos.getAge() +
", " + INFOS_MAIL + "=\"" + allInfos.getMail() + "\""+
", " + INFOS_DISPLAY_PRICE + "=\"" + allInfos.getDisplayPrice() + "\"" +
", " + INFOS_TOKEN + "=\"" + allInfos.getToken() + "\"" +
", " + INFOS_REFRESH_TOKEN + "=\"" + allInfos.getRefreshToken() + "\"" +
", " + INFOS_TOKEN_EXPIRATION + "=\"" + allInfos.getTokenExpiration() + "\"" +
", " + INFOS_REFRESH_TOKEN_EXPIRATION + "=\"" + allInfos.getRefreshTokenExpiration() + "\"" +
", " + INFOS_APP_VERSION + "=\"" + allInfos.getAppVersion() + "\"";
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL(Query);
}
public InfosModel getInfos(){
String selectQuery = "SELECT * FROM " + TABLE_INFOS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null){
if (cursor.moveToFirst()){
InfosModel infos = new InfosModel();
infos.setMail(cursor.getString(cursor.getColumnIndex(INFOS_MAIL)));
infos.setAge(cursor.getInt(cursor.getColumnIndex(INFOS_AGE)));
infos.setDisplayPrice(cursor.getString(cursor.getColumnIndex(INFOS_DISPLAY_PRICE)));
infos.setToken(cursor.getString(cursor.getColumnIndex(INFOS_TOKEN)));
infos.setRefreshToken(cursor.getString(cursor.getColumnIndex(INFOS_REFRESH_TOKEN)));
infos.setTokenExpiration(cursor.getString(cursor.getColumnIndex(INFOS_TOKEN_EXPIRATION)));
infos.setRefreshTokenExpiration(cursor.getString(cursor.getColumnIndex(INFOS_REFRESH_TOKEN_EXPIRATION)));
infos.setAppVersion(cursor.getString(cursor.getColumnIndex(INFOS_APP_VERSION)));
cursor.close();
return (infos);
}
}
return (null);
}
public int getInfosCount() {
String countQuery = "SELECT * FROM " + TABLE_INFOS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
the java activity where i'm using the function getInfo:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
SQLHelper sqlHelper = new SQLHelper(this);
InfosModel infos = sqlHelper.getInfos();
Log.i("infos", infos.getMail());
}
The problem comes from the getInfos() function i believe.
My cursor isn't null but the function moveToFirst() fails but i don't know why and i don't know what to do to fix this since i've never had that problem before and my database was working well ..
thank you for the help :)
bottus.
edit : i tryed to see how many row i'm having in the infos table, there is zero row and that's why movetofirst() fail i believe but the behavior is exactly the same if i had a row in the table ..
Per the Android documents:
This method will return false if the cursor is empty.
So you must not have any data there, and you should manage appropriately. Check for typos, etc.

table "places" has no column named "smallDesc"

I don't see any mistakes with my code, I browsed questions with the same issue but I couldn't solve
it, I tried upgrading the sql version from 1 to 2, but still same error.
Is there anything wrong with my code?
public String place_ID = "id";
public String place_LAT = "LAT";
public String place_LNG = "LNG";
public String place_name = "name";
public String place_number = "number";
public String place_city = "city";
public String place_country = "country";
public String place_street = "street";
public String place_smallDesc = "smallDesc";
public String place_bigDesc = "bigDesc";
public String place_site = "site";
public String place_category = "category";
public String place_imageName ="image";
public String place_rank = "rank";
final static String PASS = "testPass";
final static String db_Name = "placesManager";
final static String DBTABLE_NAME_STRING = "places";
public DatabaseHelper(Context context) {
super(context, db_Name,null,2);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
String createDBQuery = "CREATE TABLE " + DBTABLE_NAME_STRING + "("
+ place_ID + " INTEGER PRIMARY KEY," + place_LAT + " REAL,"
+ place_name + " TEXT," + place_number + " TEXT,"
+ place_city + " TEXT," + place_country + " TEXT,"
+ place_street + " TEXT" + place_smallDesc + " TEXT,"
+ place_site + " TEXT" + place_category + " TEXT,"
+ place_imageName + " TEXT"+ place_rank + " INTEGER " + ")";
db.execSQL(createDBQuery);
}
public void AddPlaces(ArrayList<Place> placesList)
{
SQLiteDatabase db = this.getWritableDatabase(PASS);
ContentValues cValues = new ContentValues();
Log.d("MyTag","inserting");
for(int i = 0;i<placesList.size();i++)
{
cValues.put(place_ID, placesList.get(i).ID);
cValues.put(place_LAT, placesList.get(i).LAT);
cValues.put(place_LNG, placesList.get(i).LNG);
cValues.put(place_name, placesList.get(i).name);
cValues.put(place_number, placesList.get(i).number);
cValues.put(place_city, placesList.get(i).city);
cValues.put(place_ID, placesList.get(i).ID);
cValues.put(place_street, placesList.get(i).street);
cValues.put(place_smallDesc, placesList.get(i).smallDesc);
cValues.put(place_site, placesList.get(i).site);
cValues.put(place_category, placesList.get(i).category);
cValues.put(place_imageName, placesList.get(i).imageName);
cValues.put(place_rank, placesList.get(i).rating);
db.insert(DBTABLE_NAME_STRING, null, cValues);
}
Log.d("MyTag","done inserting");
db.close();
}
Inside onCreate you have:
+ place_street + " TEXT" + place_smallDesc + " TEXT,"
should be like below(missed colon), due to colon miss, both merged and table will have completely different column name than you are assuming.
+ place_street + " TEXT, " + place_smallDesc + " TEXT,"

Categories

Resources