At first it was no such table:teacher_table , read posts told me to uninstall which i did and the the table was created but when tried to insert data in it,i got another error
Error inserting teacher_password=123 teacher_lname=soukat teacher_email=a#a.com course_id=1 teacher_mobile=12345432 admin_id=1 teacher_fname=galina teacher_no=tr001 teacher_username=mali
: no such table: main.course_name (code 1): , while compiling: INSERT INTO teacher_table(teacher_password,teacher_lname,teacher_email,course_id,teacher_mobile,admin_id,teacher_fname,teacher_no,teacher_username)VALUES(?,?,?,?,?,?,?,?,?)
Unfortunately i did not write any query to create the above table causing the error.
SitmDatabaseHelper.java
public class SitmDatabaseHelper extends SQLiteOpenHelper {
private static String dbName = "sitm_db.db";
private static int dbVersion =15;
private final static String dg = "databaseTest";
public SitmDatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
Log.d(dg, "SitmDatabaseHelper: db created");
}
//this method when called returns an instance of the helper class
public static SitmDatabaseHelper getDatabaseHelper(Context context){
SitmDatabaseHelper instance;
instance = new SitmDatabaseHelper(context);
return instance;
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
Log.d(dg, "onCreate: ONCREATE METHOD CALLED");
//creating the admin table
db.execSQL(AdminTable.adminTableQuery);
db.execSQL(StaffTable.staffTableQuery);
db.execSQL(CourseTable.courseTableQuery);
db.execSQL(BatchTable.batchTableQuery);
db.execSQL(TeacherTable.teacherTableQuery);
}catch (Exception e){
Log.d("TableCreation", "onCreate: table creation failed at "+e.getMessage());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//dropping older table if exists
try{
db.execSQL(AdminTable.dropAdminQuery);
db.execSQL(StaffTable.dropStaffQuery);
db.execSQL(CourseTable.dropCourseQuery);
db.execSQL(BatchTable.dropTableQuery);
db.execSQL(TeacherTable.dropTeacherQuery);
}catch (Exception e){
Log.d("dropTables", "onUpgrade: failed to drop table "+e.getMessage());
}
onCreate(db);
}
#Override //overriden to enable foreign keys
public void onOpen(SQLiteDatabase db) {
db.execSQL("PRAGMA foreign_keys=ON");
}
#Override
public void onConfigure(SQLiteDatabase db) {
db.setForeignKeyConstraintsEnabled(true);
}
}
TeacherTable.java
public final class TeacherTable {
//public static final String TEACHER_TABLE,teacherId,teacherNo,teacherFname,teacherLname,teacherUsername,teacherEmail, teacherPassword,
//
public static final String TEACHER_TABLE="teacher_table",
teacherId="teacher_id",
teacherNo="teacher_no",
teacherFname="teacher_fname",
teacherLname="teacher_lname",
teacherUsername="teacher_username",
teacherEmail="teacher_email",
teacherPassword="teacher_password",
teacherMobile="teacher_mobile",
teacherDate="teacher_date",
adminId="admin_id",
courseId="course_id";
public static final String teacherTableQuery="CREATE TABLE IF NOT EXISTS "+TeacherTable.TEACHER_TABLE+"("
+teacherId+" INTEGER PRIMARY KEY AUTOINCREMENT, "
+teacherNo+" TEXT,"
+teacherFname+" TEXT, "
+teacherLname+" TEXT, "
+teacherUsername+" TEXT,"
+teacherEmail+" TEXT,"
+teacherPassword+" TEXT,"
+teacherMobile+" TEXT,"
+adminId+" INTEGER NOT NULL,"
+courseId+" INTEGER NOT NULL, "
+"FOREIGN KEY("+adminId+")"+" REFERENCES "+AdminTable.adminTable+"("+AdminTable.sId +"),"
+"FOREIGN KEY("+courseId+")"+" REFERENCES "+CourseTable.courseName+"("+CourseTable.courseID+")"
+")";
public final static String dropTeacherQuery = "DROP TABLE IF EXISTS "+ TEACHER_TABLE;
}
>**TeacherDao.java ("add method")**
public class TeacherDao extends DBconnectionHelper {
public TeacherDao(Context tcontext) {
super(tcontext);
}
//add teacher
public void addTeacher(TeacherModal teacherModal){
long status;
//connection
openWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TeacherTable.adminId , teacherModal.getAdmin().getSuper_admin_id());
contentValues.put(TeacherTable.courseId,teacherModal.getCourse().getCourse_id());
contentValues.put(TeacherTable.teacherNo,teacherModal.getTeacher_no());
contentValues.put(TeacherTable.teacherFname , teacherModal.getTeacher_fname());
contentValues.put(TeacherTable.teacherLname , teacherModal.getTeacher_lname());
contentValues.put(TeacherTable.teacherUsername,teacherModal.getTeacher_username());
contentValues.put(TeacherTable.teacherEmail , teacherModal.getTeacher_email());
contentValues.put(TeacherTable.teacherPassword,teacherModal.getTeacher_password());
contentValues.put(TeacherTable.teacherMobile ,teacherModal.getTeacher_mobile());
try{
database.insert(TeacherTable.TEACHER_TABLE, null , contentValues);
}catch (Exception e){
Log.d("TeacherTable" , "reason "+e.getMessage());
e.printStackTrace();
}
// close connection
closeDatabase();
//return status;
}
AddTeacherFragment.java
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//DAOs
coursesDao = new CoursesDao(getActivity());
teacherDao = new TeacherDao(getActivity());
teacherDao.addTeacher(new TeacherModal("tr001","galina","soukat","mali",
"a#a.com","123","12345432",new SuperAdminModal(1),new CourseModal(1)));
}
Unfortunately i did not write any query to create the above table
causing the error.
Assuming that you really meant to say i did not write any query to use the above table; you did implicitly by defining teacher_table table with :-
+"FOREIGN KEY("+courseId+")"+" REFERENCES "+CourseTable.courseName+"("+CourseTable.courseID+")"
That is to insert into the teacher_table the value in the courseId column must match the specified column (whatever CourseTable.courseID resolves to) in the course_name table (i.e. CourseTable.courseName resolves to course_name).
However, as the table course_name doesn't exist the FOREIGN KEY constraint cannot even be checked. Hence the failure.
You MUST define the course_name table and you must also populate it with appropriate values unless you remove the FOREIGN KEY constraint.
Related
I'm developing a fitness tracker android app and have set up a SQLite database with 2 tables successfully. One table is for saving data about cardio exercises and one table is for saving data about weight lifting exercises. I'm able to save information to the cardio table (saved_workout_cardio) however, I can't seem to save anything to the weight lifting table (saved_workout_weights). I started off by coding the functionality for saving to 'saved_workout_cardio' table and once I had successfully got that working, I just copy and pasted the code and edited it to fit what was needed for saving to 'saved_workout_weights' table, however unfortunately it's not working and I'm puzzled as to why.
Below is the code from my databasehelper java class where I create the database as well as 2 methods, 1 for saving data to each table:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "FitnessTracker.db";
public static final String TABLE_WEIGHTS = "saved_workout_weights";
public static final String COL_1 = "ID";
public static final String COL_2 = "DATE";
public static final String COL_3 = "EXERCISE";
public static final String COL_4 = "WEIGHT";
public static final String COL_5 = "REPS";
public static final String COL_6 = "SETS";
public static final String TABLE_CARDIO = "saved_workout_cardio";
public static final String COL_1a = "ID";
public static final String COL_2a = "DATE";
public static final String COL_3a = "TIME";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_WEIGHTS + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,DATE TEXT,EXERCISE TEXT,WEIGHT INTEGER,REPS INTEGER)");
db.execSQL("create table " + TABLE_CARDIO + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,DATE TEXT,TIME INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_WEIGHTS);
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_CARDIO);
onCreate(db);
}
public boolean saveData (String date, String time) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2a, date);
contentValues.put(COL_3a, time);
long result = db.insert(TABLE_CARDIO, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public boolean saveData2 (String date, String exercise, String weight, String reps, String sets) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put(COL_2, date);
contentValues2.put(COL_3, exercise);
contentValues2.put(COL_4, weight);
contentValues2.put(COL_5, reps);
contentValues2.put(COL_6, sets);
long result = db.insert(TABLE_WEIGHTS, null, contentValues2);
if(result == -1)
return false;
else
return true;
}
}
Now here's the relevant code from my 'Cardio' java class where I'm calling the method for saving data to the cardio table (this method works and I'm able to save data to the cardio table successfully:
public void saveCardioData () {
btnSaveCardio.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.saveData(txtDate.getText().toString(),
txtTimer.getText().toString() );
if(isInserted = true)
Toast.makeText(Cardio.this, "Workout saved", Toast.LENGTH_LONG).show();
else
Toast.makeText(Cardio.this, "Error saving workout", Toast.LENGTH_LONG).show();
}
}
);
}
Now here's the 'weights' java class where I call the method for saving data to the weights table. As you can see I have set up a toast message to appear if data is successfully inserted. Whenever I click to save the workout in my app the toast message tells me that the workout has been successfully saved however, when I check the weights table in my database no values have been saved.
public void saveWeightsData () {
btnSaveWeights.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.saveData2(exerciseVal.getText().toString(),
weightVal.getText().toString(),
repVal.getText().toString(),
setVal.getText().toString(),
dateVal.getText().toString() );
if(isInserted = true)
Toast.makeText(WeightsMain.this, "Workout saved", Toast.LENGTH_LONG).show();
else
Toast.makeText(WeightsMain.this, "Error saving workout", Toast.LENGTH_LONG).show();
}
}
);
}
Really confused as to why I'm having this problem, so if anyone can tell me why it would be greatly appreciated! :)
EDIT: I'm using Android Device Monitor within Android studio to pull the database from the android emulator's storage to my pc. I then use SQLite Manager firefox addon to check the 2 tables.
There's no SETS column in your table but you're trying to insert data to it. That won't work.
After adding the SETS column to the CREATE TABLE, you can uninstall your app to force onCreate() to execute again.
In my application, I use the users password as the encryption key for encryption media. I am encrypting media using PBEWithMD5AndDES and this works fine with a password stored in shared preferences. Now to achieve a level of security I am removing the password from shared preferences and using a singleton that is only kept alive during the app session (as the app logs out automatically requiring entry of the password). Below is my singleton:
public class Credentials {
private static Credentials dataObject = null;
private Credentials() {
// left blank intentionally
}
public static Credentials getInstance() {
if (dataObject == null)
dataObject = new Credentials();
return dataObject;
}
private char[] user_password;
public char[] getUser_password() {
return user_password;
}
public void setUser_password(char[] user_password) {
this.user_password = user_password;
}
}
The password is zeroed out from memory if the app logs out, or is log out by the user or gets destroyed. However at times I am getting a null pointer when trying to retrieve the password.
char[] pswd = Credentials.getInstance().getUser_password();
What could be causing this? is there any other method I can use except a singleton?
Alternatively, you can store the password using built-in Sqlite db, though I'd still recommend you save it encrypted for max protection. You can do this in 4 steps:
2) Create an entity object to store the password:
public class Password {
int password_id; // will be auto-increamted
String password;
public Password(int password_id, String password) {
this.password_id = password_id;
this.password = password;
}
// getter/setters ...
}
2) Create an Sqlite utility object:
public class SQLiteDBAdapter {
protected static final String DATABASE_NAME = "mydb";
protected static final int DATABASE_VERSION = 1;
protected Context context;
protected static DatabaseHelper mDbHelper;
public static final String TABLE_PASSWORD = "tbl_password";
// columns
public static final String PASSWORD_ID = "_id";
public static final String PASSWORD = "password";
// create table string
private static final String CREATE_TABLE_PASSWORD =
"CREATE TABLE if not exists " + TABLE_PASSWORD + " ( " +
PASSWORD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
PASSWORD + " TEXT NOT NULL);";
public SQLiteDBAdapter(Context context) {
context = context.getApplicationContext();
}
public SQLiteDatabase openDb() {
if (mDbHelper == null) {
mDbHelper = new DatabaseHelper(mContext);
}
return mDbHelper.getWritableDatabase();
}
protected static class DatabaseHelper extends SQLiteOpenHelper {
// -------------------------------------------------------------------------------------------
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// -------------------------------------------------------------------------------------------
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PASSWORD);
}
// -------------------------------------------------------------------------------------------
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " +
newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS routes");
onCreate(db);
}
}
}
3) Extend an Sqlite object to manipulate the table (CRUD operations):
public class PasswordDbAdapter extends SQLiteDBAdapter {
private SQLiteDatabase db;
// these are column corresponding indices
public static final int INDEX_PASSWORD_ID = 0; // an auto-increment
public static final int INDEX_PASSWORD = 1;
public PasswordDbAdapter(Context context) {
super(context);
}
public void addPassword(String password) {
db = openDb();
ContentValues values = new ContentValues();
values.put(PASSWORD, password);
db.insert(TABLE_PASSWORD, null, values);
}
public void updatePassword(String password) {
db = openDb();
ContentValues values = new ContentValues();
values.put(PASSWORD, password);
db.update(TABLE_PASSWORD, values, null);
}
public void deletePassword() {
db = openDb();
db.delete(TABLE_PASSWORD, null, null);
}
public boolean isEmpty() {
db = openDb();
boolean empty = true;
Cursor cur = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_PASSWORD, null);
if (cur != null && cur.moveToFirst()) {
empty = (cur.getInt (0) == 0);
}
cur.close();
return empty;
}
public Password fetchPassword() { // ok because there's only one password record
db = openDb();
Cursor cursor = db.query(TABLE_PASSWORD, new String[]{PASSWORD_ID, PASSWORD},
null, null, null, null, null, null);
if (cursor != null &&
cursor.moveToFirst()) {
return new Password(
cursor.getString(INDEX_PASSWORD_ID),
cursor.getInt(INDEX_PASSWORD));
}
return null;
}
}
4) Finally, save/update/retrieve the password as desired:
public class MainActivity extends AppCompatActivity {
private PasswordDbAdapter passwordDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// initialize the password db
passwordDB = new PasswordDbAdapter(this);
// check if password record exists
if (passwordDB.isEmpty() {
// save a new copy
passwordDB.addPassword("the_password"); // more secure if it is saved encrypted
} else {
// update it
passwordDB.updatePassword("the_password");
}
}
...
public String fetchPassword() {
return passwordDB.fetchPassword(); // or first decrypt it, then return it
}
}
I recently launched an app on the android app store that contained a SQLite database.
I am now attempting to release an update of the app, and want to add more data into the existing database, however have come a bit unstuck. I have read answers on SO that outline making changes to the database itself, however I want my tables and columns to stay the same, only add new data in.
The data that i want to add to the database is pulled from CSV files in the Raw file, and originally loaded into the database when the user registers for the app.
I have a feeling I am going to need to implement the onUpgrade method, however should I be adding the new data from the CSV files in at that point as well? Is it a matter of simple updating the database version and using the onUpgrade to load the new data?
I am fairly new to SQLite DB, so any help would be hugely appreciated.
CourseDBHelper Code
public class CourseDBHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "CourseDB";
// Create two table names
private static final String TABLE_COURSES = "courses";
// Universities Table Columns names
private static final String COURSE_NAME = "Course_name";
private static final String UNI_NAME = "Uni_name";
private static final String COURSE_DURATION = "Duration";
private static final String COURSE_STUDY_MODE = "Study_mode";
private static final String COURSE_QUALIFICATION = "Qualification";
private static final String COURSE_ENTRY_STANDARDS = "Entry_standards";
private static final String COURSE_GRADUATE_PROSPECTS = "Graduate_prospects";
private static final String COURSE_STUDENT_SATISFACTION = "Student_satisfaction";
private String CREATE_COURSES_TABLE = "CREATE TABLE courses" +
"(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"Course_name TEXT NOT NULL," +
"Uni_name TEXT NOT NULL," +
"Duration TEXT NOT NULL," +
"Study_mode TEXT NOT NULL," +
"Qualification TEXT NOT NULL," +
"Entry_standards TEXT NOT NULL," +
"Graduate_prospects TEXT NOT NULL," +
"Student_satisfaction TEXT NOT NULL" +
");";
private static final String[] COLUMNS = {
COURSE_NAME,
UNI_NAME,
COURSE_DURATION,
COURSE_STUDY_MODE,
COURSE_QUALIFICATION,
COURSE_ENTRY_STANDARDS,
COURSE_GRADUATE_PROSPECTS,
COURSE_STUDENT_SATISFACTION
};
public CourseDBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// TODO: REMOVED NOT NULL FROM EVERY COLUMN FOR TEST PURPOSES, WILL NEED TO BE READDED
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_COURSES_TABLE);
}
public void deleteAll()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete("courses", null, null);
db.execSQL("delete from " + "courses");
db.close();
}
// Getting one course by course name and uni name
public Course getCourse(String courseName, String uniName) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_COURSES, COLUMNS, " Course_name = ? AND Uni_name = ?",
new String[]{courseName, uniName},
null,
null,
null,
null);
if (cursor != null)
cursor.moveToFirst();
Course course = new Course();
/*
System.out.println(cursor.getString(0));
System.out.println(cursor.getString(1));
System.out.println(cursor.getString(2));
System.out.println(cursor.getString(3));
System.out.println(cursor.getString(4));
System.out.println(cursor.getString(5));
System.out.println(cursor.getString(6));
*/
course.setCourseName(cursor.getString(0));
course.setUniversity(cursor.getString(1));
course.setCourseDuration(cursor.getString(2));
course.setStudyMode(cursor.getString(3));
course.setQualification(cursor.getString(4));
course.setEntryStandards(cursor.getString(5));
course.setGradProspects(cursor.getString(6));
course.setStudentSatisfaction(cursor.getString(7));
return course;
}
public void addCourse(Course course)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COURSE_NAME, course.getCourseName());
values.put(UNI_NAME, course.getUniversity());
values.put(COURSE_DURATION, course.getCourseDuration());
values.put(COURSE_STUDY_MODE, course.getStudyMode());
values.put(COURSE_QUALIFICATION, course.getQualification());
values.put(COURSE_ENTRY_STANDARDS, course.getEntryStandards());
values.put(COURSE_GRADUATE_PROSPECTS, course.getGradProspects());
values.put(COURSE_STUDENT_SATISFACTION, course.getStudentSatisfaction());
db.insert(TABLE_COURSES,
null, //nullColumnHack
values);
db.close();
}
public ArrayList<Course> getAllCourses()
{
ArrayList<Course> courses = new ArrayList<>();
// 1. build the query
String query = "SELECT * FROM " + TABLE_COURSES;
// 2. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
// 3. go over each row, build course and add it to list
Course course;
if(cursor.moveToFirst()){
cursor.moveToNext();
do{
course = new Course();
course.setCourseName(cursor.getString(1));
course.setUniversity(cursor.getString(2));
course.setCourseDuration(cursor.getString(3));
course.setStudyMode(cursor.getString(4));
course.setQualification(cursor.getString(5));
course.setEntryStandards(cursor.getString(6));
course.setGradProspects(cursor.getString(7));
course.setStudentSatisfaction(cursor.getString(8));
// Add course to courses list
courses.add(course);
} while(cursor.moveToNext());
}
// return courses
return courses;
}
public int getDBCount()
{
SQLiteDatabase db = this.getWritableDatabase();
String count = "SELECT count(*) FROM courses";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
return icount;
}
public void deleteCourse(Course course) {
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. delete
db.delete("courses", //table name
"Course_name = ? AND Uni_name = ?", // selections
new String[] { course.getCourseName(), course.getUniversity() }); //selections args
// 3. close
db.close();
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
Method that loads data from CSV file to SQlite DB
public void populateCourseDatabase(int id) {
// NOW POPULATE THE COURSE DATABASE FILE
inputStream = getResources().openRawResource(R.raw.coursesone);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String word;
String cvsSplitBy = ",";
try{
while((word = reader.readLine()) != null){
Log.d(TAG, "constructing Course object from: " + word);
String[] segment = word.split(cvsSplitBy);
Course course = new Course();
course.setCourseName(segment[0]);
course.setUniversity(segment[1]);
course.setCourseDuration(segment[2]);
course.setStudyMode(segment[3]);
course.setQualification(segment[4]);
course.setEntryStandards(segment[5]);
course.setGradProspects(segment[6]);
course.setStudentSatisfaction(segment[7]);
myCourseDBHelper.addCourse(course);
progressBar.setProgress(count);
count = count + 1;
System.out.println("Sucessfully added: " + course.toString());
}
}
catch(IOException e1){
e1.printStackTrace();
System.out.println("SOMETHING WENT WRONG");
}
}
SQLiteOpenHelper onCreate() and onUpgrade() callbacks are invoked when the database is actually opened, for example by a call to getWritableDatabase().onCreate() is only run when the database file did not exist and was just created. onUpgrade() is only called when the database file exists but the stored version number is lower than requested in constructor.Increment the database version so that onUpgrade() is invoked.
Example pseudo code below
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
//upgrade logic from version 1 to 2
case 2:
//upgrade logic from version 2 to 3
case 3:
//upgrade logic from version 3 to 4
break;
default:
throw new IllegalStateException(
"onUpgrade() with unknown oldVersion " + oldVersion);
}
}
When I run my android app I keep getting the error (1) no such table userTable, as far as I am aware I am creating the table in
TABLE_CREATE = "create table userTable("
+ USER + " text not null, " + PWD + " text not null, );";
I have two other databases in this project and the are working fine, any help is welcome.
package com.weightpro.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class usrPwdDB {
public static final String USER = "userName";
public static final String PWD = "password";
public static final String TABLE_NAME = "userTable";
public static final String DATA_BASE_NAME = "userdatabase";
public static final String KEY_ROWID = "_id";
public static final int DB_VERSION = 2;
private static final String TABLE_CREATE = "create table userTable("
+ USER + " text not null, " + PWD + " text not null, );";
DBHelper WDBHelper;
Context mContext;
SQLiteDatabase db;
public usrPwdDB(Context mContext) {
this.mContext = mContext;
WDBHelper = new DBHelper(mContext);
}
private static class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context) {
super(context,DATA_BASE_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS userTable");
onCreate(db);
}
}
public usrPwdDB open()
{
db = WDBHelper.getWritableDatabase();
return this;
}
public void close(){
WDBHelper.close();
}
public long insertInfo(String userName, String password){
ContentValues content = new ContentValues();
content.put(USER, userName);
content.put(PWD, password);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public boolean getUserNameAndPassword(String userName, String Password) throws SQLException {
Cursor mCursor =
db.query(true, TABLE_NAME, new String[] {USER,
PWD},USER+"='"+userName+"' AND password='"+Password+"'", null,
null, null, null, null);
if (mCursor.getCount() > 0)
{
return true;
}
return false;}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[] {USER, PWD},null,null,null,null,null);
}
}
remove the last comma , from the create table syntax,
private static final String TABLE_CREATE =
"create table userTable("
+ USER + " text not null, "
+ PWD + " text not null, );"; // remove this comma after not null
The correct syntax should be
private static final String TABLE_CREATE =
"create table userTable("
+ USER + " text not null, "
+ PWD + " text not null );";
You go wrong over here
+ USER + " text not null, " + PWD + " text not null, );"; //remove , from last text not null
correct SQL command with below
private static final String TABLE_CREATE = "create table userTable("
+ USER + " text not null, " + PWD + " text not null);" ;
private static final String TABLE_CREATE = "create table userTable("
+ USER + " text not null, " + PWD + " text not null,);" ;
remove "," after "text not null" and also remove ";"(semicolon) in the string, that is not needed i think,
then clear data or uninstall application then execute again
even though the creation of table failed i think next time onCreate() in SQLiteOpenHelper only executes once, so you will need to clear data of application
if you are using separate class for separate table and using same DB name, then all the tables in the first using class will be ok, and others will not be created since for a single database onCreate() function works only one, even if there is separate classes each with onCreate(),
onCreate() function creates a file in DB location of android file system when first called onCreate(), if the onCreate called again it check for the existence of DBNAME file in DB location and avoid creating if its exit, I think this is logic behind it...
so keep one onCreate() function for a single DB file and create all tables in that function
This is my Database class
public class ProgramDbAdapter{
public static final String KEY_ROWID = "_id";
public static final String KEY_PROGRAM_TITLE = "ProgramTitle";
public static final String KEY_PROGRAM_DATE = "ProgramDate";
public static final String KEY_PROGRAM_TIME = "ProgramTime";
public static final String KEY_PROGRAM_CHANNEL = "ProgramChannel";
private static final String DATABASE_CREATE =
"CREATE TABLE " + DATABASE_TABLE + " (" + "_id integer primary key autoincrement, "
+ "ProgramTitle text, " + "ProgramDate varchar(20), "
+ "ProgramTime varchar(20), " + "ProgramChannel text)";
private static final String DATABASE_UPGRADE = "DROP TABLE IF EXISTS " + DATABASE_TABLE;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL(DATABASE_UPGRADE);
onCreate(db);
}
}
public ProgramDbAdapter open() throws SQLException{
mDbHelper = new DatabaseHelper(mcontext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public long CreateData(String ProgramTitle, String ProgramDate, String ProgramTime, String ProgramChannel){
ContentValues initialvalues = new ContentValues();
initialvalues.put(KEY_PROGRAM_TITLE, ProgramTitle);
initialvalues.put(KEY_PROGRAM_DATE, ProgramDate);
initialvalues.put(KEY_PROGRAM_TIME, ProgramTime);
initialvalues.put(KEY_PROGRAM_CHANNEL, ProgramChannel);
return mDb.insert(DATABASE_TABLE, null, initialvalues);
}
}
This is my main class
public class Program extends ExpandableListActivity{
public void onCreate(Bundle savedInstanceState) {
mDbHelper = new ProgramDbAdapter(this);
mDbHelper.open();
mDbHelper.CreateData("a","a","a","a");
}
}
when i call open() and createdata function, the logcat tell me no such table:Program. where is the problem is?
There is no varchar type in sqlite, see here. Use text instead.
I don't see where 'DATABASE_TABLE' is coming from.
Also, you should use the "rawQuery()", "query()"-Methods or a "SQLiteStatement" to bind parameters into your SQL-Statement.
And last but not least, SQLite doesn't know any 'varchar'. Check here for all Data types: Link
varchar is translated to text ...
from vladimir link:
If the declared type of the column
contains any of the strings "CHAR",
"CLOB", or "TEXT" then that column has
TEXT affinity. Notice that the type
VARCHAR contains the string "CHAR" and
is thus assigned TEXT affinity.
problem is that u created db in first run and there was different Create statment ...
delete app data from android settings or change DATABASE_VERSION