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?
Related
I've fixed an issue in my code that doesn't allow me to add records to my SQLite database. Even though I've fixed it, I don't really get what's wrong with my first code, so if anyone is willing to help me understand please do explain!
My first code:
package com.example.starbuzz;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class StarbuzzDatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "DatabaseName";
public static final int DATABASE_VERSION = 2;
public StarbuzzDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
updateMyDatabase(db, 0, DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
updateMyDatabase(db, oldVersion, newVersion);
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onDowngrade(db, oldVersion, newVersion);
}
private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion){
if (oldVersion < 1){
db.execSQL("CREATE TABLE DRINK (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"NAME TEXT," +
"DESCRIPTION TEXT," +
"IMAGE_RESOURCE_ID INTEGER);");
insertDrink(db, "Latte", "Expresso and steamed milk", R.drawable.latte, false);
insertDrink(db, "Cappuccino", "Expresso, hot milk, and a steamed milk foam", R.drawable.cappuccino, true);
insertDrink(db, "Filter", "Highest quality beans roasted and brewed fresh", R.drawable.filter, false);
}
if (oldVersion < 2){
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC");
}
}
public static void insertDrink(SQLiteDatabase db,
String name,
String description,
int resourceID,
boolean favorite){
ContentValues drinkValues = new ContentValues();
drinkValues.put("NAME", name);
drinkValues.put("DESCRIPTION", description);
drinkValues.put("IMAGE_RESOURCE_ID", resourceID);
drinkValues.put("FAVORITE", favorite);
db.insert("DRINK", null, drinkValues);
}
}
My new code:
package com.example.starbuzz;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class StarbuzzDatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "DatabaseName";
public static final int DATABASE_VERSION = 2;
public StarbuzzDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// updateMyDatabase(db, 0, DATABASE_VERSION);
db.execSQL("CREATE TABLE DRINK (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"NAME TEXT," +
"DESCRIPTION TEXT," +
"IMAGE_RESOURCE_ID INTEGER);");
//Due to update version 2
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC");
insertDrink(db, "Latte", "Expresso and steamed milk", R.drawable.latte, false);
insertDrink(db, "Cappuccino", "Expresso, hot milk, and a steamed milk foam", R.drawable.cappuccino, true);
insertDrink(db, "Filter", "Highest quality beans roasted and brewed fresh", R.drawable.filter, false);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// updateMyDatabase(db, oldVersion, newVersion);
if (oldVersion < 2){
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC");
}
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onDowngrade(db, oldVersion, newVersion);
}
private void updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion){
/* if (oldVersion < 1){
db.execSQL("CREATE TABLE DRINK (" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"NAME TEXT," +
"DESCRIPTION TEXT," +
"IMAGE_RESOURCE_ID INTEGER);");
insertDrink(db, "Latte", "Expresso and steamed milk", R.drawable.latte, false);
insertDrink(db, "Cappuccino", "Expresso, hot milk, and a steamed milk foam", R.drawable.cappuccino, true);
insertDrink(db, "Filter", "Highest quality beans roasted and brewed fresh", R.drawable.filter, false);
}
if (oldVersion < 2){
db.execSQL("ALTER TABLE DRINK ADD COLUMN FAVORITE NUMERIC");
} */
}
public static void insertDrink(SQLiteDatabase db,
String name,
String description,
int resourceID,
boolean favorite){
ContentValues drinkValues = new ContentValues();
drinkValues.put("NAME", name);
drinkValues.put("DESCRIPTION", description);
drinkValues.put("IMAGE_RESOURCE_ID", resourceID);
drinkValues.put("FAVORITE", favorite);
db.insert("DRINK", null, drinkValues);
}
}
The whole point of using updateMyDatabase(SQLiteDatabase db, int oldVersion, int newVersion) was so that I could manage the changes in the database in one method, as instructed in the book I'm following: Head First Android Development, 2rd Edition. Problem is that the database gets created, but it's empty so the insertDrink() methods aren't working. I think it should be working.
To fix the issue, I tried doing it the conventional way by adding all the code needed to run in onCreate() inside itself directly. This fixed the issue, but when I trace how the first code would run, I really don't think the result should be any different. Can anyone explain?
BTW if you need any additional info or code, I'm very much willing to give whatever.
I'm sorry in advance for my English, it isn't my first language.
In your first code, you're adding the FAVORITE column after trying to insert data to it. In the second code, you create the table with the FAVORITE column first and then insert data.
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
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 "+ ")";
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.
I am trying to add a simple int count which is set to count++ everytime a player wins it will increment by 1. I am trying to add this int count inside my SQLite Database. But I have no Idea how I can do that, the database is in one class, and my int value is in another class, How can I add the int inside the database. I have created a addScores method inside my class:
Database Code:
public class Database {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "number_of_wins";
private static final String DATABASE_NAME = "HIGHSCORES";
private static final String DATABASE_TABLE= "Total_Wins";
private static final int DATABASE_VERSION = 2;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " INTEGER);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Database(Context context) {
ourContext = context;
}
public Database open() {
ourHelper = new DBHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public Cursor getScores() {
return ourDatabase.rawQuery("SELECT * FROM "+DATABASE_TABLE, null); //No Parameter
}
}
Someother Class:
int count =0;
count++;
//Adding HighScore to Database
public void addScore() {
}
How do I add the int count inside my database? I am trying to add it in the column number_of_wins?
You need to insert a value in the database using something like this.
ContentValues values = new ContentValues();
values.put("number_of_wins", counter);
id = ourDatabase.insertOrThrow("Total_Wins", null, values);
Create a method in your database class and add/modify this code, and finally call this new method from 'SomeOther' class.
This is a simple DBHelper that should work for you and get you started, create an instance of this and you should be able to add a score into your database, However I highly recommend you read the tutorial in comment, and really figure out how it works. So from here you should be able to complete all other CRUD operations.
public class DBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME= "HIGHSCORES";
private static final String DATABASE_TABLE = "TotalWins";
// The keys
private static final String KEY_ID = "id";
private static final String KEY_SCORE = "NumberOfWins";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ID + " INTEGER PRIMARY KEY, " +
KEY_SCORE + " INTEGER);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Careful with this!
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
public void addScore(int score) {
// Get a writable database handle
SQLiteDatabase db = getWritableDatabase();
// Put the coun into a ContentValues object, with correct key
ContentValues values = new ContentValues();
values.put(KEY_SCORE, score);
// Inserting Row
db.insert(DATABASE_TABLE, null, values);
// Closing database connection
db.close();
}
}
I assume you have the unique id for the particular count you'd like to increase. In that case, I'd write the following method inside of the Database class and call it when the count should increase.
public void addScore(long id) {
ourDatabase.execSQL(String.format("UPDATE %s SET %s=%s+1 WHERE %s=%d",
DATABASE_TABLE, KEY_NAME, KEY_NAME, KEY_ID, id));
}