I am building a workout logging app as a project. I am trying to insert the workout name into the database. Before prompting the user to then add in there exercise. Currently it it displyed the "Something went wrong error" and then app crashes.
Below is the error in the Logcat
android.database.sqlite.SQLiteException: near "Name": syntax error (code 1): , while compiling: INSERT INTO workout_table(Workout Name) 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.cormac.gymbud.DatabaseHelper.addWorkout(DatabaseHelper.java:112)
at com.example.cormac.gymbud.AddWorkout.AddData(AddWorkout.java:65)
at com.example.cormac.gymbud.AddWorkout.access$100(AddWorkout.java:15)
at com.example.cormac.gymbud.AddWorkout$1.onClick(AddWorkout.java:49)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21164)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
Below is my DatabaseHelper.class
public class DatabaseHelper extends SQLiteOpenHelper {
private static String TAG = "DatabaseHelper";
//workout table
public static final String TABLE_WORKOUT = "workout_table";
public static final String COL1 = "ID";
public static final String COL2 = "Workout Name";
//exercise table
public static final String TABLE_EXERCISE ="exercise_table";
public static final String COL3 = "ID";
public static final String COL4 = ("Exercise Name");
public static final String COL5 = ("Set");
public static final String COL6 = ("Weight");
public static final String COL7 = ("Reps");
private static final String DATABASE_NAME = "workouts.db";
private static final int DATABASE_VERSION = 1;
private static final String createWorkoutTable = "CREATE TABLE " + TABLE_WORKOUT + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT)";
private static final String createExerciseTable = "CREATE TABLE " + TABLE_EXERCISE + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL4 +" TEXT," + COL5 +" INTEGER,"+ COL6 + " INTEGER," + COL7 + "INTEGER)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("Create table user(email text primary key, password text)");
db.execSQL(createWorkoutTable);
db.execSQL(createExerciseTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
//db.execSQL("drop table if exists user");
//onCreate(db);
db.execSQL("DROP IF TABLE EXISTS " + TABLE_WORKOUT);
onCreate(db);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EXERCISE);
onCreate(db);
}
//inserting in database
// public boolean insert(String email, String password){
// SQLiteDatabase db = this.getWritableDatabase();
// ContentValues contentValues = new ContentValues();
//contentValues.put("email",email);
//contentValues.put("password",password);
//long ins = db.insert("user", null,contentValues);
//if (ins==1) return false;
//else return true;
//}
//checking if the email already exists
//public Boolean checkEmail(String email){
// SQLiteDatabase db = this.getReadableDatabase();
// Cursor cursor = db.rawQuery("Select * from user where email=?",new String[]{email});
//if (cursor.getCount()>0) return false;
//else return true;
//}
//checking the email and password
//public Boolean emailpassword(String email, String password){
// SQLiteDatabase db = this.getReadableDatabase();
// Cursor cursor = db.rawQuery("select * from user where email=? and password=?",new String[]{email,password});
// if (cursor.getCount()>0) return true;
//else return false;
//}
public boolean addWorkout(String workout){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2,workout);
Log.d(TAG, "addData: Adding " + workout + " to" + TABLE_WORKOUT);
long result = db.insert(TABLE_WORKOUT, null, contentValues);
if (result == -1){
return false;
}else{
return true;
}
}
public boolean addExercise(String item){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(item, COL4);
contentValues.put(item, COL5);
contentValues.put(item, COL6);
contentValues.put(item, COL7);
Log.d(TAG, "addData: Adding " + item + " to" + TABLE_EXERCISE);
long result = db.insert(TABLE_EXERCISE, null, contentValues);
if (result == -1){
return false;
}else{
return true;
}
}
//return data from the database
public Cursor getDataWorkout(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_WORKOUT;
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getDataExercise(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_EXERCISE;
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getItemIDWorkout(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + "FROM" + TABLE_WORKOUT +
" WHERE " + COL2 + " = " + name + " ";
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getItemIDExercise(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL3 + "FROM" + TABLE_EXERCISE +
" WHERE " + COL4 + " = " + name + " ";
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getExerciseSet(Integer set){
SQLiteDatabase db = this.getWritableDatabase();
Integer query = Integer.valueOf("SELECT " + COL3 + "FROM" + TABLE_EXERCISE +
" WHERE " + COL5 + " = " + set + " ");
Cursor data = db.rawQuery(String.valueOf(query), null);
return data;
}
public Cursor getExerciseWeight(Integer weight){
SQLiteDatabase db = this.getWritableDatabase();
Integer query = Integer.valueOf("SELECT " + COL3 + "FROM" + TABLE_EXERCISE +
" WHERE " + COL6 + " = " + weight + " ");
Cursor data = db.rawQuery(String.valueOf(query), null);
return data;
}
public Cursor getExerciseRep(Integer rep){
SQLiteDatabase db = this.getWritableDatabase();
Integer query = Integer.valueOf("SELECT " + COL3 + "FROM" + TABLE_EXERCISE +
" WHERE " + COL7 + " = " + rep + " ");
Cursor data = db.rawQuery(String.valueOf(query), null);
return data;
}
public void updateWorkoutName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_WORKOUT + " SET" + COL2 +
" = " + newName + "WHERE" + COL1 + " = " + id + " " +
" AND " + COL2 + " = " + oldName + " ";
Log.d(TAG, "updateName: query " + query);
Log.d(TAG, "updateName: Setting name to " + newName);
db.execSQL(query);
}
public void updateExerciseName(String newName, int id, String oldName){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE" + TABLE_EXERCISE + "SET" + COL4 +
" = " + newName + "WHERE" + COL3 + " = " + id + " " +
" AND " + COL4 + " = " + oldName + " ";
Log.d(TAG, "updateName: query " + query);
Log.d(TAG, "updateName: Setting name to" + newName);
db.execSQL(query);
}
public void updateExerciseSet(int newSet, int id, String oldSet){
SQLiteDatabase db = this.getWritableDatabase();
Integer query = Integer.valueOf("UPDATE" + TABLE_EXERCISE + "SET" + COL5 +
" = " + newSet + "WHERE" + COL3 + " = " + id + " " +
" AND " + COL5 + " = " + oldSet + " ");
Log.d(TAG, "updateSet: query " + query);
Log.d(TAG, "updateSet: Setting name to" + newSet);
db.execSQL(String.valueOf(query));
}
public void updateExerciseWeight(int newWeight, int id, String oldWeight){
SQLiteDatabase db = this.getWritableDatabase();
Integer query = Integer.valueOf("UPDATE" + TABLE_EXERCISE + "SET" + COL6 +
" = " + newWeight + "WHERE" + COL3 + " = " + id + " " +
" AND " + COL6 + " = " + oldWeight + " ");
Log.d(TAG, "updateWeight: query " + query);
Log.d(TAG, "updateWeight: Setting name to" + newWeight);
db.execSQL(String.valueOf(query));
}
public void updateExerciseRep(int newRep, int id, String oldRep){
SQLiteDatabase db = this.getWritableDatabase();
Integer query = Integer.valueOf("UPDATE" + TABLE_EXERCISE + "SET" + COL7 +
" = " + newRep + "WHERE" + COL3 + " = " + id + " " +
" AND " + COL7 + " = " + oldRep + " ");
Log.d(TAG, "updateRep: query " + query);
Log.d(TAG, "updateRep: Setting name to" + newRep);
db.execSQL(String.valueOf(query));
}
public void deleteWorkoutName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_WORKOUT + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
public void deleteExerciseName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_EXERCISE + " WHERE "
+ COL3 + " = '" + id + "'" +
" AND " + COL4 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
public void deleteExerciseSet(int id, int set){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_EXERCISE + " WHERE "
+ COL3 + " = '" + id + "'" +
" AND " + COL5 + " = '" + set + "'";
Log.d(TAG, "deleteSet: query: " + query);
Log.d(TAG, "deleteSet: Deleting " + set + " from database.");
db.execSQL(query);
}
public void deleteExerciseWeight(int id, int Weight){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_EXERCISE + " WHERE "
+ COL3 + " = '" + id + "'" +
" AND " + COL6 + " = '" + Weight + "'";
Log.d(TAG, "deleteWeight: query: " + query);
Log.d(TAG, "deleteWeight: Deleting " + Weight + " from database.");
db.execSQL(query);
}
public void deleteExerciseRep(int id, int rep){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_EXERCISE + " WHERE "
+ COL3 + " = '" + id + "'" +
" AND " + COL7 + " = '" + rep + "'";
Log.d(TAG, "deleteRep: query: " + query);
Log.d(TAG, "deleteRep: Deleting " + rep + " from database.");
db.execSQL(query);
}
}
Here is the AddWorout Activty
public class AddWorkout extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = "AddWorkout";
private EditText edtWorkout;
private Button btnAddW;
DatabaseHelper mDatabseHelper;
private WorkoutDAO mWorkoutDOA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_workout2);
initViews();
edtWorkout = (EditText) findViewById(R.id.edtWorkout);
btnAddW = (Button) findViewById(R.id.btnAddW);
mDatabseHelper = new DatabaseHelper(this);
btnAddW.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String workout = edtWorkout.getText().toString();
if (edtWorkout.length() != 0) {
AddData(workout);
edtWorkout.setText("");
Intent intent = new Intent(AddWorkout.this, AddExercise.class);
startActivity(intent);
} else {
toastMessage("You must put something in the text field!");
}
;
}
});
}
private void AddData(String workout) {
boolean insertData = mDatabseHelper.addWorkout(workout);
if (insertData){
toastMessage("Data Successfully Inserted");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String s) {
Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
}
private void initViews(){
this.edtWorkout = (EditText) findViewById(R.id.edtWorkout);
this.btnAddW = (Button) findViewById(R.id.btnAddW);
this.btnAddW.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAddW:
Editable WorkoutName = edtWorkout.getText();
if (!TextUtils.isEmpty(WorkoutName) ) {
// add the exercise to database
Workout createdWorkout = mWorkoutDOA.createWorkout(
WorkoutName.toString());
Log.d(TAG, "added workout : "+ createdWorkout.getName());
Intent intent = new Intent();
intent.putExtra(ListWorkoutActivity.EXTRA_ADDED_WORKOUT, (Parcelable) createdWorkout);
setResult(RESULT_OK, intent);
finish();
}
else {
Toast.makeText(this, R.string.empty_fields_message, Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mWorkoutDOA.close();
}
}
Your issue is that you've defined COL2 with public static final String COL2 = "Workout Name";
The space between Workout and Name will cause issues such as this but sometimes not cause issue such as when creating the table.
i.e the column will be Workout and the column type will be name TEXT which will have a type affinity of TEXT as it contains TEXT.
more about this at - Datatypes In SQLite Version 3
You can either change the column name to not have a space e.g.
public static final String COL2 = "Workout_Name"; //<<<< recommended way
or you could enclose it e.g. using ONE of the following:-
public static final String COL2 = "[Workout Name]";
public static final String COL2 = "`Workout Name`";
public static final String COL2 = "'Workout Name'";
public static final String COL2 = "\"Workout Name\"";
These fixes would require that the table is dropped and recreated as the current column name would be Workout
If you really wanted, you may get away with using public static final String COL2 = "Workout"; as that is what the column name will currently be. This wouldn't, at this stage, require dropping and recreating the table.
NOTE
You will likely have similar problems with COL4 being Excerise Name.
Related
i've been trying to update one column that stores data type double in it, but it failed without any error and i have no idea what i do wrong
i tried using both rawquery and update using ContentValues but both doesn't work, i know it's related to REAL data type in sqlite but i have no idea how to make it work
my table
private static final String SQL_CREATE_TABLE_WOUND
= "CREATE TABLE "
+ WOUND_TABLE_NAME + "("
//+ WOUND_ID + " TEXT,"
+ WOUND_POSITION + " INT,"
+ WOUND_SIZE + " DOUBLE,"
+ WOUND_OWNER + " TEXT,"
+ WOUND_PHOTO + " TEXT,"
+ WOUND_THUMBNAIL + " TEXT,"
+ WOUND_TREATED + " INT DEFAULT 0,"
+ WOUND_NUMBER + " INT,"
+ WOUND_DATE + " INT,"
+" FOREIGN KEY ("+WOUND_OWNER+") REFERENCES "+PATIENT_TABLE_NAME+"("+PATIENT_ID+"),"
+" FOREIGN KEY ("+WOUND_POSITION+") REFERENCES "+WOUND_POSITION_TABLE_NAME+"("+POSITION_NUMBER+"),"
+" PRIMARY KEY ("+ WOUND_OWNER +", "+ WOUND_POSITION +", "+ WOUND_NUMBER +", "+ WOUND_DATE +")"
+ ")";
this is my update function
public boolean setWoundSizeValue(String ownerID,String position,String number,long date,Double value){
boolean setSuccess = false;
/*approach 2
ContentValues cv = new ContentValues();
cv.put(WOUND_SIZE,value);*/
SQLiteDatabase db = this.getWritableDatabase();
/*approach 1, didn't work
try{
String strSQL = "UPDATE "+WOUND_TABLE_NAME+" SET "+WOUND_SIZE+" = "+value+" WHERE "+WOUND_OWNER+" = "+ownerID+" AND "
+ WOUND_POSITION+" = "+position+ " AND "+ WOUND_NUMBER +" = "+ number +" AND "+WOUND_DATE +" = "+date;
Cursor c = db.rawQuery(strSQL,null);
if(c!=null){
if(c.moveToFirst()){
setSuccess = true;
}
c.close();
}
}catch (Exception e){
}*/
/*approach 2 didn't work
long result = db.update(WOUND_TABLE_NAME,cv,WOUND_OWNER+"=? AND "+ WOUND_POSITION+"=? AND "+ WOUND_NUMBER +"=? AND "+WOUND_DATE+"=?"
,new String[]{ownerID,position,number,String.valueOf(date)});
if(result>0){
setSuccess = true;
}*/
return setSuccess;
}
and this is where i call my update function
public class SetWoundSizeActivity extends AppCompatActivity {
private EditText setWoundSize;
private Button saveButton;
private String owner;
private String position;
private String woundNum;
private String timer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_wound_size);
getSupportActionBar().setTitle("Set Wound Size");
Intent intent = getIntent();
owner = intent.getStringExtra("owner");
position = intent.getStringExtra("position");
woundNum = intent.getStringExtra("woundNum");
timer = intent.getStringExtra("timer");
setWoundSize = findViewById(R.id.wound_size);
saveButton = findViewById(R.id.wound_size_button);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DatabaseHelper helper = new DatabaseHelper(SetWoundSizeActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
final double woundSize = Double.valueOf(setWoundSize.getText().toString());
Toast.makeText(SetWoundSizeActivity.this,"size is"+woundSize,Toast.LENGTH_LONG).show();
//String ownerID,String position,String number,long date,float value
boolean result;
result = helper.setWoundSizeValue(owner,position,woundNum,Long.valueOf(timer),woundSize);
if(result){
Toast.makeText(SetWoundSizeActivity.this,"size inserted",Toast.LENGTH_LONG).show();
}else{Toast.makeText(SetWoundSizeActivity.this,"size not inserted",Toast.LENGTH_LONG).show();}
finish();
}
});
}
}
there is no error but the result confirming in where i call it is always false
rawQuery() does not work for sure because it is only used to fetch data in the form of a Cursor.
But update() with ContentValues does work and it is the recommended way:
ContentValues cv = new ContentValues();
cv.put(WOUND_SIZE, value);
int rows = db.update(
WOUND_TABLE_NAME,
cv,
WOUND_OWNER + " = ? AND " + WOUND_POSITION + " = ? AND " + WOUND_NUMBER + " = ? AND " + WOUND_DATE + " = ?",
new String[] {ownerID, position, number, String.valueOf(date)}
);
In the variable rows will be returned the number of rows updated.
Will this return multiple ID´S if there are multiple rows whit the same value(dataClicked) in COL_4 ?
COL_1="ID";
public int getDateId(String dateClicked) {
int dateID=0;
String last_query = "SELECT " + COL_1 + " FROM " + TABLE_NAME + " WHERE " + COL_4 + " = '" + dateClicked + "'";
Cursor c = database.rawQuery(last_query, null);
if (c != null && c.moveToFirst())
{
dateID = c.getInt(0);
}
c.close();
return dateID;
}
If it isn't can I store the values in an array ? And how can I do that
If you have multiple COL_4 with the same value as dateClicked then multiple COL_1 will be returned. You can add them to list like this:
public List<Integer> getDateIds(String dateClicked) {
List<Integer> ids = new ArrayList<>();
String last_query = "SELECT " + COL_1 + " FROM " + TABLE_NAME + " WHERE " + COL_4 + " = '" + dateClicked + "'";
Cursor c = database.rawQuery(last_query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
ids.add(c.getInt(0));
c.moveToNext();
}
c.close();
return ids;
}
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;
}
I had made SQLite database to my android application and it worked fine until I tried to add new column called "state". I have read previous posts in forum, and I tried adding new database version, modifying onUpgrade method, I have also tried deleting app, cleaning cache, and adding ALTER table but I still get error:
table has no column named state
So how do I update my database to make it work?
Here's my code
public class DatabaseHelper extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 3;
// Database Name
private static final String DATABASE_NAME = "dbase";
// Contacts table name
private static final String TABELL_BRUKERE = "bTab";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAVN = "navn";
private static final String KEY_ADR = "adresse";
private static final String KEY_BIL = "bil_kjennemerke";
private static final String KEY_STATE = "state";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "DROP TABLE IF EXISTS " + TABELL_BRUKERE + " CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT"
+ KEY_STATE + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String CREATE_CONTACTS_TABLE = "DROP TABLE IF EXISTS " + TABELL_BRUKERE + " CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT"
+ KEY_STATE + " TEXT" + ")";
if (oldVersion < 4 )
db.execSQL(CREATE_CONTACTS_TABLE);
// Create tables again
onCreate(db);
}
public void addContact(Bruker bruker) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAVN, bruker.getNavn()); // navn
values.put(KEY_ADR, bruker.getAdresse()); // Adresse
values.put(KEY_BIL, bruker.getBilmerke()); // Bil
values.put(KEY_STATE, bruker.getState()); // state
// Inserting Row
db.insert(TABELL_BRUKERE, null, values);
db.close(); // Closing database connection
}
public int getCount() {
String countQuery = "SELECT * FROM " + TABELL_BRUKERE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Getting single contact
public Bruker getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABELL_BRUKERE, new String[] { KEY_ID,
KEY_NAVN, KEY_ADR,KEY_BIL,KEY_STATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Bruker bruker = new Bruker(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4));
// return contact
return bruker;
}
// Getting All Contacts
public List<Bruker> getBrukere() {
List<Bruker> contactList = new ArrayList<Bruker>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABELL_BRUKERE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Bruker bruker = new Bruker();
bruker.setID(Integer.parseInt(cursor.getString(0)));
bruker.setNavn(cursor.getString(1));
bruker.setAdresse(cursor.getString(2));
bruker.setBilmerke(cursor.getString(3));
bruker.setState(cursor.getString(4));
// Adding contact to list
contactList.add(bruker);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Deleting single contact
public void deleteContact(Bruker bruker) {}
}
create query in Oncreate method:
" CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT,"
+ KEY_STATE + " TEXT" + ")";
and
Delete query in onupgrade method :
"DROP TABLE IF EXISTS " + TABELL_BRUKERE ;
In your onCreate and onUpdate you forget to put a "," after the KEY_BIL text.
Therefore android could not "parse" you string succesfull.
so, the CREATE_CONTACTS_TABLE string should look like this:
String CREATE_CONTACTS_TABLE = "DROP TABLE IF EXISTS " + TABELL_BRUKERE + " CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT," // add the "," here !!!
+ KEY_STATE + " TEXT" + ")";
KEY_BIL + " TEXT after you missed comma(,)
String CREATE_CONTACTS_TABLE = "DROP TABLE IF EXISTS " + TABELL_BRUKERE + " CREATE TABLE " + TABELL_BRUKERE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAVN + " TEXT,"
+ KEY_ADR + " TEXT,"
+ KEY_BIL + " TEXT,"
+ KEY_STATE + " TEXT" + ")";
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.