Problems with SQLiteException: no such table - java

I have a database with two tables and every time I try to add a new item to the second table it says that there is no such table. Please help.
DatabaseHelper:
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TableName + " ( "+COL_1 +" INTEGER PRIMARY KEY AUTOINCREMENT, "+COL_2+ " TEXT, "+COL_3+ " TEXT, "+COL_4+" TEXT, "+COL_5+ " INTEGER)";
String createSubjectsTable = "CREATE TABLE "+SubjectsTableName+" ( "+Subjects_COL_1+" INTEGER PRIMARY KEY AUTOINCREMENT, "+Subjects_COL_2+" TEXT, "+Subjects_COL_3+" TEXT, "+Subjects_COL_4+" TEXT, "+Subjects_COL_5+" TEXT)";
db.execSQL(createTable);
db.execSQL(createSubjectsTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TableName);
db.execSQL("DROP TABLE IF EXISTS "+SubjectsTableName);
onCreate(db);
}
The add method from DatabaseHelper:
public boolean addSubjectData (String name, String letters, String teacher, String color){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Subjects_COL_2,name);
contentValues.put(Subjects_COL_3,letters);
contentValues.put(Subjects_COL_4,teacher);
contentValues.put(Subjects_COL_5,color);
long result = db.insert(SubjectsTableName, null, contentValues);
if (result==-1){
return false;
}
else{
return true;
}
}
The place where the new item creation is:
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(name!=null && letters!=null && color!=null){
mDatabase.addSubjectData(name,letters,teacher,color);
}
}
});

you may have changed the schema and did not increase the db version so you may have two options:
increase the db version
or if you did not publish previous version of your app uninstall app from emulator then run project

Related

Adding a new column in SQLite Database

I am pretty new to Android development and I am trying to implement a database for my app.
I started with only having one column in the database (COLUMN_DATE) and then added another column (COLUMN_REPEAT). This worked fine and printed the results as expected. However, when I tried adding another column (COLUMN_ACCOUNT), printDatabase() in MainActivity did not print anything.
I understand you can view what is in your database by using Android Device Monitor, but I keep getting an error when I click on that so I cannot use it (That is a separate issue which I haven't been able to solve). Hence, I am unsure if it is just an issue with printing the database or if there is actually any data in the database at all.
Any help would be much appreciated
----MainActivity.java----
dbHandler = new DatabaseHandler(this, null, null, 1);
printDatabase();
//Print the database
public void printDatabase() {
String dbString = dbHandler.databaseToString();
recordsTextView.setText(dbString);
}
//Add an item to the database
public void addButtonClicked(View view){
Income date = new Income(dateView.getText().toString());
Income repeat = new Income(repeatSpinner.getSelectedItem().toString());
Income account = new Income(accountSpinner.getSelectedItem().toString());
dbHandler.addData(date, repeat, account);
printDatabase();
}
//Delete items with input date from database
public void deleteButtonClicked(View view){
String inputText = dateView.getText().toString();
dbHandler.deleteData(inputText);
printDatabase();
}
----DatabaseHandler.java----
public class DatabaseHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "IncomeExpenseDB.db";
public static final String TABLE_NAME = "income_expense";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATE = "date";
public static final String COLUMN_REPEAT = "repeat";
public static final String COLUMN_ACCOUNT = "account";
public DatabaseHandler(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_DATE + " TEXT, " + COLUMN_REPEAT + " TEXT, " +
COLUMN_ACCOUNT + " TEXT " +
");";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add a new row to the database
public void addData(Income date, Income repeat, Income
account){
ContentValues values = new ContentValues();
values.put(COLUMN_DATE, date.get_item());
values.put(COLUMN_REPEAT, repeat.get_item());
values.put(COLUMN_ACCOUNT, account.get_item());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_NAME, null, values);
db.close();
}
//Delete data from the database
public void deleteData(String date){
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_DATE + "=\""
+ date + "\";");
}
// Create a string to print out in MainActivity
public String databaseToString() {
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
//Cursor points to a location in results
Cursor c = db.rawQuery(query, null);
//Move to first row in results
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("date")) != null &&
c.getString(c.getColumnIndex("repeat")) != null &&
c.getString(c.getColumnIndex("account")) != null) {
dbString += c.getString(c.getColumnIndex("date"));
dbString += " ";
dbString += c.getString(c.getColumnIndex("repeat"));
dbString += " ";
dbString += c.getString(c.getColumnIndex("account"));
dbString += "\n";
}
c.moveToNext();
}
db.close();
return dbString;
}
}
----Income.java----
public class Income {
private int _id;
private String _item;
public Income(){
}
public Income(String item) {
this._item = item;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_item() {
return _item;
}
public void set_item(String _item) {
this._item = _item;
}
}
Uninstalling and reinstalling is very naive approach which will only work in development phase. When your app goes on to play store, users are not going to uninstall and reinstall the app.
Correct way to update the database for published apps is to increase your db version and use onUpgrade method to update your database.
look at this method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
In current scenario if you just increase your db version, it will drop existing table and create a new one with new columns and specifications. The downside is that you'll lose all of your existing data.
If you want to save existing data and add new column to db, you have to do something like this -
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
//add new column
sqLiteDatabase.execSQL("ALTER TABLE "+ TABLE_NAME + " ADD COLUMN "+ NEW_COLUMN + " INTEGER/TEXT ");
}
}
Just update your version of database when you add any column or make any update in the table. ... this helps me hope it will also work for you.

can not Creating tables in sqlite database on android

I can not create a table. It shows that the database is created and I can also insert a row, but the table is not created.
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int Database_version = 2;
public static final String Tag = DatabaseOperations.class.getSimpleName();
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null,Database_version);
Log.d("Tag", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(SQL_CREATE_ENTRIES);
Log.d("Tag", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putInformation(DatabaseOperations drop, String name, String pass, String email) {
SQLiteDatabase SQ = drop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_ID, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Tag", "inert a row");
}
public Cursor getInformation(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableData.TableInfo.USER_ID, TableData.TableInfo.USER_PASS, TableData.TableInfo.USER_EMAIL};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, null, null, null, null, null);
return CR;
}
}
You're missing a , between USER_EMAIL and USER_PASS columns in the CREATE TABLE.
After adding it you can uninstall your app to recreate the database. When is SQLiteOpenHelper onCreate() / onUpgrade() run?
You miss comma in USER PASS type.Uninstall the application and install it again each time you add something new to sqlite database because the table structure has been changed.So you need to reinstall the new application .
The code should be like this
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT ,"+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ")";

Android how to insert data into database outside of the database helper class

I have set up a SQLite database which is working fine in terms of creating the tables that i need. What i have been trying to do now is insert into the database but from another class (Signup.java). I want to grab text input into edittext and insert this into the database,but only when a button is clicked.
See my DatabaseHelper class below:
package com.example.testerrquin.euro2016fanguide;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Euro2016.db";
public static final String TABLE_USERS = "Users_table";
public static final String TABLE_CAPACITY = "Capacity_table";
public static final int CapacityOne = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TABLE_USERS +" (UserID INTEGER PRIMARY KEY AUTOINCREMENT, Forename TEXT, Surname TEXT, Email TEXT, Password TEXT, Country TEXT)");
db.execSQL("Create table " + TABLE_CAPACITY +" (CapacityID INTEGER PRIMARY KEY AUTOINCREMENT, Capacity INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CAPACITY);
onCreate(db);
}
}
Basically i need to run the line starting with "db.execSQL". I probably need to reference 'db' somewhere to link up to Databasehelper class but not sure. At the moment i am getting 'Cannot resolve symbol 'db'.
CompleteB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String grabFirstname = UsernameET.getText().toString();
String grabSurname = SurnameET.getText().toString();
String grabEmail = EmailET.getText().toString();
String grabPassword = PasswordET.getText().toString();
String grabCountry = CountryDrop.getSelectedItem().toString();
db.execSQL("Insert into Users_table (Forename, Surname, Email, Password, Country) values ((" + grabFirstname +"),(" + grabSurname +"),(" + grabEmail +"), (" + grabPassword +"), (" + grabCountry +"))");
Intent i=new Intent(Signup.this,Login.class);
startActivity(i);
}
});
Thanks in advance.
Declare any method that you need in your SQL helper class:
public void sampleMethod(String[] arguments) {
ContentValues values = new ContentValues();
values.put("Column1", arguments[0]);
values.put("Column2", arguments[1]);
values.put("Column3", arguments[2]);
....
db.insert(TABLE_NAME, null, values);
}
In your Activity:
#Override
public void onClick(View v) {
String grabFirstname = UsernameET.getText().toString();
String grabSurname = SurnameET.getText().toString();
String grabEmail = EmailET.getText().toString();
String grabPassword = PasswordET.getText().toString();
String grabCountry = CountryDrop.getSelectedItem().toString();
DatabaseHelper helper = new DatabaseHelper(context); //replace context with your activity context. "this" would refer to your onClickListener so be careful.
helper.sampleMethod(new String[]{
"user",
"pass",
"foo",
"bar",
...
});
//rest of your code
}
Also, on another note, make sure you close your database when you are done with it. I personally would call getWritableDatabase in each method and then close the database at the end of the method. Something like:
public class DatabaseHelper extends SQLiteOpenHelper {
Context c;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
c = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table " + TABLE_USERS +" (UserID INTEGER PRIMARY KEY AUTOINCREMENT, Forename TEXT, Surname TEXT, Email TEXT, Password TEXT, Country TEXT)");
db.execSQL("Create table " + TABLE_CAPACITY +" (CapacityID INTEGER PRIMARY KEY AUTOINCREMENT, Capacity INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CAPACITY);
onCreate(db);
}
public void sampleMethod(String[] arguments) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Column1", arguments[0]);
values.put("Column2", arguments[1]);
values.put("Column3", arguments[2]);
....
db.insert(TABLE_NAME, null, values);
db.close();
}
Declare "SQLiteDatabase db" instance out side the constructor in your DatabaseHelper.
Create a method in DatabaseHelper class which takes param which requires and inserts into db
Then in your activity create an instance of DatabaseHelper and call the method which you created in step 2
please check for other singleton patterns
Why not make DatabaseHelper a singleton object by declaring all the methods static? Then you can call it from anywhere in your activities.

Show Data from Multiple Tables with connected id in SQLite

I have two tables in my SQLite database, first users and second jobs, where a user can have multiple jobs to do
Data in users table
id name
1 Me
2 You
where id generated through : id integer primary key autoincrement
Data in jobs table
id jobname userid
1 JobA 2
2 JobB 2
3 JobC 1
where id generated through : id integer primary key autoincrement
where user_id fetched from users table
Now, I would like to loop through all the users and jobs table one by one, if user has some job to do then need to show Toast
JobC assigned to user1
DatabaseHandler.java:
public class DatabaseHandler extends SQLiteOpenHelper {
..................
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TABLE_USERS +
"(id integer primary key autoincrement," +
" name text);");
db.execSQL("CREATE TABLE " + TABLE_JOBS +
"(id integer primary key autoincrement," +
" jobname text" +
" userid long);");
}
// Insert data into users table
public long InsertUsers(String name) {
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("name", name);
long rows = db.insert(TABLE_USERS, null, Val);
db.close();
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
// Insert data into jobs table
public long InsertJobs(String jobname, long userid) {
try {
SQLiteDatabase db;
db = this.getWritableDatabase(); // Write Data
ContentValues Val = new ContentValues();
Val.put("jobname", jobname);
Val.put("userid", userid);
long rows = db.insert(TABLE_JOBS, null, Val);
db.close();
return rows; // return rows inserted.
} catch (Exception e) {
return -1;
}
}
public String[] getUsersId() {
String selectQuery = "SELECT id FROM " + TABLE_USERS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] data = null;
if (cursor.moveToFirst()) {
do {
int id_row=cursor.getInt(cursor.getColumnIndex("id"));
Log.d("TAG","id is ::"+id_row);
} while (cursor.moveToNext());
}
db.close();
return data;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_JOBS);
onCreate(db);
}
}
And in MainActivity.java:
DatabaseHandler dh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dh = new DatabaseHandler(MainActivity.this);
buttonGetData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dh.getUsersId();
}
});
}
You can do it using join:
db.rawQuery("SELECT j.jobname, u.name FROM jobs j JOIN users u ON j.userid=u.id");
I won't give you the exact code but try to execute the query something similar to this. And do a little research before asking the question.
String newQuery="SELECT db1.your_column db2.you_coloum2 from table1 db1, table2 db2 where db2.u_id=db1.id;
fetch the results using Cursor

Upgrade SQLiteDatabase Android

I am writing application which uses SQLite. At first, my database had only one table called products. Now I want to add one more table called favouriteproduct_table. I wrote db.exec("create table fav_product") command in the onCreate method, but my app is crashing saying that no table found for Product_fav.
This is my code before adding favourite_product_table.
private static class OpenHelper extends SQLiteOpenHelper
{
OpenHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, systemSerID TEXT, systemSerName TEXT, productID TEXT, productName TEXT, productDesc TEXT, productType TEXT, batchID TEXT, minVal TEXT, maxVal TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
Above code is working fine, but when I try to create a new table using the following code, my app crashes.
private static class OpenHelper extends SQLiteOpenHelper
{
OpenHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, systemSerID TEXT, systemSerName TEXT, productID TEXT, productName TEXT, productDesc TEXT, productType TEXT, batchID TEXT, minVal TEXT, maxVal TEXT)");
db.execSQL("CREATE TABLE " + TABLE_TOPUP_FAVOURITE + "(id INTEGER PRIMARY KEY, systemSerID TEXT, systemSerName TEXT, productID TEXT, productName TEXT, productDesc TEXT, productType TEXT, batchID TEXT, minVal TEXT, maxVal TEXT, imageid TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
Check your question what you have asked
Now I want to add one more table called favouriteproduct_table
and then
db.exec("create table fav_product")
and at last
my app is crashing saying that no table found for Product_fav
Now see what is the error.
In three of your sentence tables are of different names.
DO you have all these tables(favouriteproduct_table, fav_product, Product_fav) different which each others?

Categories