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().
Related
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
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).
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.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hi I want to delete a row from the listview from an another activity. I tried a lot but didn't succeed. here is my code. I want to delete item from the listview through case.id.id_favorite2
case R.id.id_favorit:
// Add it to the DB and re-draw the ListView
myDb.insertRow("Atherosclerosis", 0, "");
Toast.makeText(getApplicationContext(), "Item Added to favorite list!", Toast.LENGTH_SHORT).show();
case R.id.id_favorit2:
myDb.deleteRow(??);
Toast.makeText(getApplicationContext(), "Item deleted from favorite list!", Toast.LENGTH_SHORT).show();
here is my DBAdapter. database code for delete.
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_STUDENTNUM = "studentnum";
public static final String KEY_FAVCOLOUR = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_STUDENTNUM = 2;
public static final int COL_FAVCOLOUR = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_STUDENTNUM, KEY_FAVCOLOUR};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_STUDENTNUM + " integer not null, "
+ KEY_FAVCOLOUR + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
#SuppressLint("NewApi")
public long insertRow(String name, int studentNum, String favColour) {
Cursor c= db.query(true, DATABASE_TABLE, ALL_KEYS, KEY_NAME + "='" + name +"'", null, null, null, null, null, null);
if(c.getCount()>0){
return -1;
}
c.close();
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_STUDENTNUM, studentNum);
initialValues.put(KEY_FAVCOLOUR, favColour);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
#SuppressLint("NewApi")
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, KEY_ROWID + " DESC", null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_STUDENTNUM, studentNum);
newValues.put(KEY_FAVCOLOUR, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
finally my other activity where the listview is populated from the database.
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_STUDENTNUM};
int[] toViewIDs = new int[]
{R.id.item_name};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.item_layout, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.favlistView1);
myList.setAdapter(myCursorAdapter);
}
private void registerListClickCallback() {
ListView myList = (ListView) findViewById(R.id.favlistView1);
The KEY_ROWID value is depended on the order you enter the rows in the database,
It increases on every row you enter, so if you search your database by KEY_ROWID + "=" + rowed you must know the order of your rows or the specific value,
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();
}
}