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
Related
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 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.
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 getting a "Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference"
public class userDB extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserInfo";
// Assignment table name
private static final String TABLE_USERINFO = "user";
// Assignment Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TOKEN = "token";
Context context;
public userDB (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_USERINFO + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TOKEN + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERINFO);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding user
public void addUser(authToken user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TOKEN, user.getToken());
// Inserting Row
db.insert(TABLE_USERINFO, null, values);
Toast.makeText(context, "Inserted" + values.toString() , Toast.LENGTH_LONG).show();
db.close(); // Closing database connection
}
// Getting All Users
public List<authToken> getAllUsers() {
List<authToken> userList = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_USERINFO;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
authToken user = new authToken();
user.setToken(cursor.getString(1));
// Adding user to list
userList.add(user);
} while (cursor.moveToNext());
}
// return user list
return userList;
}
// Update User
public int updateUser(authToken user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TOKEN, user.getToken());
// updating row
return db.update(TABLE_USERINFO, values, KEY_ID + " = ?",
new String[] { String.valueOf(user.getUser().getId())});
}
// Delete user
public void deleteUser(authToken user) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_USERINFO, KEY_ID + " = ?",
new String[] { String.valueOf(user.getToken()) });
db.close();
}
// Getting User Count
public int getUserCount() {
String countQuery = "SELECT * FROM " + TABLE_USERINFO;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
I am reading the info in like this: (and userinfo.getToken) is spitting out the token, its something with the sql not adding in db properly.
userDB db = new userDB(getApplicationContext());
dbs = db.getWritableDatabase();
//db.onUpgrade(dbs, 1, 1);
// Inserting Contacts
Log.d("Insert: ", "Inserting .." +
userInfo.getToken());
db.addUser(new authToken(userInfo.getToken()));
// Reading all
Log.d("Reading: ", "Reading all contacts..");
List<authToken> contacts = db.getAllUsers();
for (authToken cn : contacts) {
String log = "Token: " + cn.getToken();
// Writing Contacts to log
Log.d("Name: ", log);
}
Where are you setting context? I think the problem is with the toast message.
You should set context in your constructor method:
Context context;
public userDB (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
This may not be related but in the method getUserCount(), cursor.getCount() should be called before cursor.close().
I'm implementing a "add to favorite" function. Where the user should be able to add data to a database.
The DatabaseHandler is working and I've created a class to handle get/set methods.
I can easily add data to the database, but I can't quite figure out how to check if a specific id is already present and thereby not adding a duplicate to the database.
Here's my DatabaseHandler:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "favoriteMovies";
// DataFavorites table name
private static final String TABLE_NAME = "movies";
// DataFavorites Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_URL = "url";
private static final String KEY_RELEASEDATE = "releaseDate";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DATAFAVORITES_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_URL + " TEXT,"+ KEY_RELEASEDATE + " TEXT" + ")";
db.execSQL(CREATE_DATAFAVORITES_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Create tables again
onCreate(db);
}
// Adding new movie
public void addMovie(DataFavorites movie) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, movie.getId()); // movie id
values.put(KEY_TITLE, movie.getTitle()); // movie title
values.put(KEY_URL, movie.getUrl()); // movie url (poster)
values.put(KEY_RELEASEDATE, movie.getReleaseDate()); // movie url (poster)
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
// Getting single movie
public DataFavorites getMovie(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ID,
KEY_TITLE, KEY_URL, KEY_RELEASEDATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
DataFavorites movie = new DataFavorites(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return movie
return movie;
}
// Getting All movie
public List<DataFavorites> getAllMovie() {
List<DataFavorites> movieList = new ArrayList<DataFavorites>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
DataFavorites dataFavorites = new DataFavorites();
dataFavorites.setId(Integer.parseInt(cursor.getString(0)));
dataFavorites.setTitle(cursor.getString(1));
dataFavorites.setUrl(cursor.getString(2));
dataFavorites.setReleaseDate(cursor.getString(3));
// Adding movie to list
movieList.add(dataFavorites);
} while (cursor.moveToNext());
}
// return movie list
return movieList;
}
// Getting movie Count
public int getMoviesCount(){
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single movie
public int updateMovie(DataFavorites movie) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, movie.getId());
values.put(KEY_TITLE, movie.getTitle());
values.put(KEY_URL, movie.getUrl());
values.put(KEY_RELEASEDATE, movie.getReleaseDate());
// updating row
return db.update(TABLE_NAME, values, KEY_ID + " = ?",
new String[] { String.valueOf(movie.getId()) });
}
// Deleting single movie
public void deleteMovie(DataFavorites movie) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",
new String[] { String.valueOf(movie.getId()) });
db.close();
}
And here I want to add data if id doesn't already exist:
public void AddToFavorites(MenuItem item) {
DatabaseHandler db = new DatabaseHandler(this);
/* if ( id is not there ){
// Inserting movie
Log.d("Insert: ", "Inserting movie..");
db.addMovie(new DataFavorites(Integer.parseInt(Id), Title, Poster, Release));
} */
}
Add a UNIQUE index to the Table column to prevent duplicate entries. Also note that it will throw an Exception if duplicate is inserted, so don't forget to handle that
you should use :
db.execSql("INSERT OR IGNORE INTO movies (columns names) VALUES (your values)");
or
db.execSql("INSERT OR REPLACE INTO movies (columns names) VALUES (your values)");
to insert the values, if they are already in the table they will not be added(first method) or they will be replaced(second method).