Displaying multiple Items in simple_list_item_1 - java

I followed this guide http://www.vogella.de/articles/AndroidSQLite/article.html and altered the table and code to handle additional fields. But when the list is displayed it only displays the Item field and not the price. I can't find where in the code it does this.
Here is the code for the loading of items into the adapter, the getAllItems returns and array of items. Item has id, item and price.
List<Item> values = datasource.getAllItems();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
Here is the code behind that :
public List<Item> getAllItems() {
List<Item> items = new ArrayList<Item>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
null, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Item item = cursorToItem(cursor);
items.add(item);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return items;
}
private Item cursorToItem(Cursor cursor) {
Item item = new Item();
item.setId(cursor.getLong(0));
item.setItem(cursor.getString(1));
item.setPrice(cursor.getString(2));
return item;
}
It appears 'values' is only Item.items and not price and ID but I don't see why?

Without the whole private Item cursorToItem stuff, how about adding
while (!cursor.isAfterLast()) {
items.add(cursor.getLong(0) + " " + cursor.getString(1) + " " + cursor.getString(1));
cursor.moveToNext();
}
If you want to have more objects in a row, your task is much bigger. I suggest you check this link and implement Pankaj's code. I have been using it for a while and it works like a charm. However, it took me a while to understand.

Related

Hashmap to link albumid with album name?

I'm trying to display the album names and album artwork from the songs on my device.
I tried using a comparator to sort the album names, but when i sort the album names the artwork doesn't match the album name.
How can i link the albumid with the matching artwork?
I use picasso to display the album art and.
I get the album art from MediaStore.Audio.Media.ALBUM_ID;
Then i tried using a hashmap to link albumid with album name.
But im getting this error;
E/Couldn't execute task: java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.database.Cursor.moveToFirst()' on a null object reference
// Creating the map "Album IDs" -> "Album Names"
albumIdToAlbumNameMap = new HashMap<>();
//This is what we'll ask of the albums
String[] albumColumns = {
SONG_ALBUMID,
SONG_ALBUM,
};
// Querying the album database
cursor = resolver.query(musicUri, albumColumns, null, null, null);
// Iterating through the results and filling the map.
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
albumIdToAlbumNameMap.put(cursor.getString(0), cursor.getString(1));
cursor.close();
// Map Song IDs to Album IDs
songIdToAlbumIdMap = new HashMap<>();
// For each album, we'll query the databases
for (String albumID : albumIdToAlbumNameMap.keySet()) {
Uri uri = MediaStore.Audio.Albums.getContentUri(albumID);
cursor = resolver.query(uri, new String[] { SONG_ID }, null, null, null);
// Iterating through the results, populating the map
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long currentSongID = cursor.getLong(cursor.getColumnIndex(SONG_ID));
songIdToAlbumIdMap.put(Long.toString(currentSongID), albumID);
}
cursor.close();
}
final String musicsOnly = MediaStore.Audio.Media.IS_MUSIC + "=1";
// Actually querying the system
cursor = resolver.query(musicUri, columns, musicsOnly, null, null);
if (cursor != null && cursor.moveToFirst())
{
// NOTE: I tried to use MediaMetadataRetriever, but it was too slow.
// Even with 10 songs, it took like 13 seconds,
do {
// Creating a song from the values on the row
QuerySongs song = new QuerySongs(cursor.getInt(cursor.getColumnIndex(SONG_ID)),
cursor.getString(cursor.getColumnIndex(SONG_FILEPATH)));
song.setTitle (cursor.getString(cursor.getColumnIndex(SONG_TITLE)));
song.setArtist (cursor.getString(cursor.getColumnIndex(SONG_ARTIST)));
song.setAlbumID (cursor.getInt(cursor.getColumnIndexOrThrow(SONG_ALBUMID)));
// Using the previously created genre maps
// to fill the current song genre.
String currentGenreID = songIdToGenreIdMap.get(Long.toString(song.getId()));
String currentGenreName = genreIdToGenreNameMap.get(currentGenreID);
String currentAlbumID = songIdToAlbumIdMap.get(Long.toString(song.getId()));
String currentAlbumName = albumIdToAlbumNameMap.get(currentAlbumID);
song.setGenre(currentGenreName);
song.setAlbum(currentAlbumName);
// Adding the song to the global list
songs.add(song);
}
while (cursor.moveToNext());
}
else
{
// What do I do if I can't find any songs?
}
cursor.close();
Here does the error occur
// Iterating through the results, populating the map
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long currentSongID = cursor.getLong(cursor.getColumnIndex(SONG_ID));
songIdToAlbumIdMap.put(Long.toString(currentSongID), albumID);
}
Seems like you need to fix your query input to avoid null in cursor.

Whatsapp contacts duplicating my contact list

I created a small activity that displays all contacts with phone numbers in my phone. However, there are duplicates for contacts that have whatsapp installed. For example, if John is in my contact list and he has a whatsapp account as well, the list would look like this:
...
Jake
John
John
JP
...
This is my code for assigning the cursor to the the adapter which links to a listview.
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
final Cursor cursor = getContentResolver().query(uri, null, null, null, sortOrder);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor, from, to, 0);
EDIT
With this code, I confirmed that the duplicates have 0 value for the ContactsContract.CommonDataKinds.Phone.TYPE which means it is a custom contact (Whatsapp). The rest are 2 which means it is a normal contact.
I need to figure out a query where it doesn't use any contacts where ContactsContract.CommonDataKinds.Phone.TYPE == 0
I know it might be a bit late. However I was having the same issue.
ContactsContract.CommonDataKinds.Phone.TYPE as per the android documentation refers not to whether it is a custom contact but to what type of contact it is i.e. Mobile(2), Home(1) or Work(3). Whatsapp contacts will be a 2 - mobile.
I used the following function to remove the duplicates (not sure if there is a better way):
private boolean checkDuplicate(String position) {
LinkedHashMap<String, Integer> map;
Integer testNull;
map=new LinkedHashMap<>();
testNull=map.get(position);
if(testNull==null) {
testNull=1;
map.put(position, testNull);
return false;
}
else {
testNull=testNull+1;
if(testNull==2) {
return true;
}
else {
map.put(position, testNull);
return false;
}
}
}

Change Spinner options based on another Spinner

I am trying to implement a user search through my database with the use of spinners.
I have fleets and vehicles(fleets contain vehicles). I have a list of fleets as one spinner and a list of vehicles as the other.
By default I want the fleets to be set to "All" and the vehicle one to show all the vehicles(This is currently the case), however when the fleet input is changed to a particular one, say fleet1, the vehicle spinner should update accordingly[this will be implemented via SQLite database search but I don't think the issue is here].
How do I make a listener for when fleet spinner data is changed?
vehicleSpinner = (Spinner) findViewById(R.id.vehicleSpinner);
String selected = (String)fleetSpinner.getSelectedItem();
ArrayAdapter<String> adapter5 = null;
if(selected == "All"){
//show all vehicles
adapter5 = new ArrayAdapter<String>(this, R.layout.sherlock_spinner_item, vehicleArrayListString);
}else{
String vehiclesInFleetQuery = "SELECT * FROM " + Database.TABLE_VEHICLE + " WHERE " + Database.COLUMN_FLEET + "='" + selected +"'";
Log.i(TAG,"QUERY: "+ vehiclesInFleetQuery);
Cursor cursor = Database.listOfVehiclesDesired(query);
if(cursor.moveToFirst()){
do {
String addToList = cursor.getString(cursor.getColumnIndex(Database.COLUMN_VEHICLE_ID));
vehicleArrayFleet.add(addToList);
} while (cursor.moveToNext());
}else{//error on fleet search, no vehicles in fleet
vehicleArrayFleet = vehicleArrayListString;
builderContinue.setMessage("Selected Fleet(" + selected + ") had zero associated vehicles").setTitle("Error").show();
}
if (cursor != null && !cursor.isClosed()) {
System.out.println("Closed");
cursor.close();
}
adapter5 = new ArrayAdapter<String>(this, R.layout.sherlock_spinner_item, vehicleArrayFleet);
}
adapter5.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
vehicleSpinner.setAdapter(adapter5);
You need to set an OnItemSelectedListener for the fleet spinner. You can find an example at http://start-jandroid.blogspot.com/2011/01/android-spinner-example.html. From the listener in the fleet spinner, you can set the selected item of the vehicle spinner.

Getting ArrayList with SQLOpenHelper not working

I have a problem with my SQLiteOpenHelper class.
I have a database with printer manufacturers and details of any kind of printer.
I try to get all manufacturer from my database with this code and returning them in a arraylist.
// Read database for All printer manufacturers and return a list
public ArrayList<String> getPrManufacturer(){
ArrayList<String> manufacturerList = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(CoDeskContract.Printer.TABLE_NAME,
printerManuProjection, null, null, null, null, null,null);
// If cursor is not null and manufacturer List
// does not contains Manufacturer in the list then add it!
if ((cursor != null) && (cursor.getCount()>0)){
cursor.moveToFirst();
do {
String cursorManufacturer = cursor.getString(0);
//Checking for manufacturer in the list
for(String manufacturerInList:manufacturerList){
if (!manufacturerInList.equals(cursorManufacturer))
manufacturerList.add(cursorManufacturer);
}
}while(cursor.moveToNext());
}
// Return list of manufacturers from database
return manufacturerList;
}
I want every manufacturer to be once in a list.
Somehow i cant to get it to work.
Im still a newbie.
Thanks for any Help.
You can also use the distinct keyword in SQLite (http://www.sqlite.org/lang_select.html). Use SQLiteDatabase.rawQuery(String query, String[] args) for that.
db.rawQuery("SELECT DISTINCT name FROM " + CoDeskContract.Printer.TABLE_NAME,null);
There are two issues:
In the beginning, when your list manufacturerInList is empty then it will not go inside for(String manufacturerInList:manufacturerList){ loop and hence it will never add any entry in the list.
Once you fix your problem 1, still it will not work as if (!manufacturerInList.equals(cursorManufacturer)) checks against each entry in the list and adds the non matching entry in the list possibly multiple times.
To fix the issue, you have two options.
Option1: Use contains as:
if (!manufacturerList.contains(cursorManufacturer)) {
manufacturerList.add(cursorManufacturer);
}
Option2: Use a matchFound boolean flag as:
String cursorManufacturer = cursor.getString(0);
boolean matchFound = false;
//Checking for manufacturer in the list
for(String manufacturerInList:manufacturerList){
if (manufacturerInList.equals(cursorManufacturer)){
matchFound = true;
break;
}
}
if(!matchFound){ // <- doesn't exit in the list
manufacturerList.add(cursorManufacturer);
}
Use ArrayList.contains(Object elem) to check if item is exist in ArrayList or not Change your code as:
// does not contains Manufacturer in the list then add it!
if ((cursor != null) && (cursor.getCount()>0)){
cursor.moveToFirst();
do {
String cursorManufacturer = cursor.getString(0);
//Checking for manufacturer in the list
if (!manufacturerList.contains(cursorManufacturer)) {
manufacturerList.add(cursorManufacturer);
} else {
System.out.println("cursorManufacturernot found");
}
}while(cursor.moveToNext());
}

getting String value from a Spinner backed by CursorAdapter from SQL query in Android

my code here is horribly wrong, and i'm not sure how you would properly do this. i have a Spinner which is populated from a SQLite database query through a CursorAdapter. i need to get the text (value) of the currently selected item. i tried this garbage:
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition())
to get the text, but it crashes every time. what's the proper way to do this? here's some additional code that may be relevant:
/// qc defined above as a SimpleCursorAdapter
/////////setup product selection spinner from db
prdSpn = (Spinner)findViewById(R.id.prd_spn);
Cursor prdCur = null;
try {
prdCur = mDb.query(smsDbSchema.ProductSchema.TABLE_NAME, null, null, null, null, null, null);
} catch(Exception e) {
Log.e("smsdb", e.toString());
}
prdCur.moveToFirst();
startManagingCursor(prdCur);
qc = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
prdCur,
new String[] {smsDbSchema.ProductSchema.COLUMN_NAME},
new int[] {android.R.id.text1}
);
qc.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
prdSpn.setAdapter(qc);
Code similar to the following works for me...
Cursor theCursor = qc.getCursor();
String theString = theCursor.getString(theCursor.getColumnIndex(<your column name here>));
EDIT by moonlightcheese:
implementation:
Cursor theCursor = (Cursor)prdSpn.getSelectedItem();
Log.e("spnERRtest", "Item: " + theCursor.getString(theCursor.getColumnIndex(smsDbSchema.ProductSchema.COLUMN_NAME)));
//theCursor.getString(theCursor.getColumnIndex(smsDbSchema.ProductSchema.COLUMN_NAME)).contains("CAR")
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition())
I'm unclear why you are passing getSelectedItemPosition() to getString(). Shouldn't you pass the column number of the column that has the data you want? Isn't this column unrelated to the row that was selected in the spinner?

Categories

Resources