Store SQLite query result in a String array - android

How can I save a query result in a String array?
The query is simple, it's got only one column i.e.:
SELECT NAME FROM MYTABLE
What I want is to store the ids in a String array so I can show them as clickable items in a ListView

Try this
String selectQuery = "SELECT * FROM table";
try {
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<String> ids = new ArrayList<>();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(KEY_ID));
ids.add(id);
} while (cursor.moveToNext());
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}

Assuming you've already executed your query against a SQLiteDatabase object, and received a Cursor in return, you can iterate through the cursor and save the value of each row to a String[] array like so:
String[] names;
if (cursor.moveToFirst()) {
names = new String[cursor.getCount()];
int colIndex = cursor.getColumnIndex("NAME");
do {
names[cursor.getPosition()] = cursor.getString(colIndex);
} while (cursor.moveToNext());
}
Keep in mind that names will be null if no rows are returned, so make sure you do a null check.

create following method in SQLiteOpenHelper class
public List<String> getAllNames() {
List<String> retData = new ArrayList<String>();
String selectQuery = "SELECT NAME FROM MYTABLE";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
retData.add(cursor.getString(0));
} while (cursor.moveToNext());
}
return retData;
}
then assign this returned list to adapter

The issue with listing id's is that they tend to be meaningless to an end user. Really you want to display user meaningful data, e.g. a name, but to then be able to access the respective id to then efficiently act on a selection from the list presented to a user.
Using an ArrayList is frequently the cause of much frustration, as the list shows what is required but it's then found to be of little use when attempting to use the list beyond displaying data e.g. selecting an item to then do something such as delete or update (if the value is unique within the database it can be used).
As such an ArrayList<your_object> rather then an ArrayList<String> is generally more viable as the source of the List; a Cursor Adapter can also be used as data from the underlying row is easily obtained.
However, there is an issue, unless a Custom Array Adapter is utilised, when using an ArrayList in that the ArrayAdapter class uses the toString method of the object to retrieve the data that is displayed. The simple fix is to provide a suitable toString method in the object, if you don't you will get something long the lines of “SomeType#2f92e0f4”.
Example showing all 3
In the following working example :-
the database (mydb) has 1 table named mytable which has two columns _id (Note must be _id for a CursorAdapter)
There are 3 methods to get the 3 types of list (named accordingly) :-
getAllAsStringArrayList (gets ArrayList)
getAllAsMyTableObjectArrayList (gets ArrayList). Note uses the MyTableObject class (see note in class re overriding the default toString method)
getAllAsCursor
The App, when run, will have 3 lists, the left based upon the first ArrayList, the middle based upon the ArrayList and the last based upon the Cursor.
Clicking an item in any of the lists displays the respective name along with attempts to get the id.
The ArrayList, Left List, fails in this aspect as it can only get the position (i.e. the 4th parameter passed to the listener is the same value as the position).
The ArrayList, middle List, when getting the id from the object (which is retrieved via the getItem(position) method of the Adapter) successfully retrieves the correct id, the 4th parameter is the same as the position, and should not be used.
The Cursor, Right List, retrieves the correct id both via the Cursor and the 4th parameter.
The Code
MyTableObject.java :-
public class MyTableObject {
private long id;
private String name;
public MyTableObject(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
NOTE toString method returns just the name
*/
#Override
public String toString() {
return name;
}
}
DatabaseHelper.java :-
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_MYTABLE = "mytable";
public static final String COl_MYTABLE_ID = BaseColumns._ID; //<<<< use standard android id column name
public static final String COL_MYTABLE_NAME = "_name";
private static final String mytable_crtsql =
"CREATE TABLE IF NOT EXISTS " + TB_MYTABLE +
"(" +
COl_MYTABLE_ID + " INTEGER PRIMARY KEY, " +
COL_MYTABLE_NAME + " TEXT " +
")";
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(mytable_crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addRow(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_MYTABLE_NAME,name);
return mDB.insert(TB_MYTABLE,null,cv);
}
public ArrayList<String> getAllAsStringArrayList() {
ArrayList<String> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME)));
}
csr.close();
return rv;
}
public ArrayList<MyTableObject> getAllAsMyTableObjectArrayList() {
ArrayList<MyTableObject> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(new MyTableObject(
csr.getLong(csr.getColumnIndex(COl_MYTABLE_ID)),
csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME))
)
);
}
csr.close();
return rv;
}
public Cursor getAllAsCursor() {
return mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
ListView mListView01,mListVeiw02,mListView03;
ArrayAdapter<String> mAdapterStringArrayList;
ArrayAdapter<MyTableObject> mAdapterMyTableObjectArrayList;
SimpleCursorAdapter mAdapterCursor;
ArrayList<String> mMyTableListAsStrings;
ArrayList<MyTableObject> mMyTableAsObjects;
Cursor mMyTableListAsCursor;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView01 = this.findViewById(R.id.listview01);
mListVeiw02 = this.findViewById(R.id.listview02);
mListView03 = this.findViewById(R.id.listview03);
mDBHlpr = new DatabaseHelper(this);
mDBHlpr.addRow("Fred");
mDBHlpr.addRow("Bert");
mDBHlpr.addRow("Harry");
mDBHlpr.addRow("Fred");
//String Array List
mMyTableListAsStrings = mDBHlpr.getAllAsStringArrayList();
mAdapterStringArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsStrings
);
mListView01.setAdapter(mAdapterStringArrayList);
//Object Array List
mMyTableAsObjects = mDBHlpr.getAllAsMyTableObjectArrayList();
mAdapterMyTableObjectArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableAsObjects
);
mListVeiw02.setAdapter(mAdapterMyTableObjectArrayList);
// Cursor
mMyTableListAsCursor = mDBHlpr.getAllAsCursor();
mAdapterCursor = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsCursor,
new String[]{DatabaseHelper.COL_MYTABLE_NAME},
new int[]{android.R.id.text1},
0
);
mListView03.setAdapter(mAdapterCursor);
mListView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = mAdapterStringArrayList.getItem(position);
Toast.makeText(
mContext,
"Name is " + name +
". ID is " + String.valueOf(id) +
" (note may not match)",
Toast.LENGTH_SHORT
).show();
}
});
mListVeiw02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
MyTableObject mytable = mAdapterMyTableObjectArrayList.getItem(position);
String name = mytable.getName();
long id_in_object = mytable.getId();
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_object) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
mListView03.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Cursor csr = mAdapterCursor.getCursor(); // already positioned
String name = csr.getString(csr.getColumnIndex(DatabaseHelper.COL_MYTABLE_NAME));
long id_in_cursor = csr.getLong(csr.getColumnIndex(DatabaseHelper.COl_MYTABLE_ID));
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_cursor) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
}
}

Related

How to make a checkbox from information found in DataBase?

I have a table in DataBase, and I want to make a table.
Now it makes no sense that I will do a lot of CheckBox and show you only some of them according to the information in the table. I heard about the listview
But how do I do listview of checkbox I found an example of listview on the Internet and when I tried to insert large information, only half the information came in, so I was told to do adapter.
Do you have an example of how to do this?
It DatabaseHandler:
package budgetreport.com.budgetreport;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 4;
// Database Name
private static final String DATABASE_NAME = "Records_Item Purcashes";
// Contacts table name
private static final String TABLE_RECORDS = "Records";
// Contacts Table Columns names
private static final String KEY_ID = "ID";
private static final String KEY_PRICE = "Price";
private static final String KEY_ITEM = "Item";
private static final String KEY_DETAILS = "Details";
private static final String KEY_DATE = "Date";
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_RECORDS + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_PRICE + " INTEGER," + KEY_ITEM + " TEXT,"
+ KEY_DETAILS + " TEXT, " + KEY_DATE + " 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_RECORDS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addRecord(Record record) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, record.getId()); // Contact Name
values.put(KEY_PRICE, record.getPrice()); // Contact Name
values.put(KEY_ITEM, record.getItem()); // Contact Name
values.put(KEY_DETAILS, record.getDetails()); // Contact Name
values.put(KEY_DATE, record.getDetails()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_RECORDS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Record getRecord(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_RECORDS, new String[] { KEY_ID, KEY_PRICE,
KEY_ITEM, KEY_DETAILS, KEY_DATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Record record = new Record(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)), cursor.getString(2), cursor.getString(3), cursor.getString(4));
// return contact
return record;
}
// Getting All Contacts
public List<Record> getAllContacts() {
List<Record> contactList = new ArrayList<Record>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_RECORDS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Record record = new Record();
record.setId(Integer.parseInt(cursor.getString(0)));
record.setPrice(Integer.parseInt(cursor.getString(1)));
record.setItem(cursor.getString(2));
record.setDetails(cursor.getString(3));
record.setDate(cursor.getString(4));
// Adding contact to list
contactList.add(record);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Getting contacts Count
public int getRecordsCount() {
String countQuery = "SELECT * FROM " + TABLE_RECORDS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
// cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public int updateContact(Record record) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, record.getId());
values.put(KEY_PRICE, record.getPrice());
values.put(KEY_DETAILS, record.getDetails());
values.put(KEY_DATE, record.getDate());
// updating row
return db.update(TABLE_RECORDS, values, KEY_ID + " = ?",
new String[] { String.valueOf(record.getPrice()) });
}
// Deleting single contact
public void deleteContact(Record record) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECORDS, KEY_ID + " = ?",new String[]
{String.valueOf(record.getPrice()) });
db.close();
}
}
Deletion of checked Items as per I want to erase the lines I have marked.
This is relatively simple to progress to.
It involves
- a) adding a method to the database helper to delete according to id.
- b) (i)amend the onClick listener to invoke the delete method (simple loop) and to then (ii)update the listview (after the loop).
However, the original custom adapter has some flaws in that the original cursor is retained via mCsr and no consideration was given to the number of checkboxes being changed when the Cursor is changed (swapped).
As such the adapter has had references to mCsr removed and replaced by the Cursor passed or via calling the getCursor method. Also the swapCursor() method has been overidden to adjust the number of elements of and re-initialise the elemnets (set to false), of mCheckBoxes.
a) The new deleteRecord method :-
public boolean deleteRecord(long id) {
SQLiteDatabase db = this.getWritableDatabase();
return (db.delete(TABLE_RECORDS,KEY_ID + "=?",new String[]{Long.toString(id)})> 0);
}
b)(i) onCLickListener amendments (note includes grouping all deletes into a single transaction) :-
// <<<<< DO IT BUTTON HANDLER i.e. get list of ID's for checked items
mDoItButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get the ID's for the checked Items
mCheckedIdList = mMCA.getCheckedRecordIdList();
Toast.makeText(mContext,"You have " + mCheckedIdList.length + " Items checked.",Toast.LENGTH_SHORT).show();
//<<<< to delete
SQLiteDatabase db = mDBHandler.getWritableDatabase();
db.beginTransaction();
for (long id: mCheckedIdList) {
mDBHandler.deleteRecord(id);
}
db.setTransactionSuccessful();
db.endTransaction();
refreshListView();
}
});
b(ii) Update the Listview (new method in the Activity) :-
private void refreshListView() {
mCsr = mDBHandler.getAllRecords();
mMCA.swapCursor(mCsr);
}
Notes
this is added as a method to the activity.
mMCA.notifyDatasetChanged(); is an alternative (I personally prefer `swapCursor1 as it's more decsriptive).
The modified Custom Cursor Adapter should be :-
public class MyCustomCursorAdapter extends CursorAdapter {
private Context mContext;
private String[] mColumns;
private int[] mViews;
private int mLayout;
private boolean[] mCheckBoxStates;
private int mCheckBoxView;
// Constructor for the Custom Cursor Adapter
MyCustomCursorAdapter(Context context, int layout, Cursor csr, String[] from_columns, int[] to_views, int checkbox_view) {
super(context,csr, false);
mContext = context;
mLayout = layout;
mColumns = from_columns;
mViews = to_views;
mCheckBoxView = checkbox_view;
}
#Override
// Inflate the layout we are going to use (as passed via 2nd parameter)
public View newView(Context context, Cursor csr, ViewGroup parent) {
// Initialise an int array for the checkboxes (all will be 0)
mCheckBoxStates = new boolean[csr.getCount()];
return LayoutInflater.from(context).inflate(mLayout,parent,false);
}
#Override
// Tie the from_columns to the display views
public void bindView(View view, Context context, Cursor csr) {
final Cursor fcsr = csr;
// Place the data from the cursor into the respective View (TextView)
for (int i = 0; i < mColumns.length; i++) {
((TextView) view.findViewById(mViews[i])).setText(csr.getString(csr.getColumnIndex(mColumns[i])));
}
// Set the checkbox (note should be false, unless otherwise changed)
CheckBox currentCheckBox = (CheckBox) view.findViewById(mCheckBoxView);
currentCheckBox.setChecked(mCheckBoxStates[csr.getPosition()]);
currentCheckBox.setTag(new Long(csr.getLong(csr.getColumnIndex(DatabaseHandler.KEY_ID))));
//
currentCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
final int position = fcsr.getPosition();
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Store the checkbox status
mCheckBoxStates[position] = ((CheckBox) buttonView).isChecked();
int restore_cursor_position = fcsr.getPosition();
//Move the Cursor to the respective row
//NOTE! 1st position in Lisview is 1 but equates to cursor row 0 etc hence -1
fcsr.moveToPosition(position);
Toast.makeText(mContext,
"You Changed the CheckBox for row " +
Integer.toString(position + 1) +
" Item is " +
fcsr.getString(fcsr.getColumnIndex(DatabaseHandler.KEY_ITEM))
,
Toast.LENGTH_SHORT
).show();
//restore the Cursor's position
fcsr.moveToPosition(restore_cursor_position);
}
});
}
// get the list of items (the ID's as long) that have been checked.
public long[] getCheckedRecordIdList() {
Cursor csr = this.getCursor();
// using ArrayList as we can add as we don't yet know how many
ArrayList<Long> rva = new ArrayList<>();
// Just in case save the current position of the Cursor
int restore_cursor_position = csr.getPosition();
// Loop through the checkbox states
for (int i=0; i < mCheckBoxStates.length; i++) {
// If the checkbox reflected as being checked then handle, else ignore it
if (mCheckBoxStates[i]) {
// Move to the respective cursor row
csr.moveToPosition(i);
// get the respective ID and store in the arraylist
rva.add(csr.getLong(csr.getColumnIndex(DatabaseHandler.KEY_ID)));
}
}
// Done with the Cursor so re-position it
csr.moveToPosition(restore_cursor_position);
// Create the long array to be returned
long[] rv = new long[rva.size()];
// Populate the long array with the id's from the arraylist
for (int i=0; i < rva.size(); i++) {
rv[i] = rva.get(i);
}
// return the long[]
return rv;
}
#Override
public Cursor swapCursor(Cursor csr) {
mCheckBoxStates = new boolean[csr.getCount()];
for (int i=0; i < mCheckBoxStates.length; i++) {
mCheckBoxStates[i] = false;
}
return super.swapCursor(csr);
}
}
here's an example based upon you code.
1) The Activity's layout (i.e a ListView with an id of lv001) as file activity_main.xml :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mjt.budgetreport.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_margin="10dp"
/>
<ListView
android:id="#+id/lv001"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
2) A layout for each row (Item in ListView terminology) as file listviewitem_record.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/record_price"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
<TextView
android:id="#+id/record_item"
android:layout_width="0dp"
android:layout_weight="10"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
<TextView
android:id="#+id/record_details"
android:layout_width="0dp"
android:layout_weight="20"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
<TextView
android:id="#+id/record_date"
android:layout_width="0dp"
android:layout_weight="10"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
<CheckBox
android:id="#+id/record_checkbox"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:layout_margin="5dp"/>
</LinearLayout>
Note! the inclusion of a CheckBox, as well as TextViews for all columns.
3) To simplify matters I used this as DatabaseHandler.java :-
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 4;
// Database Name
public static final String DATABASE_NAME = "Records_Item Purcashes";
// Contacts table name
public static final String TABLE_RECORDS = "Records";
// Contacts Table Columns names
public static final String KEY_ID = "_id";
public static final String KEY_PRICE = "Price";
public static final String KEY_ITEM = "Item";
public static final String KEY_DETAILS = "Details";
public static final String KEY_DATE = "Date";
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_RECORDS +
"(" +
KEY_ID + " INTEGER PRIMARY KEY," +
KEY_PRICE + " INTEGER," +
KEY_ITEM + " TEXT," +
KEY_DETAILS + " TEXT, " +
KEY_DATE + " 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_RECORDS);
// Create tables again
onCreate(db);
}
public void insertRecord(int price, String item, String details, String date) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRICE,price);
cv.put(KEY_ITEM,item);
cv.put(KEY_DETAILS,details);
cv.put(KEY_DATE,date);
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_RECORDS,null,cv);
}
public Cursor getAllRecords() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_RECORDS,null,null,null,null,null,null);
}
/*
// Adding new contact
public void addRecord(AlphabeticIndex.Record record) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, record.getId()); // Contact Name
values.put(KEY_PRICE, record.getPrice()); // Contact Name
values.put(KEY_ITEM, record.getItem()); // Contact Name
values.put(KEY_DETAILS, record.getDetails()); // Contact Name
values.put(KEY_DATE, record.getDetails()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_RECORDS, null, values);
db.close(); // Closing database connection
}
*/
/*
// Getting single contact
public AlphabeticIndex.Record getRecord(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_RECORDS, new String[] { KEY_ID, KEY_PRICE,
KEY_ITEM, KEY_DETAILS, KEY_DATE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
AlphabeticIndex.Record record = new AlphabeticIndex.Record(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)), cursor.getString(2), cursor.getString(3), cursor.getString(4));
// return contact
return record;
}
*/
/*
// Getting All Contacts
public List<AlphabeticIndex.Record> getAllContacts() {
List<AlphabeticIndex.Record> contactList = new ArrayList<AlphabeticIndex.Record>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_RECORDS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
AlphabeticIndex.Record record = new AlphabeticIndex.Record();
record.setId(Integer.parseInt(cursor.getString(0)));
record.setPrice(Integer.parseInt(cursor.getString(1)));
record.setItem(cursor.getString(2));
record.setDetails(cursor.getString(3));
record.setDate(cursor.getString(4));
// Adding contact to list
contactList.add(record);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
*/
/*
// Getting contacts Count
public int getRecordsCount() {
String countQuery = "SELECT * FROM " + TABLE_RECORDS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
// cursor.close();
// return count
return cursor.getCount();
}
*/
/*
// Updating single contact
public int updateContact(AlphabeticIndex.Record record) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, record.getId());
values.put(KEY_PRICE, record.getPrice());
values.put(KEY_DETAILS, record.getDetails());
values.put(KEY_DATE, record.getDate());
// updating row
return db.update(TABLE_RECORDS, values, KEY_ID + " = ?",
new String[] { String.valueOf(record.getPrice()) });
}
*/
/*
// Deleting single contact
public void deleteContact(AlphabeticIndex.Record record) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_RECORDS, KEY_ID + " = ?",new String[]
{String.valueOf(record.getPrice()) });
db.close();
}
*/
}
Notes about Changes to DatabaseHandler.java
The rowid alias has been changed from ID to _id, this is because CursorAdapter's need a column named _id and that column should be an alias for for the rowid (not going into technicalities here).
Instead of using a Record class I've commented out your code that uses this class, for my convenience.
I've changed TABLE and COLUMN names definitions to public, so they can be accessed elsewhere.
I've added two new methods insertRecord and getAllRecords:-
insertRecord just to add some data for testing/example
getAllRecords retrieves all rows as a Cursor, as opposed to an array.
NOTE! The database is not closed, this would result in an exception because a Cursor needs access to the database (opening and closing a database can be detrimental anyway).
4) The Activity itself (just displays the ListView after adding some data for the first run) as file MainActivity.java :-
public class MainActivity extends AppCompatActivity {
DatabaseHandler mDBHandler;
ListView mListView;
SimpleCursorAdapter mSCA;
Cursor mCsr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) this.findViewById(R.id.lv001); // Get the ListView from it's id
mDBHandler = new DatabaseHandler(this); // Get an instance of the Database Handler
// Add some data but only if there is no data
if (DatabaseUtils.queryNumEntries(mDBHandler.getWritableDatabase(),DatabaseHandler.TABLE_RECORDS) < 1) {
mDBHandler.insertRecord(100,"Rock","A large stone.","31/12/2017");
mDBHandler.insertRecord(50,"Boulder","A Rock.","31/12/2018");
mDBHandler.insertRecord(322,"Soil","Loose earth.","31/7/2015");
mDBHandler.insertRecord(237,"Stone","A small rock.","31/8/2014");
mDBHandler.insertRecord(32,"Pebble","A small smooth stone.","11/12/2017");
}
// get all rows into a Cursor
mCsr = mDBHandler.getAllRecords();
// Prepare a list of the columns to get the data from, for the ListViewt
String[] columns_to_get_data_from = new String[]{
DatabaseHandler.KEY_PRICE,
DatabaseHandler.KEY_ITEM,
DatabaseHandler.KEY_DETAILS,
DatabaseHandler.KEY_DATE
};
// Prepare a list of the Views into which to place the data
int[] itemviews_to_place_data_in = new int[]{
R.id.record_price,
R.id.record_item,
R.id.record_details,
R.id.record_date
};
// get and instance of SimpleCursorAdapter
mSCA = new SimpleCursorAdapter(this,
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
0);
// get and instance of SimpleCursorAdapter the listviewitem_record layout
mListView.setAdapter(mSCA);
}
}
Result :-
Notes
This doesn't go into handling the checkboxes, this would likely need a CustomAdapter. There's plenty of tutorials for that e.g. how do i create a custom cursor adapter for a listview for use with images and text?.
Edit Amended to Include CheckBox handling
1) The Activity's layout activity_main.xml - Added a Button for getting Checked Items :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mjt.budgetreport.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_margin="10dp"
/>
<Button
android:id="#+id/doitbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DO ALL CHECKED ROWS"
/>
<ListView
android:id="#+id/lv001"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
2) The Custom Cursor Adapter MyCustomCursorAdapter.java
Signature similar to SimpleCursorAdapter BUT with an extra parameter for the id of the CheckBox.
Includes method getCheckedRecordIdList, which will return a list of Id's that have been checked.
Issues a Toast when a checkbox is checked or unchecked which displays the item, as in the ListView's Item # (not the Item in the table), clicked and the Item clicked (as in the Item value from the table).
:-
public class MyCustomCursorAdapter extends CursorAdapter {
private Context mContext;
private Cursor mCsr;
private String[] mColumns;
private int[] mViews;
private int mLayout;
private boolean[] mCheckBoxStates;
private int mCheckBoxView;
// Constructor for the Custom Cursor Adapter
MyCustomCursorAdapter(Context context, int layout, Cursor csr, String[] from_columns, int[] to_views, int checkbox_view) {
super(context,csr, false);
mContext = context;
mLayout = layout;
mCsr = csr;
mColumns = from_columns;
mViews = to_views;
mCheckBoxView = checkbox_view;
}
#Override
// Inflate the layout we are going to use (as passed via 2nd parameter)
public View newView(Context context, Cursor csr, ViewGroup parent) {
// Initialise an int array for the checkboxes (all will be 0)
mCheckBoxStates = new boolean[csr.getCount()];
return LayoutInflater.from(context).inflate(mLayout,parent,false);
}
#Override
// Tie the from_columns to the display views
public void bindView(View view, Context context, Cursor csr) {
// Place the data from the cursor into the respective View (TextView)
for (int i = 0; i < mColumns.length; i++) {
((TextView) view.findViewById(mViews[i])).setText(csr.getString(csr.getColumnIndex(mColumns[i])));
}
// Set the checkbox (note should be false, unless otherwise changed)
CheckBox currentCheckBox = (CheckBox) view.findViewById(mCheckBoxView);
currentCheckBox.setChecked(mCheckBoxStates[mCsr.getPosition()]);
currentCheckBox.setTag(new Long(mCsr.getLong(mCsr.getColumnIndex(DatabaseHandler.KEY_ID))));
//
currentCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
final int position = mCsr.getPosition();
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Store the checkbox status
mCheckBoxStates[position] = ((CheckBox) buttonView).isChecked();
int restore_cursor_position = mCsr.getPosition();
//Move the Cursor to the respective row
//NOTE! 1st position in Lisview is 1 but equates to cursor row 0 etc hence -1
mCsr.moveToPosition(position);
Toast.makeText(mContext,
"You Changed the CheckBox for row " +
Integer.toString(position + 1) +
" Item is " +
mCsr.getString(mCsr.getColumnIndex(DatabaseHandler.KEY_ITEM))
,
Toast.LENGTH_SHORT
).show();
//restore the Cursor's position
mCsr.moveToPosition(restore_cursor_position);
}
});
}
// get the list of items (the ID's as long) that have been checked.
public long[] getCheckedRecordIdList() {
// using ArrayList as we can add as we don't yet know how many
ArrayList<Long> rva = new ArrayList<>();
// Just in case save the current position of the Cursor
int restore_cursor_position = mCsr.getPosition();
// Loop through the checkbox states
for (int i=0; i < mCheckBoxStates.length; i++) {
// If the checkbox reflected as being checked then handle, else ignore it
if (mCheckBoxStates[i]) {
// Move to the respective cursor row
mCsr.moveToPosition(i);
// get the respective ID and store in the arraylist
rva.add(mCsr.getLong(mCsr.getColumnIndex(DatabaseHandler.KEY_ID)));
}
}
// Done with the Cursor so re-position it
mCsr.moveToPosition(restore_cursor_position);
// Create the long array to be returned
long[] rv = new long[rva.size()];
// Populate the long array with the id's from the arraylist
for (int i=0; i < rva.size(); i++) {
rv[i] = rva.get(i);
}
// return the long[]
return rv;
}
}
3) The amended MainActivity to use the Custom Adapter and to get the list of checked Records (displays number selected via Toast) - MainActivity.java
Changed/Added Lines/Methods are marked with <<<<<.
:-
public class MainActivity extends AppCompatActivity {
DatabaseHandler mDBHandler;
ListView mListView;
SimpleCursorAdapter mSCA;
MyCustomCursorAdapter mMCA; // <<<<<
Cursor mCsr;
Button mDoItButton;
Context mContext; //<<<<<
long[] mCheckedIdList; //<<<<<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView = (ListView) this.findViewById(R.id.lv001); // Get the ListView from it's id
mDoItButton = (Button) this.findViewById(R.id.doitbutton); //<<<<<
mDBHandler = new DatabaseHandler(this); // Get an instance of the Database Handler
// Add some data but only if there is no data
if (DatabaseUtils.queryNumEntries(mDBHandler.getWritableDatabase(),DatabaseHandler.TABLE_RECORDS) < 1) {
mDBHandler.insertRecord(100,"Rock","A large stone.","31/12/2017");
mDBHandler.insertRecord(50,"Boulder","A Rock.","31/12/2018");
mDBHandler.insertRecord(322,"Soil","Loose earth.","31/7/2015");
mDBHandler.insertRecord(237,"Stone","A small rock.","31/8/2014");
mDBHandler.insertRecord(32,"Pebble","A small smooth stone.","11/12/2017");
}
mDBHandler.increasePrice(1,213);
// get all rows into a Cursor
mCsr = mDBHandler.getAllRecords();
// Prepare a list of the columns to get the data from, for the ListViewt
String[] columns_to_get_data_from = new String[]{
DatabaseHandler.KEY_ID,
DatabaseHandler.KEY_PRICE,
DatabaseHandler.KEY_ITEM,
DatabaseHandler.KEY_DETAILS,
DatabaseHandler.KEY_DATE
};
// Prepare a list of the Views into which to place the data
int[] itemviews_to_place_data_in = new int[]{
R.id.record_id,
R.id.record_price,
R.id.record_item,
R.id.record_details,
R.id.record_date
};
// get and instance of SimpleCursorAdapter the listviewitem_record layout
mSCA = new SimpleCursorAdapter(this,
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
0);
// Tie the adapter to the Listview
mListView.setAdapter(mSCA);
// <<<<<< Alternate Custom Cursor Adapter
mMCA = new MyCustomCursorAdapter(this,
R.layout.listviewitem_record,
mCsr,
columns_to_get_data_from,
itemviews_to_place_data_in,
R.id.record_checkbox //<<<<<< id of the checkbox
);
// Hijack the Listview
mListView.setAdapter(mMCA); //<<<<<<
// <<<<< DO IT BUTTON HANDLER i.e. get list of ID's for checked items
mDoItButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get the ID's for the checked Items
mCheckedIdList = mMCA.getCheckedRecordIdList();
Toast.makeText(mContext,"You have " + mCheckedIdList.length + " Items checked.",Toast.LENGTH_SHORT).show();
}
});
}
}
Note! you wouldn't typically have two adapters, but I left the SimpleCursorAdapter in for comparison.
Note! be a little patient, as if you click too much too soon you may get consfused.
Note! See other answer for deleting checked items.

Can't match SQLite Row ID with ListView position when trying to delete an item from the table/list

This question has been asked before but none of the implementations helped me so far.
I'm building a to do app and I'm displaying my items in a listview, using SQLite for persistence. I'm able to dynamically add items to my listview and successfully store them in my database, but I'm not able to delete them from the screen or the table. I know the reason why. My SQLite Row ID does not match my ListView. But the other problem is that I should still be able to delete items off my screen and my table with positions that does match the SQLite Row ID (For example, my 3rd To Do in the list) but I'm not able to delete anything.
This is my method that is supposed to delete items from the database:
public boolean itemDeleteFromDatabase(long id) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=?" + id, null) > 0;
listItems.setAdapter(adapter);
return databaseDelete;
}
And I'm calling this method from my OnItemLongClick method, passing in the ListView position as the parameter:
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int position, long id) {
toDoItems.remove(position);
itemDeleteFromDatabase(id);
MainActivity.this.adapter.notifyDataSetChanged();
return true;
}
});
This is the stacktrace. The problem with this is that it only addresses 1 problem in the code:
FATAL EXCEPTION: main
Process: ca.ozbek.preworktodoapp, PID: 2105
android.database.sqlite.SQLiteException: variable number must be between ?1 and ?999 (code 1): , while compiling: DELETE FROM student WHERE todo=?0
Adding Source Code per request
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
private final int REQUEST_CODE = 10;
ArrayList <String> toDoItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ListView listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = (ListView) findViewById(R.id.listViewItems);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, toDoItems);
listItems.setAdapter(adapter);
databaseHelper = new DatabaseHelper(this);
getToDos();
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int position, long id) {
toDoItems.remove(position);
itemDeleteFromDatabase(id + 1);
MainActivity.this.adapter.notifyDataSetChanged();
return true;
}
});
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
Intent intent = new Intent(MainActivity.this, EditItemActivity.class);
intent.putExtra("item", toDoItems.get(pos));
intent.putExtra("itemPos", String.valueOf(pos));
startActivityForResult(intent, REQUEST_CODE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
String item = data.getStringExtra("item");
int itemPosition = Integer.parseInt(data.getStringExtra("itemPos"));
toDoItems.add(itemPosition, item);
toDoItems.remove(itemPosition + 1);
adapter.notifyDataSetChanged();
}
}
public void addItem(View v) {
EditText newItem = (EditText) findViewById(R.id.itemInputEditText);
if (newItem.getText().length() == 0) {
Toast.makeText(this, "You need to enter a to do.", Toast.LENGTH_SHORT).show();
} else {
String item = newItem.getText().toString();
databaseHelper.insertData(item);
adapter.add(item);
newItem.setText("");
}
}
public void getToDos(){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from student",null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex("todo"));
adapter.add(name);
adapter.notifyDataSetChanged();
cursor.moveToNext();
}
}
}
public boolean itemDeleteFromDatabase(Long id) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=?", new String[]{Long.toString(id)}) > 0;
listItems.setAdapter(adapter);
return databaseDelete;
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "todo.db";
public static final String TABLE_NAME = "student";
public static final String ID = "id";
public static final String TO_DO = "todo";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TO_DO_TABLE = "CREATE TABLE "
+ TABLE_NAME
+ "("
+ ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TO_DO
+ " TEXT"
+ ")";
sqLiteDatabase.execSQL(CREATE_TO_DO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(String todo) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TO_DO, todo);
long result = sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor data = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
}
SQL is basically saying that you haven't provided an argument to match the placement ?. i.e.
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=?" + id, null) > 0;
Is effectively saying DELETE FROM table WHERE TO_DO =unobtainablevale 10
10 being a made-up id for demonstration
You could change it to
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=" + id, null) > 0;
or to
boolean databaseDelete = database.delete(TABLE_NAME, TO_DO + "=?", new String[]{Long.toString(id)}) > 0;
The latter probably being considered the better.
P.S. not tested so the odd typo might exist.
Solution 1 using a SimpleCursorAdapter as opposed to an ArrayAdpater
1) in DatabaseHelper change public static final String ID = "id"; to be public static final String ID = "_id"; (i.e add the underscore, suggest do this irrespective of method used but NEEDED for CursorAdapter)
Note! This will require the existing database to be deleted. Use Settings/Apps, select App and then clear data or uninstall app.
2) add the lines indicated with <<<<< to MainActivity (preparing to use Cursor Adapter, ps will leave the ArrayAdapter stuff generally asis but have to remove some)
ArrayList<String> toDoItems = new ArrayList<>();
ArrayAdapter<String> adapter;
SimpleCursorAdapter altadapter; //<<<<<<<<<
Cursor itemlistcursor; //<<<<<<<<<
ListView listItems;
3) Add override for onDestroy method (not required but cleans up cursor) :-
#Override
public void onDestroy() {
super.onDestroy();
itemlistcursor.close();
}
4) Add altertantive method e.g. getItemListAsCursor to get data:-
public void getItemListAsCursor() {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
itemlistcursor = database.query(TABLE_NAME,null,null,null,null,null,null);
}
Note! uses query method instead of rawQuery but equates to SELECT * FROM student;
5) Change itemDeleteFromDatabase to use ID column not the TODO column (didn't spot this before) and comment out lines as per the code below:-
public boolean itemDeleteFromDatabase(Long id) {
SQLiteDatabase database = databaseHelper.getWritableDatabase();
boolean databaseDelete = database.delete(TABLE_NAME, ID + "=?", new String[]{Long.toString(id)}) > 0;
//listItems.setAdapter(adapter);
return databaseDelete;
}
6) Comment out the lines as below (get rid of using ArrayAdapater) :-
listItems = (ListView) findViewById(R.id.listViewItems);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, toDoItems);
//listItems.setAdapter(adapter);
databaseHelper = new DatabaseHelper(this);
//getToDos();
7) Change onItemLongClickListener as below
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int position, long id) {
//toDoItems.remove(position);
itemDeleteFromDatabase(id); //<<<<<<
getItemListAsCursor(); //<<<<<<
//MainActivity.this.adapter.notifyDataSetChanged();
altadapter.swapCursor(itemlistcursor); //<<<<<<
return true;
}
});
Note! could keep notifyDatasetChanged (I just prefer swapCursor);
8) Finally add the following just after the commented out //getToDos line :-
getItemListAsCursor();
altadapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
itemlistcursor,
new String[]{ TO_DO},
new int[]{android.R.id.text1},
0);
listItems.setAdapter(altadapter);
Solution 2 using ArrayAdpater
1) Add the complimentary Array for the ID (as per the //<<<<<< line):-
ArrayList <String> toDoItems = new ArrayList<>();
ArrayList<Long> toDoItemsID = new ArrayList<>(); //<<<<<<
ArrayAdapter<String> adapter;
ListView listItems;
2) Change insertData method in DatabaseHelper to return the id by replacing the method with :-
public long insertData(String todo) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TO_DO, todo);
return sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
}
3) Change getToDos method to store id into the compliementary array (//<<<<< ):-
public void getToDos(){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from student",null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(TO_DO));
adapter.add(name);
toDoItemsID.add(cursor.getLong(cursor.getColumnIndex(ID))); //<<<<<<
adapter.notifyDataSetChanged();
cursor.moveToNext();
}
}
}
Note! I have also replaced "todo" with TO_DO
4) Change addItem method to also store id
public void addItem(View v) {
EditText newItem = (EditText) findViewById(R.id.itemInputEditText);
if (newItem.getText().length() == 0) {
Toast.makeText(this, "You need to enter a to do.", Toast.LENGTH_SHORT).show();
} else {
String item = newItem.getText().toString();
//databaseHelper.insertData(item); //OLD
toDoItemsID.add(databaseHelper.insertData(item)); //<<<<<<<
adapter.add(item);
newItem.setText("");
}
}
Note! I don't like this at all I can envisage issue with keeping toDoItemsID in sync, plus this does currently cater for a not inserted (easy to do as return from insertData should be > 0).
5) Finally the onItemLongClickListener changes :-
listItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int position, long id) {
itemDeleteFromDatabase(toDoItemsID.get(position)); //<<<<<<
toDoItems.remove(position);
toDoItemsID.remove(position); //<<<<<<
//itemDeleteFromDatabase(id + 1); // REMOVE
MainActivity.this.adapter.notifyDataSetChanged();
return true;
}
});
I've tested the above, but may have inadvertently missed something when copying.

How to avoid duplicate contact name (data ) while loading contact info to listview?

I am populating contact list details to list view successfully.
My code:
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor curLog = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,order);
How can I avoid the duplicate data In List view as the contact details is repeating if its joined contact i.e. joined with both phone and Google?. The screen is like
I want to select programmatically only 1 name not the both? Any Idea how I can select?
I have used a rough way to avoid this problem which helped me so much and working nicely.
i.e
Use local database (SQLite) to avoid duplicate data by make phone number to unique.
I have made one SQLite DB to handle this problem:
ContactMerger.java:
public class ContactMerger {
private static final String CONTACT_TABLE = "_contact_table";
private static final String CONTACT_ID = "_contactId";
private static final String CONTACT_NAME = "_contactName";
private static final String CONTACT_MOBILE_NUMBER = "_contactNumber";
private static final String CONTACT_DATE = "_contactDate";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "DB_Contact";
private final Context context;
private SQLiteDatabase ourDatabase;
private DbHelper ourHelper;
private class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String contactQuery = "CREATE TABLE " + CONTACT_TABLE + " ("
+ CONTACT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CONTACT_NAME + " TEXT NOT NULL, " + CONTACT_DATE
+ " TEXT NOT NULL, " + CONTACT_MOBILE_NUMBER
+ " TEXT NOT NULL UNIQUE);";
db.execSQL(contactQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + CONTACT_TABLE);
onCreate(db);
}
}
public ContactMerger(Context context) {
this.context = context;
}
public ContactMerger open() throws SQLException {
ourHelper = new DbHelper(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
// Insert Data to Contact Table
public long insertContacts(String name, String number, String date) throws SQLException {
ContentValues cv = new ContentValues();
cv.put(CONTACT_NAME, name);
cv.put(CONTACT_DATE, date);
cv.put(CONTACT_MOBILE_NUMBER, number);
Log.d("Insert Data", cv.toString());
return ourDatabase.insert(CONTACT_TABLE, null, cv);
}
//Get Contact details from Contact Table
public ArrayList<ContactHolder> getContactDetails() throws Exception{
ArrayList<ContactHolder> contactDetails = new ArrayList<ContactHolder>();
String[] columns = new String[] { CONTACT_ID, CONTACT_NAME, CONTACT_DATE, CONTACT_MOBILE_NUMBER };
Cursor c = ourDatabase.query(CONTACT_TABLE, columns, null, null, null,null, null);
int iContactName = c.getColumnIndex(CONTACT_NAME);
int iContactDate = c.getColumnIndex(CONTACT_DATE);
int iContactMobileNumber = c.getColumnIndex(CONTACT_MOBILE_NUMBER);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
ContactHolder data = new ContactHolder();
data.setName(c.getString(iContactName));
data.setDate(c.getString(iContactDate));
data.setNumber(c.getString(iContactMobileNumber));
contactDetails.add(data);
}
return contactDetails;
}
}
Here ContactHolder is just a getter/setter class to handle contact entities.
First I inserted all Contact information once in my MainActivity by the help of a background thread. It prevents to insert the contact info multiple times.
Something like:
private ArrayList<ContactHolder> contactHolder;
private void setCallLogs(Cursor managedCursor) {
contactHolder = new ArrayList<ContactHolder>();
int _number = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int _name = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int _id = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
while (managedCursor.moveToNext()) {
ContactHolder holder = new ContactHolder();
holder.setNumber(managedCursor.getString(_number));
holder.setName(managedCursor.getString(_name));
holder.setDate(managedCursor.getString(_id));
contactHolder.add(holder);
}
Thread t = new Thread(new Runnable() {
#Override
public void run() {
for(int i=0; i<contactHolder.size(); i++){
try{
ContactMerger merger = new ContactMerger(HomeActivity.this);
merger.open();
merger.insertContacts(contactHolder.get(i).getName(),
contactHolder.get(i).getNumber(),
contactHolder.get(i).getdate());
merger.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
});
t.start();
}
At last I gtt all contact information inside an Asynctask(doInbackground()) and put in adapter/listview in its onPostExecute() method in the class I want to show.
Here:
#Override
protected ArrayList<ContactHolder> doInBackground(String... parameters) {
ArrayList<ContactHolder> filterContacts = new ArrayList<ContactHolder>();
ContactMerger merger = new ContactMerger(Aaja_Contact.this);
merger.open();
try {
filterContacts = merger.getContactDetails();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
merger.close();
return filterContacts;
}
I believe this may happen if the contact number is stored in two different ways/formats: for example in your case the number for Akshay may be saved as 982-0123456 and 9820123456
Did you try displaying the number along with the Name by including the Number as well in the list view?
You need to retrieve the data from the Cursor to HashSet (which don't allows duplicate itmes) and then pass the HashSet object to your ListView's Adapter
This is a dump solution but it will help you:
ListView listView;
Set<String> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
listItems = new HashSet<String>();
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor curLog = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,order);
if(curLog != null) {
while(curLog.moveToNext()) {
String str = curLog.getString(curLog.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
listItems.add(str);
}
}
String listString = listItems.toString();
listString = listString.substring(1,listString.length()-1);
String[] newList = listString.split(", ");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, newList);
listView.setAdapter(adapter);
}
Good luck..
Since you're querying Phone.CONTENT_URI, I'm assuming you're looking for contacts with phone number.. then you can use ContactsContract.Contacts.CONTENT_URI
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor curLog = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" }, order);
Its because the listview is showing both normal contacts as well as whatsapp( or like this) linked contacts. Best is to store all the contacts in a Database and then retrieve the contacts using "select distinct..." command of SQL.
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, order);
String temp_name="";
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (name.equals(temp_name))
continue;
temp_name=name;
//add name to your list or adapter here`enter code here`
}
phones.close();
When you loop through your contacts, here's something you can do in the looping statement while you add your next object to avoid creating a duplicate contact:
UserList object=new UserList(name,number);
if(arrayList.size()==0)
{
arrayList.add(object);
}
if(arrayList.size()>0) {
position = arrayList.size();
if (!(arrayList.get(arrayList.position - 1).getName().equals(number) ||
arrayList.get(position - 1).getNumber().equals(number)))
{
arrayList.add(object); }
}
Here, in my object of 'UserList' class, the name and number would repeat from the contact list, so this code just checks if the previous object has the same name or number before adding in the new one.
Old question but still relevant. I could not find suitable query to skip dupes with contentresolver but it's possible to compare all contacts for duplicates by phone number.
With com.googlecode.libphonenumber library it's really simple. Method public MatchType isNumberMatch(CharSequence firstNumber, CharSequence secondNumber) compares number, coutry code, mask and return one of MatchType enum value.

Android SQLite: attempt to re-open an already-closed object

I'm trying to get certain book data from my Inventory table based on the ISBN.
However, I'm getting an error: "attempt to re-open an already-closed object". The error only occurs when I click a listView object, go to a different screen, go back to this page via "finish()", and then try to click on another listView object. I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
Why does it not work if I try to getInventoryEntriesByISBN after returning to this activity from another activity via "finish()"?
The error occurs at SearchResultsScreen:
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
and by extension, occurs at InventoryAdapter:
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
SearchResultsScreen.java
// Set up search array
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]);
InventoryAdapter.java (Most relevant parts)
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
int publish = cursor.getInt(cursor.getColumnIndex("PUBLISH_DATE"));
String publishdate = ((Integer)publish).toString();
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
String callNumber = cursor.getString(cursor.getColumnIndex("CALL_NUMBER"));
int available = cursor.getInt(cursor.getColumnIndex("AVAILABLE_COUNT"));
String availablecount = ((Integer)available).toString();
int inventory = cursor.getInt(cursor.getColumnIndex("INVENTORY_COUNT"));
String inventorycount = ((Integer)inventory).toString();
int due = cursor.getInt(cursor.getColumnIndex("DUE_PERIOD"));
String dueperiod = ((Integer)due).toString();
int checkoutcount = cursor.getInt(cursor.getColumnIndex("COUNT"));
String count = ((Integer)checkoutcount).toString();
//combine variables into one array
searchEntry[0] = ISBN;
searchEntry[1] = title;
searchEntry[2] = author;
searchEntry[3] = publishdate;
searchEntry[4] = callNumber;
searchEntry[5] = availablecount;
searchEntry[6] = inventorycount;
searchEntry[7] = dueperiod;
searchEntry[8] = count;
cursor.close();
return searchEntry;
}
public String getTitleAndAuthorByISBN(String ISBN)
{
int entriesFound = getNumSearchEntries(ISBN);
if(entriesFound==0)
entriesFound = 1;
String searchEntry;
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
searchEntry = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
//put data into respective variable
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
//close cursor and return
cursor.close();
return searchEntry;
}
DataBaseHelper.java
public class DataBaseHelper extends SQLiteOpenHelper
{
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
// ============================ End Variables ===========================
public DataBaseHelper(Context context, String name, CursorFactory factory, int version)
{
super(context, name, factory, version);
}
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
#Override
public void onCreate(SQLiteDatabase _db)
{
_db.execSQL(LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL(CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL(InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL(StatisticsAdapter.STATISTICS_TABLE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// on upgrade drop older tables
_db.execSQL("DROP TABLE IF EXISTS " + LoginDataBaseAdapter.USER_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + CheckOutDataBaseAdapter.CHECKOUT_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + InventoryAdapter.INVENTORY_TABLE_CREATE);
_db.execSQL("DROP TABLE IF EXISTS " + StatisticsAdapter.STATISTICS_TABLE_CREATE);
// Create a new one.
onCreate(_db);
}
}
Check Database Connection before executing query:
if (!dbHelper.db.isOpen())
dbHelper.open();
you can also use cursor.requery(); for again same query.
and in last you have to close the cursor and database also.
cursor.close();
db.close();
Edited:
I have created DBHelper class which extends SQLiteOpenHelper, this class is inner class of DatabaseHelper class and that class have following methods.
/** For OPEN database **/
public synchronized DatabaseHelper open() throws SQLiteException {
dbHelper = new DBHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
/** For CLOSE database **/
public void close() {
dbHelper.close();
}
If you have still doubt then feel free to ping me. Thank you.
The error only occurs when I click an item, go to a different screen, go back to this page via "finish()", and then try to click on another listView object.
I moved the String searchEntries[] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[position]); from the onClickListener to the previous for loop before the onClickListener and now it works.
The correct SearchResultsScreen is below:
SearchResultsScreen.java
// Set up search array
final String Entries[][] = new String[isbn.length][9];
for(int i = 0; i < isbn.length; i++)
{
searchArray.add(new InventoryItem(isbn[i], InventoryAdapter.getTitleAndAuthorByISBN(isbn[i])));
Entries[i] = InventoryAdapter.getInventoryEntriesByISBN(searchQuery, isbn[i]);
}
Toast.makeText(getApplicationContext(), "searchArray.size()="+searchArray.size(), Toast.LENGTH_LONG).show();
// add data in custom adapter
adapter = new CustomAdapter(this, R.layout.list, searchArray);
ListView dataList = (ListView) findViewById(R.id.list);
dataList.setAdapter(adapter);
// On Click ========================================================
dataList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String searchEntries[] = Entries[position];
This is your problem
if(cursor.getCount()<1) // title Not Exist
{
cursor.close();
for(int i = 0; i < 9; i++)
searchEntry[i] = "Not Found";
return searchEntry;
}
cursor.moveToFirst();
cursor.close();
Change to
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
{
String title = cursor.getString(cursor.getColumnIndex("TITLE"));
String author = cursor.getString(cursor.getColumnIndex("AUTHOR"));
//combine variables into one String
searchEntry = title + " / " + author;
}
public String[] getInventoryEntriesByISBN(String search, String ISBN)
{
String[] searchEntry = new String [9];
//Query
String query = "select * from INVENTORY where ISBN = ?";
Cursor cursor = db.rawQuery(query, new String[] {ISBN});
Add SQLiteDatabase db = this.getWritableDatabase(); in this code before executing the raw Query

Android: I have to display content from the database in the listview, in which latest data comes on top

I have to implement a listview in which my current data comes on top of the listview. Right now my recent data comes at the bottom and my first data is coming on the top of the listview. I'm attaching my work so far:
SearchActivity.java
public class SearchActivity extends Activity implements OnClickListener,
OnItemClickListener {
private EditText mHistoryNameEditText;
private Button mInsertButton;
private ListView mHistoryListView;
private ListAdapter mHistoryListAdapter;
private ArrayList<SearchHistoryDetails> searchArrayList;
private ArrayList<SearchHistoryDetails> HistoryObjArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHistoryNameEditText = (EditText) findViewById(R.id.editText1);
mInsertButton = (Button) findViewById(R.id.button1);
mInsertButton.setOnClickListener(this);
mHistoryListView = (ListView) findViewById(R.id.names_lsitviews);
mHistoryListView.setOnItemClickListener(this);
searchArrayList = new ArrayList<SearchHistoryDetails>();
mHistoryListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
mHistoryListView.setAdapter(mHistoryListAdapter);
HistoryObjArrayList = new ArrayList<SearchHistoryDetails>();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
String providedUgraduateName = mHistoryNameEditText.getText()
.toString();
SearchHistoryDetails undergraduateDetailsPojoObj = new SearchHistoryDetails();
undergraduateDetailsPojoObj.setuGraduateName(providedUgraduateName);
HistoryObjArrayList.add(undergraduateDetailsPojoObj);
insertUndergraduate(undergraduateDetailsPojoObj);
finish();
}
}
public void insertUndergraduate(
SearchHistoryDetails paraUndergraduateDetailsPojoObj) {
AndroidOpenDbHelper androidOpenDbHelperObj = new AndroidOpenDbHelper(
this);
SQLiteDatabase sqliteDatabase = androidOpenDbHelperObj
.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME,
paraUndergraduateDetailsPojoObj.getuGraduateName());
long affectedColumnId = sqliteDatabase.insert(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, contentValues);
sqliteDatabase.close();
Toast.makeText(this,
"Values inserted column ID is :" + affectedColumnId,
Toast.LENGTH_SHORT).show();
}
public List<String> populateList() {
List<String> uGraduateNamesList = new ArrayList<String>();
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null,
null, null);
startManagingCursor(cursor);
while (cursor.moveToNext()) {
String ugName = cursor
.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME));
SearchHistoryDetails ugPojoClass = new SearchHistoryDetails();
ugPojoClass.setuGraduateName(ugName);
searchArrayList.add(ugPojoClass);
uGraduateNamesList.add(ugName);
}
sqliteDatabase.close();
return uGraduateNamesList;
}
#Override
protected void onResume() {
super.onResume();
searchArrayList = new ArrayList<SearchHistoryDetails>();
mHistoryListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
mHistoryListView.setAdapter(mHistoryListAdapter);
}
#Override
protected void onStart() {
super.onStart();
searchArrayList = new ArrayList<SearchHistoryDetails>();
mHistoryListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
mHistoryListView.setAdapter(mHistoryListAdapter);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "Clicked on :" + arg2,
Toast.LENGTH_SHORT).show();
SearchHistoryDetails clickedObject = searchArrayList.get(arg2);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickedUgraduateName",
clickedObject.getuGraduateName());
}}
This class helps me in getting the data from the database and populating it on the activity. My creating database class:
AndroidOpenDbHelper.java
public class AndroidOpenDbHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "allsearch_history_db";
public static final int DB_VERSION = 1;
public static final String TABLE_NAME_GPA = "search_table";
public static final String COLUMN_NAME_UNDERGRADUATE_NAME = "undergraduate_name_column";
public AndroidOpenDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sqlQueryToCreateUndergraduateDetailsTable = "create table if not exists "
+ TABLE_NAME_GPA
+ " ( "
+ BaseColumns._ID
+ " integer primary key autoincrement, "
+ COLUMN_NAME_UNDERGRADUATE_NAME
+ " text not null); ";
db.execSQL(sqlQueryToCreateUndergraduateDetailsTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) {
// Upgrade the database
}
}}
This is the class from which I create database and table.
Now, the real deal is that, when I try to populate data from the database it comes as the first one on top and the latest one on down. I want to revert it. Any help will be appreciated in overcoming this problem.
There are a few different ways to do this. I recommend using the ORDER BY clause of your query:
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null, null,
AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME + " DESC");
Also if you are only going to read from one column, your query should only request that column. Otherwise you are wasting resources querying unused columns of information:
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA,
new String[] {AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME},
null, null, null, null,
AndroidOpenDbHelper.COLUMN_NAME_UNDERGRADUATE_NAME + " DESC");
Lastly, you may want to look into using a SimpleCursorAdapter which allows you to bind a query to a ListView with minimal code.
Addition
I took a closer look at your code and try this:
Cursor cursor = sqliteDatabase.query(
AndroidOpenDbHelper.TABLE_NAME_GPA, null, null, null, null, null,
BaseColumns._ID + " DESC");
Well i can suggest you to get the data from the database and add the items in the reverse order in the adapter that you are setting for populating the listview.
Consider this as the sample where you can get the values from the database which returns an arraylist.
Now consider this arraylist and add each item to the arrayadapter from the last like :
for(i=arraylist.size()-1;i>0;i--)
{
adapter.add(arraylist.get(i));
}
and after setting for the first time you can call
adapter.notifyDataSetChanged()
to refresh the list automatically.
Give a try to this

Categories

Resources