Im struggling with a bit of my code for my database, I have managed to access the id number of the item i click however i cannot access any more of the data? How can i do this?
For example now i have my id number i want to display all of that data on that row in a seperate window but i cant seem to pull the data with the cursor
String itemselect = String.valueOf(spinner.getSelectedItem());
Toast.makeText(Developer.this, itemselect, Toast.LENGTH_LONG).show();
final Cursor cursor = mydb.getAllRows(itemselect);
startManagingCursor(cursor);
String[] fromfieldnames = new String[]{
DatabaseHelper.COL_1, DatabaseHelper.COL_2, DatabaseHelper.COL_3,
DatabaseHelper.COL_4, DatabaseHelper.COL_5, DatabaseHelper.COL_6 };
int[] toviewids = new int[]{R.id.textone, R.id.texttwo, R.id.textthree, R.id.textfour, R.id.textfive, R.id.textsix};
final SimpleCursorAdapter mycursoradapter = new SimpleCursorAdapter(this, R.layout.listtext, cursor, fromfieldnames, toviewids);
listView.setAdapter(mycursoradapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Long string = mycursoradapter.getItemId(position);
Toast.makeText(Developer.this, string.toString(),Toast.LENGTH_LONG).show();
return true;
}
});
There are no errors in this code I just need to try and add this extra functionality
Thanks in advance M.
The data is stored in your Cursor at the row position position in onItemLongClick. Use the moveToPosition() method on cursor, and retrieve the values:
String one, two, three;
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
cursor.moveToPosition(position);
one = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_1));
two = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_2));
// Etc...
}
};
use the cursor in the following way:
public Cursor getRowByID(int ID) {
SQLiteDatabase db = this.getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String [] sqlSelect = {"id, col_1, col_2, col_3"};
String sqlTables = "your_table";
String filter = "id= "+ID;
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, filter,null, null,
null, null, null);
c.moveToFirst();
return c;
}
public Cursor Retrive_SubCategory1(String id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("select "
+ "column_Name1 , "+"column_name2 " + " from "
+"table_name " + " where "
+ "column_name " + "='" + id+ "'",
null);
return cursor;
}
Related
Basically what I'm trying to do is to display data using ExpandableListView from my SQLite table, I was able to get data, but I'm getting this error 'java.lang.IllegalStateException: trying to requery an already closed cursor android.database.sqlite.SQLiteCursor#cc36823' when I'm trying to reopen my app from onPause state. I tried to search for the solution, and I think the only possible way to solve my problem is to use CursorLoader, but I don't know how can I use it into my code.
My Code >>
//onPause
#Override
protected void onPause() {
super.onPause();
SelectedListView.collapseGroup(lastExpandedPosition);
Cursor currentCursor = ((MyExpandableListAdapter)mAdapter).getCursor();
stopManagingCursor(currentCursor);
stopManagingCursor(childCursor);
}
//onRestart
#Override
protected void onRestart(){
super.onRestart();
Cursor cursor= dataBaseHelper.getSelectedParentMVPDate(reformatMVPDate());
mAdapter.changeCursor(cursor);
}
//ExpandableListView Data
private void fillData(){
String COA = String.format(dataBaseHelper.getCount(VisitDate));
if(COA.equals(0)) {
mGroupsCursor = dataBaseHelper.getSelectedParentMVPDate(reformatMVPDate());
startManagingCursor(mGroupsCursor);
mGroupsCursor.moveToFirst();
ExpandableListView SelectedListView = (ExpandableListView) findViewById(R.id.MVPListitem);
mAdapter = new MyExpandableListAdapter(mGroupsCursor, this,
R.layout.mvp_list_parent,
R.layout.mvp_list_child,
new String[]{DataBaseHelper.MVP_INDUSTRY_TYPE},
new int[]{R.id.txtMVPParent},
new String[]{DataBaseHelper.MVP_BRCH_CODE_NAME, DataBaseHelper.MVP_BRCH_ADDRESS, DataBaseHelper.MVP_ID},
new int[]{R.id.txtviewBrnchCodeName, R.id.txtviewBrchAddr, R.id.txtmvpID});
SelectedListView.setAdapter(mAdapter);
}
else{
mGroupsCursor = dataBaseHelper.getSelectedParentMVPDate(reformatMVPDate());
startManagingCursor(mGroupsCursor);
mGroupsCursor.moveToFirst();
ExpandableListView SelectedListView = (ExpandableListView) findViewById(R.id.MVPListitem);
mAdapter = new MyExpandableListAdapter(mGroupsCursor, this,
R.layout.mvp_list_parent,
R.layout.mvp_list_child,
new String[]{DataBaseHelper.MVP_INDUSTRY_TYPE},
new int[]{R.id.txtMVPParent},
new String[]{DataBaseHelper.MVP_BRCH_CODE_NAME, DataBaseHelper.MVP_BRCH_ADDRESS, DataBaseHelper.MVP_ID},
new int[]{R.id.txtviewBrnchCodeName, R.id.txtviewBrchAddr, R.id.txtmvpID});
SelectedListView.setAdapter(mAdapter);
}
}
public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {
public MyExpandableListAdapter(Cursor cursor, Context context,int groupLayout,
int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom,
int[] childrenTo) {
super(context, cursor, groupLayout, groupFrom, groupTo,
childLayout, childrenFrom, childrenTo);
}
#SuppressLint("Range")
#Override
protected Cursor getChildrenCursor(Cursor cursor) {
childCursor = (Cursor) dataBaseHelper.getSelectedChildMVPDate(cursor.getString(cursor.getColumnIndex(DataBaseHelper.MVP_INDUSTRY_TYPE)),reformatMVPDate());
startManagingCursor(childCursor);
childCursor.moveToFirst();
return childCursor;
}
public View getChildView(final int groupPosition,
final int childPosition, boolean isLastChild, View convertView,
ViewGroup parent) {
View rowView = super.getChildView(groupPosition, childPosition,
isLastChild, convertView, parent);
removeMVP = (Button) rowView.findViewById(R.id.btnRemove);
TextView txtBCN = (TextView) rowView.findViewById(R.id.txtviewBrnchCodeName);
TextView txtBA = (TextView) rowView.findViewById(R.id.txtviewBrchAddr);
TextView txtmvpID = (TextView) rowView.findViewById(R.id.txtmvpID);
});
return rowView;
}
}
//Query for Parent/Group
public Cursor getSelectedParentMVPDate(String txtDate){
SQLiteDatabase db = this.getWritableDatabase();
String dropTMPMVPTBL = "DROP TABLE IF EXISTS TMP_MVP_TBL";
db.execSQL(dropTMPMVPTBL);
String q = "CREATE TEMP TABLE IF NOT EXISTS TMP_MVP_tbl AS SELECT a.SCHEDULED_DATE,b.recID,b.BRCH_CODE_NAME,c.BrchAddr,b.INDUSTRY_TYPE,b._id " +
"FROM MVP_a a " +
"LEFT join MVP_tbl b on a.MVP_ID = b.MVP_ID " +
"LEFT JOIN taggedList_tbl c on b.BRCH_CODE_NAME = c.BrchCodeName WHERE b.AppType = 'PLANNED' AND c.areaCode = (SELECT areaCode FROM USER_INFO)";
db.execSQL(q);
String query = "Select DISTINCT INDUSTRY_TYPE, _id from TMP_MVP_tbl WHERE " +SCHEDULED_DATE+ " = '"+txtDate+"' AND recID IS NOT NULL";
return db.rawQuery(query, null);
}
//Query for Child
public Cursor getSelectedChildMVPDate(String Industry, String txtDate){
SQLiteDatabase db = this.getWritableDatabase();
String dropTMPMVPTBL = "DROP TABLE IF EXISTS TMP_MVP_TBL";
db.execSQL(dropTMPMVPTBL);
String query = "CREATE TEMP TABLE IF NOT EXISTS TMP_MVP_tbl AS SELECT a.*,b.recID,b.BRCH_CODE_NAME,c.BrchAddr,b.INDUSTRY_TYPE,b._id " +
"FROM MVP_a a LEFT join MVP_tbl b on a.MVP_ID = b.MVP_ID LEFT JOIN taggedList_tbl c on b.BRCH_CODE_NAME = c.BrchCodeName " +
"WHERE b.AppType = 'PLANNED' AND c.areaCode = (SELECT areaCode FROM USER_INFO) AND " +MVP_INDUSTRY_TYPE+ " = '" + Industry + "' AND " +SCHEDULED_DATE+ " = '"+txtDate+"' ";
db.execSQL(query);
String q = "SELECT * FROM TMP_MVP_tbl";
return db.rawQuery(q, null);
}
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.
hi I want to remove(delete) an item from listview from a second activity which I previously saved from another activity. I found similar question on deleting row from database but I think there is a little bit change in my database and the one's given in other questions and answers. here is my code.
the activity from where I am saving and deleting the row. here I want to delete the row from listview.
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();
favClicked=true;
editor.putBoolean("menu_item", favClicked);
editor.commit();
invalidateOptionsMenu();
return true;
case R.id.id_favorit2:
myDb.deleteRow(??);
Toast.makeText(getApplicationContext(), "Item deleted from favorite list!", Toast.LENGTH_SHORT).show();
favClicked=false;
editor.putBoolean("menu_item", favClicked);
editor.commit();
invalidateOptionsMenu();
return super.onOptionsItemSelected(item);
}
return true;
}
here is my database
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);
}
}
}
and now my listview another activity
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// 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);
//This code is for to delete the single item from the listview of favorite list
myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, final long arg3) {
Cursor cursor = myDb.getRow(arg3);
if (cursor.moveToFirst()) {
new AlertDialog.Builder(FavoriteDiseases.this)
.setTitle("Delete Item")
.setMessage("Do you want to delete this disease?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
myDb.deleteRow(arg3);
populateListViewFromDB();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
return true;
}
});
If you use LoaderManager and CursorLoader to load your data from the database, it will update the cursor, and you can update your ListView automatically when the database changes. Here is a link: Loaders
Hi Stackoverflow members i created an app where user can add favorite items to the favorite list. but the problem i am facing is that when i click on add to favorite button, the item adds to the bottom of the list and not on the top.
Second when i click the same item add to favorite item many time, this add the item multiple time and not just only one time. how can i add it to the list just only one time and not multiple time.
here is my code for activity and database.
My DBAdapter.class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
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.
public long insertRow(String name, int studentNum, String favColour) {
/*
* 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.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, 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);
}
}
}
My favorite list activity..
DBAdapter myDb;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favoritediseases);
openDB();
populateListViewFromDB();
registerListClickCallback();
// this code is used for the action bar color change//
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#6B8E23")));
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
/*
* UI Button Callbacks
*/
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// 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);
//This code is for to delete the single item from the listview of favorite list
myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, final long arg3) {
Cursor cursor = myDb.getRow(arg3);
if (cursor.moveToFirst()) {
new AlertDialog.Builder(FavoriteDiseases.this)
.setTitle("Delete Item")
.setMessage("Do you want to delete this disease?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
myDb.deleteRow(arg3);
populateListViewFromDB();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
return true;
}
});
//this is the code used from starting activity from the favorite list database.
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
String name = cursor.getString(DBAdapter.COL_NAME);
if (name.equals("Atherosclerosis")){
startActivity(new Intent(FavoriteDiseases.this,Atherosclerosis.class));
}else if
(name.equals("Coronary Heart Disease")){
startActivity(new Intent(FavoriteDiseases.this,CoronaryHeartDisease.class));
}else if (name.equals("Stable Angina")){
startActivity(new Intent(FavoriteDiseases.this,StableAngina.class));
}else if (name.equals("Acute Coronary Syndrome")){
startActivity(new Intent(FavoriteDiseases.this,AcuteCoronarySyndrome.class));
}else if (name.equals("Myocardial Infarction")){
startActivity(new Intent(FavoriteDiseases.this,MyocardialInfarction.class));
}else if (name.equals("Unstable Angina")){
startActivity(new Intent(FavoriteDiseases.this,UnstableAngina.class));
}else if (name.equals("Acute Heart Failure")){
startActivity(new Intent(FavoriteDiseases.this,AcuteHeartFailure.class));
}
}
cursor.close();
updateItemForId(idInDB);
}
});}
private void updateItemForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
favColour += "!";
myDb.updateRow(idInDB, name, studentNum, favColour);
}
cursor.close();
populateListViewFromDB();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.favorite_diseases, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_clear:
new AlertDialog.Builder(this)
.setTitle("Delete List")
.setMessage("Do you want to clear all?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
myDb.deleteAll();
populateListViewFromDB();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
return true;
}
return true;
}}
the final code from where i adding to the list
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();
favClicked=true;
invalidateOptionsMenu();
return true;
Seems like you just want to get your results from the DB in reverse order. Changing the function that retrieves them to ORDER BY your rowid in descending order will do the trick:
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, KEY_ROWID + " DESC", null);
if (c != null) {
c.moveToFirst();
}
return c;
}
Regarding your second question, you should check if the favorite exists before inserting it. The question is how you define your uniqueness. For example, if you don't want two "favorites" with the same name, you'll want to add a check in your insert function:
// Add a new set of values to the database, unless the name already exists.
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);
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);
}
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();
}
}