I need to know how to join 2 tables together. I am not sure how to do the joining of tables as I'm new to this.
I've created AnniversaryDBAdapter.class where I create 5 tables in one database. I just need to join 2 tables like join buddiesList table and likes table.
Below is the code of the AnniversaryDBAdapter.class
public class AnniversaryDBAdapter
{
private static final String DATABASE_NAME = "AllTables";
private static final int DATABASE_VERSION = 2;
private static final String CREATE_TABLE_BUDDIESLIST = " create table buddiesList(name_id integer primary key autoincrement, name text not null);";
private static final String CREATE_TABLE_LIKES = " create table likes(name_id integer primary key autoincrement,likes text not null);";
private static final String CREATE_TABLE_DISLIKES = " create table dislikes(name_id integer primary key autoincrement, dislikes text not null);";
private static final String CREATE_TABLE_EVENTS = "create table events(date_id integer primary key autoincrement, name_id text not null, date text not null, title_id text not null, starttime text not null, endtime text not null);";
private static final String CREATE_TABLE_TITLE = "create table titles(title_id integer primary key autoincrement, name text not null, image text not null);";
private final Context context;
private static final String TAG = "DBAdapter";
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public AnniversaryDBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_TABLE_BUDDIESLIST);
db.execSQL(CREATE_TABLE_LIKES);
db.execSQL(CREATE_TABLE_EVENTS);
db.execSQL(CREATE_TABLE_TITLE);
}
#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");
onCreate(db);
}
}
public AnniversaryDBAdapter open() throws SQLException
{
this.db = this.DBHelper.getWritableDatabase();
return this;
}
public void close()
{
this.DBHelper.close();
}
}
Assuming we correct your table layout to something like this:
CREATE TABLE buddiesList(
_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL
);
CREATE TABLE likes (
_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
buddy_id INTEGER REFERENCES buddiesList(_id) ON DELETE CASCADE NOT NULL,
likes TEXT NOT NULL
);
Now, in your setup you can create a VIEW of the JOIN between buddiesList and likes, it will act like a normal table when selecting - you just can't update/delete or insert from it (without messing around with TRIGGERs of course).
CREATE VIEW buddyLikes AS
SELECT buddiesList.*, likes._id AS likes_id, likes.likes as likes
FROM buddiesList LEFT JOIN likes ON buddiesList._id=likes.buddy_id;
A View is created using execSQL - just like a table or trigger.
With a view you can select from a join between buddies and likes, returning all buddies and all their likes, like so:
SELECT * from buddyLikes;
which would return something like this:
_id name likes_id likes
1 |Ted |5 |Facebook
1 |Ted |4 |Murder
2 |Ed |1 |Beer
2 |Ed |2 |Cats
2 |Ed |3 |Stock-car racing
3 |Red |6 |Bananarama
BTW: If you want foreign-key support in your database you need to call execSQL
with:
PRAGMA foreign_keys = ON
in your SQLiteOpenHelper#onOpen(SQLiteDatabase db).
Write a query and run with SQLiteDatabase.rawQuery(sql, params).
Related
I am a bit new to SQLite so please bear with me. I am creating a table and trying to access data from it but somehow I am getting this error.
android.database.sqlite.SQLiteException: no such table: table_image (code 1): , while compiling: SELECT image_data FROM table_image WHERE image_name= ' a '
Things that I did after the error came:
1.) Uninstalled the app and installed it again.
2.) Checked for spaces in the table creation code. It looks right to me.
I am not sure why this error is appearing then. Can someone please help me.
Thanks !!
My DatabaseHelper class
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database_name";
// Table Names
public static final String DB_TABLE = "table_image";
// column names
public static final String KEY_NAME = "image_name";
public static final String KEY_IMAGE = "image_data";
// Table create statement
private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + " ("+
KEY_NAME + " TEXT, " +
KEY_IMAGE + " BLOB"+")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating table
db.execSQL(CREATE_TABLE_IMAGE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
// create new table
onCreate(db);
}
}
Adding stuff to db in another class
// Calling addEntry
addEntry(name, img);
// Function to add entry
public void addEntry( String name, byte[] image) throws SQLiteException {
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.KEY_NAME, name);
cv.put(DatabaseHelper.KEY_IMAGE, image);
database.insert(DatabaseHelper.DB_TABLE, null, cv);
}
Then I am tying to get data from it.
SQLiteDatabase db = openOrCreateDatabase(DatabaseHelper.DB_TABLE, MODE_PRIVATE, null);
String selectQuery = "SELECT image_data FROM "+DatabaseHelper.DB_TABLE+" WHERE image_name= ' "+"a"+" ' ";
Cursor cursor = db.rawQuery(selectQuery,null);
byte[] image = cursor.getBlob(1);
openOrCreateDatabase() is not using SQLiteOpenHelper where you have the table creation code.
To get a SQLiteDatabase managed by SQLiteOpenHelper, call e.g. getWritableDatabase() on your helper object.
After fixing that, uninstall the app once more to get rid of the empty database created by openOrCreateDatabase().
Have you tried uninstalling your app and running it again?
error says "no such table: table_image", this situation can occur if you test your app with a DB with lesser number of tables and introduce a table later on.
once you relaunch your app with an additional table an older version of DB is already present and onCreate of your DBHelper will not be called and the new table will not be added in your db.
uninstalling the app will clear any previous instance of DB and onCreate will be called again and you will start with a fresh tables.
I have a simple game where users guess words. Now, I'm thinking using database to store these words to be guessed.
My problem is the tutorials that are available in the web show how to create a database and save user inputs to that database. They create, for example, a DBHelper.java in src, extends it to SQLiteOpenHelper, override the methods. Back to a specific activity, create an instance of DBHelper, then create the db, open the writable, insert user inputs, close db.
But what I think I only need to do is create a database, insert words in it, then make my app retrieve words from this database.
Am i just wondering if what i'm planning to do is right:
1. create a DBHelper.java in src, extends the class to SQLiteOpenHelper
2. define needed Strings like name of database etc.
3. Create a constructor and override the onCreate and onUpgrade methods
4. CREATE A LOADWORDS METHOD this is where i will insert my words to the database.
5. on my main activity(the first screen on my app) I will create an instance of DBHelper and call the onCreate and loadWords method.
// you would want an onCreate and onUpgrade method for best practices,, here's a partial look of what you want...
public class DBManager extends SQLiteOpenHelper
{
static final String TAG = "DBManager";
static final String DB_NAME = "words.db";
static final int DB_VERSION = 1;
static final String TABLE = "words_table";
static final String C_ID = "id";
static final String C_WORD = "word";
public DBManager(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
String sql = "CREATE TABLE " + TABLE + " ("
+ C_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ C_WORD + " TEXT)";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);
}
//**** Code Insert Word and Retrieve Word Methods *****//
//**** End Code Insert Word and Retrieve Word Methods *****//
}
I am trying to insert multiple rows in a sqlite database. I have created a SqliteOpenHelper class and have created a database and a table. Now I need to do is to insert multiple rows in the database.
Say we have five rows to insert at once, what is the best and efficient way to accomplish it.
INSERT INTO `events` (`_id`, `event_name`, `start_date`, `end_date`, `event_city`, `event_state`, `event_pic`, `event_desc`, `wiki_url`, `event_cat`) VALUES
(1, 'Purna Kumbh Fair 2013', '2013-01-27', '2013-03-10', 'Allahabad', 'Uttar Pradesh', 'img/kumbh.jpg', 'Kumbh Fair is a mass Hindu pilgrimage of faith in which Hindus gather at a sacred river for a bath in the river. It is held every third year at one of the four places by rotation: Haridwar, Prayag (Allahabad), Nasik and Ujjain.', 'http://en.wikipedia.org/wiki/Kumbh_Mela', 2),
(2, 'Taj Mahotsav 2013', '2013-02-18', '2013-02-27', 'Agra', 'Uttar Pradesh', 'img/taj-mahotsav.jpg', 'aj Mahotsav is an annual 10 day (from 18 to 27 February) event at Shilpgram in Agra, India. Every year in February tourists flock to Agra for this mega event, just a stone throw from the majestic Taj Mahal. This festival invokes the memories of old Mughal era and nawabi style prevalent in Uttar Pradesh in 18th and 19th centuries.', '', 0),
(3, 'Khajuraho Dance festival', '2013-02-01', '2013-02-08', 'Khajuraho', 'Madhya Pradesh', 'img/Khajuraho-Dance-Festival.jpg', 'One week long festival of classical dances held annually against the spectacular backdrop of the magnificently lit Khajuraho temples in Chhatarpur district of Madhya Pradesh.', '', 0),
(4, 'Holi - Festival of Colors', '2013-03-26', '2013-03-27', 'National', 'Festival', 'img/holi.jpg', 'Holi - The Festival of Colors marks the beginning of ceremonies being the first festival in the Hindu calendar. On this day, people greet each other with colours and celebrate the occasion with much gaiety and excitement.', '', 0),
(5, 'Elephant Festival', '2013-03-26', '2013-03-26', 'Jaipur', 'Rajasthan', 'img/elephant.jpg', 'Jaipur Elephant Festival, perhaps the only festival where Elephants are given prime importance.During the festival, Jaipur comes alive with elephants, dancers and musicians which draw visitors from all over the world.', '', 0),
Try to make a separate class for data base like
public class databasehandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 5;
// Database Name
private static final String DATABASE_NAME = "atabase";
// Contacts table name
private static final String TABLE_Name = "task";
// Contacts Table Columns names
private static final String event_name= "event_name";
private static final String start_date= "start_date";
private static final String KEYID="id";
private static final String end_date= "end_date";
private static final String event_pic= "event_pic";
private static final String event_desc= "event_desc";
private static final String wiki_url= "wiki_url";
private static final String event_cat= "event_cat";
public databasehandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATETABLE = "CREATE TABLE " + TABLE+ "("
+ KEYID + " INTEGER PRIMARY KEY AUTOINCREMENT," + event_name+ " TEXT,"
+ start_date+ " TEXT," + end_date+" TEXT "+ ..... so on ")";
db.execSQL(CREATE_TASK_TABLE);
db.execSQL(CREATETABLE );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// Create tables again
onCreate(db);
}
void adddata(Classname Object) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(event_name, Object.getevent_name());
values.put(start_date, Object.gestart_date());
values.put(TASK_ID, Object.getTASK_ID());
insert all values....
// Inserting Row
db.insert(Table_tasknotification, null, values);
// Closing database connection
}
}
and now Classname.java
public class Classname {
//private variables name like
String event_name;
.... so on
// Empty constructor
public Classname (){
}
// constructor
public Classname (String event_name, String start_date,String end_date.....){
this.event_name= event_name;
this.start_date=start_date;
this.end_date=end_date;
}
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
and all the get and set methods....
}
and in your main class:-
databasehandler handler=new databasehandler (context);
handler.adddata(new Classname(event_name, start_date,end_date....));
try this it will helo you :)
and also check this link http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
I made two classes, the main class that extends Activity and the Database class that holds the database and it's methods. parts of the code from the database class are shown below.
the SQLiteOpenHelper class is a nested class inside the database class. I took it from an example I found on the internet. inside of this nested class is the method,
db.execSQL(SCRIPT_CREATE_DATABASE);
how do I create a new database? If I instantiate the Database class from the Main class like this:
Database db = new Database(this);
does that instantiation automatically instantiate the nested SQLiteOpenHelper class too? so i don't have to explicitly do that.
however for this example of how to create a database, i am confused. if every time I instantiate a new instance calling the addNewRow() method like this:
public void addNewRow(String label, int price){
Database db = new Database(context);
db.openToWrite();
db.insertNewRow(checkBoxStatus, label, price);
db.close();
}
then a new database is created on the "new Database(context)" call, and next I add the info to enter into the columns. and finally call db.close(), however every time i call the addNewRow method shown above, it will instantiate a new database and that also instantiates SQLiteOpenhelper class so a new database is created. that means the last database has been overwritten, and my last row added has been lost, is this correct?
how do i use this Database class to create a Database only once and then read and write things from it with multiple calls like this?
Database db = new Database(context);
db.openToWrite(); or db.openToRead();
// read or update or create new row in database
db.close();
the database class:
public class Database {
public static final String MYDATABASE_NAME = "my_database";
public static final String MYDATABASE_TABLE = "my_table";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_CHECKBOX_STATUS = "check_box_status";
public static final String KEY_CHECKBOX_LABEL = "check_box_label";
public static final String KEY_PRICE = "price";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"CREATE TABLE " + MYDATABASE_TABLE + " (" + "ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"KEY_CHECKBOX_STATUS INTEGER, " + "KEY_CHECKBOX_LABEL TEXT, " + " KEY_PRICE INTEGER" + ");";
SQLiteDatabase sqLiteDatabase;
SQLiteHelper sqLiteHelper;
Context context;
public Database(Context c){
context = c;
}
// after this all the rest of the methods for get and set of database values
code for the SQLiteOpenHelper class, nested inside of the Database Class:
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Yes, every time you instantiate a Database class a SQLiteHelper is instantiate. But the SQLiteHelper onCreate is only called if the database does not exist. You can test this by adding a new column to one of the table and then try to insert a row having value in this column then your app will crash. The error would be "no such column". You then need to clear your data or change the version of your database or uninstall your app to have your change table to be recreated.
Whenever you want to just open your database, you need to use this:
myDatabase = myOpenHelper.getWritableDatabase();
This won't create a new database. It would just return the instance of existing database on which you can do Read/Write operations.
Refer this to get a firm idea of how creating database works in Sqlite. Hope it helps.
private static final String SCRIPT_CREATE_DATABASE =
"CREATE TABLE IF NOT EXISTS " + MYDATABASE_TABLE + " (" + "ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"KEY_CHECKBOX_STATUS INTEGER, " + "KEY_CHECKBOX_LABEL TEXT, " + " KEY_PRICE INTEGER" + ");";
Use this query while creating the table. It will create the Table if it doesn't exist.
I try to drop table programmatically nothing error show in logcat, but there has no any result :
Here my Database Helper class :
public class database1 extends SQLiteOpenHelper
{
private static final String DB_Name="database";
private static final int DB_Version=1;
private static final String tbl_arrival1="arrival1";
private static final String STRING_CREATE1 = "CREATE TABLE IF NOT EXISTS "+tbl_arrival1
+" (_f_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+"f_date TEXT,"
+"o_rder NUMERIC,"
+"rem_com TEXT);";
public database1 (Context ctx)
{
super(ctx,DB_Name,null,DB_Version);
}
#Override
public void onCreate(SQLiteDatabase database) {
databaseQuery.onCreate(database);
}
public static class databaseQuery
{
public static void onCreate(SQLiteDatabase database)
{
database.execSQL("DROP TABLE IF EXISTS "+tbl_arrival1);
database.execSQL(STRING_CREATE1);
}
}
}
I use this database helper in content provider :
database1 DBHelper ;
public Uri insert(Uri uri, ContentValues values)
{
long row_id;
SQLiteDatabase sqlDB = DBHelper.getWritableDatabase();
row_id=sqlDB.insert(tbl_arrival1, null, values);
if(row_id>0)
{
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, row_id);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Failed to insert into "+uri);
}
The problem is that, the query drop table, is not working!
All suggestion and answer would be highly appreciated...
thanks
I know I'm bit late but this question was relevant for me. In my case I tried to drop many tables in single a query, i. e.
drop table if exists table_name1;
drop table if exists table_name2;
drop table if exists table_name3;
so android's implementation of execSQL() executes only single sql statement
onCreate will work only once at time of creation once the database is created you should make use of onUpgrade() to drop table if any changes has been made to old version
EDIT
http://www.vogella.com/articles/AndroidSQLite/article.html
Your code seems to be fine. You are calling DROP TABLE and then creating again subsequently. How you checked the DROP TABLE is not working?