BaseAdapter with sections, listview - adding cursor list data - java

I'm new here and would be great if someone could help me with this small crisis I have been having. I have been following Jeff Sharkeys Separate List Adapter tutorial which can be found here and I got it all working appropriately to how he explains it.
My problem is I have a database, pre made one which has a table that I am trying to put the extracted data into a list view using Jeffs adapter. I need this data to be put in different sections according to the Category ID column.
The table I am currently extracting data from is the Food table, which has 6 columns, categoriID, menuID, Item, Description, price and a PK _id
My database works properly as in other activities I use a SimpleCursorAdapter to bind data to a list view. (from other tables)
I use the following method in the Database Helper class to retrieve the data I need
public List<FoodModel> getData(String catid, String menuid) {
List<FoodModel> FoodListModel = new ArrayList<FoodModel>();
Cursor cursor = myDataBase.query(FOOD_TABLE, new String [] {FOODITEM_COLUMN, FOODITEMDESCRIPTION_COLUMN,FOODPRICE_COLUMN}, "catid = ? AND menuid = ?",
new String[] { catid, menuid},null, null, null, null);
if (cursor.moveToFirst()){
do{
FoodModel FoodModel = new FoodModel();
FoodModel.setItem(cursor.getString(0));
FoodModel.setdescrription(cursor.getString(1));
FoodModel.setprice(Double.parseDouble(cursor.getString(2)));
FoodListModel.add(FoodModel);} while (cursor.moveToNext());
}
return FoodListModel;
}
the Food Model class is the standard get set class to store the cursors data.
This public method works accordingly as in my main activity (jeffs ListSample.java) I output to the log cat the required information using
Log.d("Reading: ", "Testing Cursor");
List<FoodModel> Data1 = dba.getData("1", "1");
for (FoodModel fd : Data1){
String log = "Item: "+fd.getitem()+" ,Description: " + fd.getdescription() + " ,Price: " + fd.getprice();
Log.d("Name: ", log);
This outputs a list of all the data I need to put into 1 section of the SeperateListAdapter but to the log cat
The 3 things i am trying to output to the list view are the Item, description and price.
My problem is How do I add this data to the list view under the correct section?
as oposed to manually inserting it as Jeff shows
List<Map<String,?>> security = new LinkedList<Map<String,?>>();
security.add(createItem("Remember passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Clear passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Show security warnings", "Show warning if there is a problem with a site's security"));
I didn't want to start my first experience of using this site by pasting all my classes is as this is my first time using this website, my English is not the best and it took me a while to write this I hope it is acceptable as a question, I would be really great full if someone could kindly help me or point me in the right direction.
EDIT: Will gladly post the rest of my code just didnt whant to bombard everyone with loads of information

Related

ListView only displays 3 of 4 records from database matching criteria set

I'm an A Level Student currently working through my A Level Computer Science Controlled Assessment. I am working in Android Studio, using Java, XML and SQLite, none of which I have used before. I am building a Scout Manager application.
I'm currently working on displaying event details, specifically the names and sections of each Scout who has been invited to an event, and this is to be displayed in a ListView. The only issue is, while 4 Scouts have been invited to this event in the database, only 3 are being displayed - or, one too few Scouts are being displayed.
It should be noted that there are separate tables for events, invites and scouts. The invite table matches together the id of the event being attended, and the id of the scout who is attending it - therefore, I find all invites to a certain event, and then the individual scouts attending the event, before displaying the details of the scout.
Here is the code used to get the invites for a given event from the database, from my databaseHandler class:
public Cursor getEventInvites(int sessionid) {
String[] columns={COLUMN_INID + " AS " + BaseColumns._ID, COLUMN_SEID, COLUMN_SCID};
String selection=COLUMN_SEID + " =? ";
String[] selectionArgs={String.valueOf(sessionid)};
Cursor cursor=db.query(TABLE_INVITES, columns, selection, selectionArgs, null, null, null);
return cursor;
}
Here is the code used to display details in a ListBox:
ListView scoutslist = findViewById(R.id.listScouts);
scoutdetailslist=new ArrayList<String>();
scoutadapter=new ArrayAdapter<String>(context, android.R.layout.simple_list_item_multiple_choice, scoutdetailslist);
//ArrayList<int>
Cursor invites;
invites=DatabaseHandler.getEventInvites(sessionid);
invites.moveToFirst();
try {
while (invites.moveToNext()) {
int ScoutID = invites.getInt(invites.getColumnIndex(DatabaseHandler.COLUMN_SCID));
Cursor scout = DatabaseHandler.getScout(ScoutID);
String forename = scout.getString(scout.getColumnIndex(DatabaseHandler.COLUMN_FNAME));
String surname = scout.getString(scout.getColumnIndex(DatabaseHandler.COLUMN_LNAME));
String section = scout.getString(scout.getColumnIndex(DatabaseHandler.COLUMN_SECTION));
String ScoutBasicDetails = forename + " " + surname + ", " + section;
scoutdetailslist.add(ScoutBasicDetails);
}
} finally {
invites.close();
}
scoutslist.setAdapter(scoutadapter);
And here is the code used to get a Scout's details from the database.
public Cursor getScout(int scoutid) {
String[]columns={COLUMN_SCID, COLUMN_FNAME, COLUMN_LNAME, COLUMN_DOB, COLUMN_SECTION, COLUMN_SEX, COLUMN_ADD1, COLUMN_ADD2, COLUMN_CITY, COLUMN_POST, COLUMN_RELIGION, COLUMN_ENAME, COLUMN_EHOME, COLUMN_EMOB, COLUMN_EEMAIL, COLUMN_MED, COLUMN_ALL, COLUMN_TET, COLUMN_SWIM, COLUMN_SCHOOL, COLUMN_PHOTO, COLUMN_MOVE};
String selection = COLUMN_SCID + " =? ";
String[] selectionArgs={String.valueOf(scoutid)};
Cursor cursor=db.query(TABLE_SCOUTS, columns, selection, selectionArgs, null, null, null);
if (cursor!=null&&cursor.moveToFirst()) {
cursor.moveToFirst();
} else {
cursor=null;
}
return cursor;
}
Any help would be appreciated - also, I'm new to this, and pretty tired, so if I've left out important details or been unclear please don't hesitate to leave a comment and ask me to amend the question.
You are moving to the first item, then immediately moving to the next item (thus skipping the first item):
invites.moveToFirst();
try {
while (invites.moveToNext()) {
Consider a do while loop that only executes if the moveToFirst() call succeeds.

SQLite database saves String as "0"

I've just learned how to use SQLite database in Android. And i have one error which i cant figure out.
When i try to save string in my sqlite database, it saves it always as "0", no matter which string i use as an input. This is my code example.
ContentValues values = new ContentValues();
Log.i("CrimeLab", "put : "+crime.getId().toString());
values.put(CrimeDbSchema.CrimeTable.Cols.UUID, "31b0a98a-4089-46de-8325-4ec673bbd713"); // crime.getId().toString()
Log.i("CrimeLab", "take: "+values.getAsString(CrimeDbSchema.CrimeTable.Cols.UUID));
values.put(CrimeDbSchema.CrimeTable.Cols.TITLE, crime.getTitle());
values.put(CrimeDbSchema.CrimeTable.Cols.DATE, crime.getDate().getTime());
values.put(CrimeDbSchema.CrimeTable.Cols.UUID, crime.isSolved() ? 1 : 0);
I have class Crime which have it's unique UUID, title, date and if crime is solved. Everything is saved perfectly but only UUID.toString() is saved in database as "0". No matter which string i try to put it will be saved as "0" in my database, here's the picture.
Here is how it is displayed in the database, everything is good except this string. I have one book, from where i follow my lectures, and it is the same code from the book and it doesn't work. This is how i get my value back from the database.
public class CrimeCursorWrapper extends CursorWrapper
{
public CrimeCursorWrapper(Cursor cursor)
{
super(cursor);
}
public Crime getCrime(){
String uuidString = getString(getColumnIndex(CrimeDbSchema.CrimeTable.Cols.UUID));
String title = getString(getColumnIndex(CrimeDbSchema.CrimeTable.Cols.TITLE));
long date = getLong(getColumnIndex(CrimeDbSchema.CrimeTable.Cols.DATE));
int isSolved = getInt(getColumnIndex(CrimeDbSchema.CrimeTable.Cols.SOLVED));
// And so on.
Everything is saved perfectly but only UUID.toString() is saved in database as "0".
That is because you have not solved any crimes, and you probably have a typo in your code.
In your code snippet, you are setting CrimeDbSchema.CrimeTable.Cols.UUID twice. Once it is the UUID. Once it is 0 or 1 depending on isSolved().
I would assume that the second occurrence needs a different column name.

Content Provider ListView Limit

I would like to limit the amount of contacts displayed in my app. Currently it is querying my Contactscontract.Contacts DB and returning every primary display name that has a phone number. Is there a simple way to reduce this to a numerical amount (say only display 5 contacts), or to certain specified ID's?
This is what I have so far:
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = ContactsContract.Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
ContactsContract.Contacts.HAS_PHONE_NUMBER + " =?", // This is selection string, were looking for records that HAS_PHONE_NUMER is 1
new String[]{"1"}, // 1 means that contact has a phone number
ContactsContract.Contacts._COUNT,
new String[] {"5"},
null);
}
Whenever I try to add new parameters in the return section, Android Studio immediately goes red saying cannot resolve constructor. Is this because the CursorLoader is not defined to receive more parameters?
I defined it earlier in my code as:
mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
Cheers,
Shyam
To achieve a limitation of query results, please add (string concatenate) a " LIMIT 5" to your query:
...
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=? LIMIT 5" //This is selection string, were looking for records that HAS_PHONE_NUMER is 1 AND
// the result set is limited to 5 rows
new String[]{"1"},
null);
...

new to android - understanding source of content provider

As I was working through the following tutorial, I came across this code :
public void onClickRetrieveStudents(View view) {
// Retrieve student records
String URL = "content://com.example.provider.College/students";
I am interested to see what kind of data this is, so I tried to go to the website http://com.example.provider.College/students to view the data, however it just gave some kind of error. Therefore my question is , is this URL some kind of xml document? what exactly is the format for this data... and how can I view it ?
I would recommend you familiarize yourself with the following documenation:
Content Providers:
http://developer.android.com/guide/topics/providers/content-providers.html
Essentially when you pass that "URL" to the ContentResolver (presumably you're doing somethign like this):
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
You're asking android to resolve that URL to a ContentProvider which is set up to handle that URL. The URL is not "imaginary" so much as it's targets are Local objects and processes which exist and are defined by applications which use the ContentProvider mechanism to store and make data available to other applications.
The goal of that URL (which is converted to a URI in this case) is to specify which ContentProvider you want, and what you want from it.
ContentProviders are generally used by applications that want to manage a database and make that information available to other applications while minimizing access violations etc..
EDIT:
This code is from your tutorial. See added comments:
/// this url points to the content provider.
//The content provider uses it to
///reference a specific database which it has knowledge of
//This URI doesn't represent an
//actual FILE on your system, rather it represents a way for you to tell the content //provider what DATABASE to access and what you want from it.
String URL = "content://com.example.provider.College/students";
// This line converts yoru "URL" into a URI
Uri students = Uri.parse(URL);
/// This call returns a Cursor - a cursor is a object type which contains the results of your QUERY in an order manner. IN this case it is a set of rows, each of which has a number of columns coresponding to your query and database, which can be iterated over to pull information from the DB..
/// managedQuery takes, as an argument, the URI conversion of the URL - this is
// where you are actually calling to the contentprovider, asking it to do a query on the
// databse for some information
Cursor c = managedQuery(students, null, null, null, "name");
// This line moves to the first ROW in the cursor
if (c.moveToFirst()) {
// this does somethign as long as the while loop conditional is true.
do{
// This line creates a pop up toast message with the information stored in the columns of the row you the cursor is currently on.
Toast.makeText(this,
c.getString(c.getColumnIndex(StudentsProvider._ID)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.NAME)) +
", " + c.getString(c.getColumnIndex( StudentsProvider.GRADE)),
Toast.LENGTH_SHORT).show();
} while (c.moveToNext());
}
Your question in the comments was:
"all I need is an example of this file: String URL = "content://com.example.provider.College/students"; , what would the data look like ? "
The answer to this is that you have an Sqlite Database on your phone somewhere - generally (and in this case definitely) created by the application and/or content provider you are accessing. You also know that the content resolver accepts this URI and some other information and will return you a CURSOR.
This question addresses what a cursor is.
use of cursor in android
If you read the tutorial fully you will find this code::
public class StudentsProvider extends ContentProvider {
static final String PROVIDER_NAME = "com.example.provider.College";
static final String URL = "content://" + PROVIDER_NAME + "/students";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String _ID = "_id";
static final String NAME = "name";
static final String GRADE = "grade";
You will also find, in the manifest of your tutorial:
<provider android:name="StudentsProvider"
android:authorities="com.example.provider.College">
</provider>
Which is the registration of your ContentProvider for the URI at question.
You will note that your URL and the "PROVIDER_NAME" and "URL" have eerie similarities. This is because the ContentProvider is utilizing these values to identify itself as the resolver for this partiuclar URI to the android system.
You should create the files as described in the tutorial, make the sample app function, and you will be able to start understanding this more clearly.
It's not real, and it's not a web url. That is an example of a hypothetical ContentURI.
As an example, you might consult the UserDictionary like so -
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
You might also create your own.

ORMLite Android- getting 1 column out of 17 from single table

I have one table "company" with contains 3 columns [ name,id ,address ]. But I want to fetch only "name " column values. I am doing like this
Dao<Company, String> dao = getDBHelper().getCompanyDao();
QueryBuilder<Company, String> queryBuilder = dao.queryBuilder();
queryBuilder.orderBy(Company.USERNAME_FIELD_NAME, true);
**queryBuilder.selectColumns("name");**
PreparedQuery<Company> preparedQuery = queryBuilder.prepare();
CloseableIterator<Company> iterator = dao.iterator(preparedQuery);
AndroidDatabaseResults results = (AndroidDatabaseResults) iterator.getRawResults();
Cursor cursor = results.getRawCursor();
But application is crashing when I add "queryBuilder.selectColumns("name") ". Please help me.I want cursor since am using cursoradapter to fill data.
crash logs are here :
java.lang.NullPointerException
at com.j256.ormlite.stmt.QueryBuilder.appendFieldColumnName(QueryBuilder.java:593)
at com.j256.ormlite.stmt.QueryBuilder.appendColumns(QueryBuilder.java:585)
at com.j256.ormlite.stmt.QueryBuilder.appendStatementStart(QueryBuilder.java:405)
at com.j256.ormlite.stmt.StatementBuilder.appendStatementString(StatementBuilder.java:122)
at com.j256.ormlite.stmt.StatementBuilder.buildStatementString(StatementBuilder.java:106)
at com.j256.ormlite.stmt.StatementBuilder.prepareStatement(StatementBuilder.java:74)
at com.j256.ormlite.stmt.QueryBuilder.prepare(QueryBuilder.java:98)
But application is crashing when I add "queryBuilder.selectColumns("name")
Wow. This is a very subtle and long standing bug. It will happen whenever you try to select columns from an entity that does not have an ID field. I've added this bug report:
https://sourceforge.net/p/ormlite/bugs/162/
This has been fixed in trunk and will be in 4.49. Here's the check-in.
https://github.com/j256/ormlite-core/commit/ee95883040a3618a1d455b44f6bfd6935a8d4ec7

Categories

Resources