Android;How to populate a ListView via Cursor - android

I have a Database with a table called users(_id,name).
I am using the following method to get all the records in the ascending order of names
public Cursor getAllNames() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME },
null, null, null, KEY_NAME+" ASC", null);
}
Now i am retrieving the Cursor in the List Activity as follows
DBAdapter db= new DBAdapter(this);
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.lview);
ListView l=(ListView) findViewById(R.id.listView1);
db.open();
Cursor c=db.getAllNames();
db.close();
}
I am trying to use Simple Cursor Adapter to iterate thru the names and assign it to the List View. But since it has be depreciated how to achieve the same ?

SimpleCursorAdapter hasn't been deprecated, one of it's constructors has. If you want to attach Cursor data to a ListView then I strongly suggest the SimpleCursorAdapter option since it's the most easy way to do it. I believe the new SimpleCursorAdapter is offered in the v4 support library.

You can create a custom Adapter that extends BaseAdapter and holds an ArrayList of items.
After you call the getAllNames() and you have all your items in the Cursor, iterate over the Cursor and put all those items in the ArrayList from the CustomAdapter. Then just set the CustomAdapter as the ListView adapter.

Related

How to pass the data in the database to a spinner

I'm creating a method to read all the information in the database and view it through a spinner here is the code i tried for this function
public Spinner loadArtist(){
SQLiteDatabase DB = getReadableDatabase();
String[] projection = {
ArtistMaster.Artist.ARTIST_NAME};
Cursor cursor = DB.query(
ArtistMaster.Artist.TABLE_ARTIST,
projection,
null,
null,
null,
null,
null);
Spinner itemIds = new ArrayList<>();
while(cursor.moveToNext()) {
long itemId = cursor.getLong(
cursor.getColumnIndex(ArtistMaster.Artist.ARTIST_NAME));
itemIds.setAdapter(itemId);
}
cursor.close();
return itemIds;
}
but it gives me an error in this line Spinner itemIds = new ArrayList<>();
Should i declare it as a list instead of spinner
itemIds should be defined as an ArrayList<Long>. A Spinner is a UI element and an ArrayList is a data structure. You will most likely need to map the data to your UI using an adapter of some sort, eg. an ArrayAdapter:
Spinner spinner = ... // findViewById, new Spinner() etc.
ArrayList<Long> itemIds = new ArrayList<>();
//... fill array with artist IDs
spinner.setAdapter(
new ArrayAdapter(
this, // Context, Activity etc.,
android.R.layout.simple_list_item_1, // Spinner TextView item resource ID
itemIds // Data set.
));
By default, ArrayAdapter will call Object#toString() on each data object in the collection.
I'd suggest that it would be easier if you used a Cursor Adpater as they are designed to be used with a Cursor and there is no need to generate arrays.
SimpleCursorAdapter being that, a simple but still pretty flexible adapter for use with Cursors.
The only issue is that a Cursor Adapter requires a column name specifically _id (BaseColumns._ID resolves to this (as used below)).
First have the following member variables (obviously names can be what you wish)
:-
Cursor mCursor;
SimpleCursorAdapter mAdapter;
Spinner spinner;
SQLiteDatabase db;
In the onCreate Method of the activity have
:-
spinner = this.findViewById(R.id.?????); //
db = ???????? (as per your existing code)
manageSpinner();
Have a method
:-
private void manageSpinner() {
mCursor = db.query(
ArtistMaster.Artist.ARTIST_NAME,
new String[]{"*","rowid AS " + BaseColumns._ID}, //<<<<<<<< adds _ID column (unless the table is a WITHOUT ROWID table, pretty unlikely)
null,null,null,null,null
);
if (mAdapter == null) {
mAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mCursor,
new String[]{"the_column"}, // column(s) from which to extract data
new int[]{android.R.id.text1}, // layout views into which the data is placed
0
);
spinner.setAdapter(mAdapter);
// You want want to do something when an Item in the spinner is clicked (this does nothing as it is)
spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//........... do your stuff here
// notes
// id will be the id of the row
// cursor will be positioned, so you can access data from the cursor if needed
}
});
} else {
mAdapter.swapCursor(mCursor);
}
}
Override the activity's onResume (refresh the spinner when returning to activity as underlying data may have changed) and onDestroy (to close the Cursor) methods using
:-
#Override
protected void onDestroy() {
super.onDestroy();
mCursor.close();
}
#Override
protected void onResume() {
super.onResume();
manageSpinner();
}

Getting individual text values from items in listView

I have a custom list view over here that displays data from a sqlite database with the help of a simple cursor adapter.
I would like to know how to display a toast showing the title of each entry (e.g. School) when I hold down each entry (using a longClickListener). Thanks.
The method for the simple cursor adapter which is called during onResume:
private void populateListViewFromDatabase() {
DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.retrieveAllEntriesCursor();
String[] from = {DBAdapter.ENTRY_TITLE, DBAdapter.ENTRY_DESTINATION};
int[] to = {R.id.tvAlarmTitle, R.id.tvAlarmDestination};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,R.layout.custom_alarm_destination_row,c,from,to);
db.close();
lvDestinations.setAdapter(myCursorAdapter);
}

How do you amend a row value before displaying it using ListView and SimpleCursorAdaptor?

I'm using SimpleCursorAdaptor and a ListView to display the values in my SQLite database rows. One of the values in my row is a date (column 'date'). Rather than display this date I need to run this through a method that will return another string based on what the date is. This is the value I want displayed in my list rather than the actual value taken straight from the Database.
In short I wish to display all values from my database table row except for one, where I need to change it before displaying it.
Here is my code:
public class BinCollectionDayListActivity extends ListActivity{
//
private static final String fields[] = { "name", "date", BaseColumns._ID };
//
public void onCreate(Bundle savedInstanceState) {
//
super.onCreate(savedInstanceState);
//
DatabaseHelper helper = new DatabaseHelper(this);
SQLiteDatabase database = helper.getWritableDatabase();
Cursor data = database.query("names", fields, null, null, null, null, null);
CursorAdapter dataSource = new SimpleCursorAdapter(this, R.layout.binrow, data, fields, new int[] { R.id.name, R.id.date });
dataSource.getCursor().requery();
//
ListView view = getListView();
view.setHeaderDividersEnabled(true);
setListAdapter(dataSource);
//
helper.close();
database.close();
}
}
As you can tell I am pretty new to Android development and would love to know what the best approach would be to achieving the desired result.
Thanks in advance,
Tony
Two options that I've used before:
Array Adapter (Preferred):
Create an ArrayAdapter and populate the Cursor data into your ArrayAdapter.
http://anujarosha.wordpress.com/2011/11/17/how-to-create-a-listview-using-arrayadapter-in-android/
ViewBinder: On your Cursor, you can setup/specify a ViewBinder where you can check the data that's about to be mapped, perform some logic on it, and spit out a different result if desired. This is probably exactly what you're looking for, but do consider the ArrayAdapter as it tends to give you better control and it's a pain to switch these things later on.
Changing values from Cursor using SimpleCursorAdapter

Problem using Cursor to populate a spinner

I'm having a problem populating my spinner with data from my SQLite database. Here's the code from my Activity. The Activity crashes with an Unable to start Activity ComponentInfo error where indicated with an arrow.
public class ProjectsActivity extends Activity {
private ReelDbAdapter dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_select);
fillProjectSpinner();
}
private void fillProjectSpinner(){
// initialize cursor to manage data binding to spinner
Cursor projectCursor = null;
Spinner spnExistingProjects = (Spinner)findViewById(R.id.spnExistingProject);
---> projectCursor = dbHelper.getExistingProjects();
//startManagingCursor(projectCursor);
/*
//get the list of project names from the database
String[] from = new String[] {dbHelper.clmProjectName};
//add a new item to the spinner for each of the rows in the database
int [] to = new int[]{R.id.txtViewProjectRow};
//initialize a cursor adapter (similar to ArrayAdapter when populating a spinner from a pre-defined array)
SimpleCursorAdapter projectAdapter = new SimpleCursorAdapter(this, R.layout.view_project_row, projectCursor, from, to);
//add all the rows to the spinner
spnExistingProjects.setAdapter(projectAdapter);
*/
}
Here's the code from the getExistingProjects method from my dbAdapter
public Cursor getExistingProjects() {
if(mDb == null)
{
this.open();
}
return mDb.query(dbTableProject, new String[] {clmProjectName, clmProjectShootingTitle, clmProjectJobNumber},
null, null, null, null, null);
}
Any clues on what I might be doing wrong?
TIA for any help.
Norm
Why don't you try making sure the query is returning something before returning the cursor in your method? Put a log line in that spits out the count of the cursor. Also, you should be able to see this easily while stepping through with the debugger.
Also, why assign null to the cursor's deceleration when you're just going to initialize it a few lines down. Do it all in one line.
Lastly, what db are you trying to one with that this.open() line? I obviously can't tell with just the code you've posted, but put a try catch around that whole thing and spit out the strackTrace. You should see your issue.

SimpleCursorAdapter not reloading data&view on insert in ContentProvider

this code is working fine - i'm loading a bunch of rows into the SimpleCursorAdapter and the ListView displays them. nice.
SimpleCursorAdapter adapter;
Cursor cursor;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv = (ListView)findViewById(R.id.main_lv_projects);
lv.setOnItemClickListener(this);
String[] columns = new String[] { CompassDataProvider.ORG_NAME };
int[] names = new int[] { R.id.organisation_row_name};
cursor = this.managedQuery(CompassDataProvider.CONTENT_URI_ORGANISATIONS, null, null, null, null);
adapter = new SimpleCursorAdapter(this, R.layout.organisation_row, cursor, columns, names);
lv.setAdapter(adapter);
startManagingCursor(cursor);
}
But when i'm inserting a new row via
long rowID = db.getWritableDatabase().insert(CompassDBHelper.ORGS_TABLE_NAME, "", values);
getContext().getContentResolver().notifyChange(CONTENT_URI_ORGANISATIONS, null);
return Uri.withAppendedPath(CONTENT_URI_ORGANISATIONS, ""+rowID);
the list view is not updateing itself - i thought the SimpleCursorAdapter is notified an can then reload its view - not?
the new row is created - i checked on this
when i'm using
cursor.requery();
adapter.notifyDataSetChanged();
in my UI threat the new data gets loaded correctly... whats the observer/listener pattern here that i did not get? :)
thanks,
Martin
The cursor is being passed into the SimpleCursorAdapter by value and not reference. So, calling cursor.requery has no effect. To get this to work the way you want, you're really going to need to implement a listAdapter and process your cursor in there.

Categories

Resources