SQLiteDatabase add only if not already there - java

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).

Related

Android SQlite update just not working, without error

I wrote some codes using this example to save and update 2 long values in SQlite. I can create new row however I can't update it. I try everything which I can but I couldn't update a row and there is no error just not update row. I am using this code to update a row:
db.updateContact(new Contact(consumed, total));
which both consumed and total are long values. I can't see any error however still I couldn't success to update a row. My constructor and databesehandler codes are below:
Contaxt.java
public class Contact {
// private variables
int _id;
double _name;
double _phone_number;
// Empty constructor
public Contact() {
}
// constructor
public Contact(int id, double name, double _phone_number) {
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
// constructor
public Contact(double name, double _phone_number) {
this._name = name;
this._phone_number = _phone_number;
}
// getting ID
public int getID() {
return this._id;
}
// setting id
public void setID(int id) {
this._id = id;
}
// getting name
public double getName() {
return this._name;
}
// setting name
public void setName(double name) {
this._name = name;
}
// getting phone number
public double getPhoneNumber() {
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(double phone_number) {
this._phone_number = phone_number;
}
}
DatabeseHandler.java
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 = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," + KEY_PH_NO + " 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_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getInt(0), cursor.getDouble(1), cursor.getDouble(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(cursor.getInt(0));
contact.setName(cursor.getDouble(1));
contact.setPhoneNumber(cursor.getDouble(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Thanks in advance.
You did not set the id in Contact object.
db.updateContact(new Contact(consumed, total));
In updateContact method : following update query is used :
db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", new String[] { String.valueOf(contact.getID()) });
contact.getID() returns 0, and no id matched with id 0 and nothing updated.
You should pass correct id also

sqllite db android not adding user properly

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().

Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it

I am having difficulty inserting image in my sqlite database. There are no syntax errors in my code. After I run it, the app automatically force stops. The logcat shows:
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 3 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at com.synergy88studios.catalogapp.DatabaseHandler.getAllItemsInList(DatabaseHandler.java:86)
at com.synergy88studios.catalogapp.MainActivity.onCreate(MainActivity.java:56)
Here is my method in getAllItemsInList in my DatabaseHandler.class
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
In my MainActivity, I simply call the method.
items = db.getAllItemsInList();
EDIT
DatabaseHandler.class
public class DatabaseHandler extends SQLiteOpenHelper{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "CatalogItems";
public static final String TABLE_ITEMS = "Items";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_DESC = "description";
public static final String KEY_IMAGE = "image";
public static final String[] ALL_KEYS = new String[] {KEY_ID, KEY_NAME, KEY_DESC};
//private static final String KEY_IMAGE = "image";
public DatabaseHandler(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "( "
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_DESC + " TEXT, " + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_ITEMS);
onCreate(db);
}
public void addItems(Item item){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
db.insert(TABLE_ITEMS, null ,values);
db.close();
}
Item getItem(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_NAME, KEY_DESC , KEY_IMAGE}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getBlob(3));
return item;
}
void deleteAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM "+ TABLE_ITEMS);
}
public List<Item> getAllItemsInList() {
List<Item> itemList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.set_id(Integer.parseInt(cursor.getString(0)));
item.set_name(cursor.getString(1));
item.set_description(cursor.getString(2));
item.set_image(cursor.getBlob(3));
// Adding contact to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
public Cursor getAllRows() {
SQLiteDatabase db = this.getWritableDatabase();
String where = null;
Cursor c = db.query(true, TABLE_ITEMS, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public int getItemsCount(){
String countQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();
}
public int updateItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.get_name());
values.put(KEY_DESC, item.get_description());
values.put(KEY_IMAGE, item.get_image());
// updating row
return db.update(TABLE_ITEMS, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
}
public void deleteContact(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(item.get_id()) });
db.close();
}
}
I hope someone can explain to me what happens. I can post my other classes for reference.
Don't store large data in an Android sqlite table. In particular, the CursorWindow only supports row data up to 2MB. If your row is larger, you can't access it.
Instead, store your blobs as files in the filesystem and store just the path in database.

No data retrieved if open sqlite more than once

When I add data into sqlite and open it for the first time, the data inside will be displayed. However, if I try opening it again nothing will show up even though there is data inside. May I know what is the problem?
Class that performs the activity:
public class Watchlist extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DatabaseHandler.TABLE_ITEM;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from sqlite");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
DatabaseHandler db = new DatabaseHandler(this.getApplicationContext());
newDB = db.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT * FROM " + tableName, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String pid = c.getString(c.getColumnIndex("id"));
String name = c.getString(c.getColumnIndex("name"));
String price = c.getString(c.getColumnIndex("price"));
String date = c.getString(c.getColumnIndex("created_at"));
Log.d("pid",pid);
results.add("Name: " + name + "\n Price: " + price + "\n Date posted: " + date);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
Database handler:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 2;
// Database Name
private static final String DATABASE_NAME = "itemManager";
// table name
public static final String TABLE_ITEM = "item";
// Item Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PRICE = "price";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_ITEM + "("
+ KEY_ID + " INTEGER PRIMARY KEY autoincrement,"
+ KEY_NAME + " TEXT, "
+ KEY_PRICE + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_ITEM_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_ITEM);
// Create tables again
onCreate(db);
}
/**
* Storing item details in database
* */
public void addItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getName()); // item name
values.put(KEY_PRICE, item.getPrice()); // item price
values.put(KEY_CREATED_AT, item.getDate()); // Created At
// Inserting Row
db.insert(TABLE_ITEM, null, values);
db.close(); // Closing database connection
}
/**
* Getting item data from database
* */
public List<Items> getAllItems(){
List<Items> itemList = new ArrayList<Items>();
String selectQuery = "SELECT * FROM " + TABLE_ITEM;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
if (cursor.moveToFirst()) {
do {
Items item = new Items();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setPrice(cursor.getString(2));
item.setDate(cursor.getString(2));
// Adding item to list
itemList.add(item);
} while (cursor.moveToNext());
}
// return item list
return itemList;
}
/**
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_ITEM;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
// Updating item
public int updateItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, item.getName());
values.put(KEY_PRICE, item.getPrice());
values.put(KEY_CREATED_AT, item.getDate());
// updating row
return db.update(TABLE_ITEM, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
}
// Deleting item
public void deleteItem(Items item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEM, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
db.close();
}
}
Well, don't you delete all the records before closing the database?
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
That would explain that behaviour.

Delete an Item on Listview but this doesnt deleted from SQLite

I use this method to delete an Item on my SQLite database:
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
And this to my ListView:
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
The problem is that when i delete an item on my listview the item disappears but when I re-open it the item is still there, because this doesn't remove from the database.
I 'll try to explain this with images :
This means that there is some problem with the deleting from the db. Just replace 2nd line in your deleteItem() with
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item}
Log.d("deletedItem", x);
Here x would be the number of rows deleted. Check the value of x after deleting, it should be greater than 0 if the deletion was successful. If it is not then that means the query is wrong and we would need the database schema for correcting it. From your ListView implementation code, its clear that your nameString itself is wrong. You are adding the whole Item in the arraylist and passing to the adapter. And when you fetch the item in the onItemClick dialog, you are using this code
String nameString = (arg0
.getItemAtPosition(arg2))
.toString();
Here arg0.getItemAtPosition(arg2) would return an Item object. You will have to do something like this.
Item tempItem=(Item)items.get(arg2);
String nameString=tempItem.getName();
where getName() would return the name of the item.
The change that I did:
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
Log.d("itemtodelete", nameString);
db.deleteItem(nameString);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
to
public void onClick(DialogInterface dialog, int which) {
String nameString = (arg0.getItemAtPosition(arg2)).toString();
String nameStringData = nameString.substring(6,
nameString.indexOf("Priority Level:") - 1);
Log.d("itemtodelete", nameStringData);
db.deleteItem(nameStringData);
magicAdapter.remove(nameString);
magicAdapter.notifyDataSetChanged();
If you have a better suggestion please post an answer.
Yes this is the problem.
deletedItem = 0 on logCat so that's my database:
public class DatabaseHolder extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "ItemsList";
private static final String TABLE_NAME = "Items";
private static final String ITEMS_COLUMN = "items_name";
private static final String PRIORITY_COLUMN = "Priority";
private static final String ID_COLUMN = "Items";
private static int DATABASE_VERSION = 1;
private static String QUERY = "CREATE TABLE " + TABLE_NAME + "("
+ ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ITEMS_COLUMN
+ " TEXT NOT NULL, " + PRIORITY_COLUMN + " TEXT NOT NULL);";
public DatabaseHolder(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
this.onCreate(db);
}
// Sharer!
public void addItem(String item_name, String priority) {
if (!duplicate(item_name)) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ITEMS_COLUMN, item_name);
values.put(PRIORITY_COLUMN, priority);
db.beginTransaction();
db.insert(TABLE_NAME, null, values);
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}
public boolean duplicate(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_NAME, null, ITEMS_COLUMN + " =?",
new String[] { name }, null, null, null);
int temp = c.getCount();
c.close();
db.close();
if (temp > 0)
return true;
else
return false;
}
public ArrayList<Item> getAllItems() {
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Item> item = new ArrayList<Item>();
db.beginTransaction();
Cursor cursor = db.query(TABLE_NAME, new String[] { this.ITEMS_COLUMN,
this.PRIORITY_COLUMN }, null, null, null, null, PRIORITY_COLUMN
+ " DESC");
while (cursor.moveToNext()) {
Item itemTemp = new Item(cursor.getString(cursor
.getColumnIndexOrThrow(ITEMS_COLUMN)), new Level(
Integer.parseInt(cursor.getString(cursor
.getColumnIndexOrThrow(PRIORITY_COLUMN)))));
item.add(itemTemp);
}
cursor.close();
db.endTransaction();
db.close();
return item;
}
public void deleteItem(String item){
SQLiteDatabase db = this.getWritableDatabase();
int x = db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
Log.d("deletedItem", String.valueOf(x) );
db.beginTransaction();
db.delete(TABLE_NAME, ITEMS_COLUMN + " =?", new String[] {item});
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
}

Categories