I'm making a media player currently, and I've been searching all day long how to make a new list view that displays all the artists in the phone.
the type of list where if you click onto it, itll go to a list of the albums by that artist, then the songs etc
the extent of what I know that I have to do is use MediaStore to sort it out, but Im just stumped.
Any help? I dont even have code to go off of, cause ive been trying and deleting what Ive been doing
I understand how it's like to have absolutely nothing to even know where to start looking.
Anyway, I use the following code for getting a list of Artists.
public ArrayList<ArtistItem> getArtistList() {
ArrayList<ArtistItem> artistList = new ArrayList<ArtistItem>();
Uri uri = MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI;
String[] projection = new String[] {MediaStore.Audio.Artists._ID, MediaStore.Audio.ArtistColumns.ARTIST, MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS};
Cursor musicCursor = getContentResolver().query(uri, projection, null, null, null);
int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Artists._ID);
int titleColumn = musicCursor.getColumnIndex(MediaStore.Audio.ArtistColumns.ARTIST);
int numColumn = musicCursor.getColumnIndex(MediaStore.Audio.ArtistColumns.NUMBER_OF_TRACKS);
// Iterate over the List
if(musicCursor!=null && musicCursor.moveToFirst()) {
//add songs to list
do {
String id = musicCursor.getString(idColumn);
String title = musicCursor.getString(titleColumn);
String num = musicCursor.getString(numColumn);
if(title == null || title.equals(MediaStore.UNKNOWN_STRING)) {
title = "Unknown Artist";
}
if(num.equals("1")) {
num = num + " Song";
} else {
num = num + " Songs";
}
artistList.add(new ArtistItem(thisId, thisTitle, thisNum));
} while (musicCursor.moveToNext());
}
return artistList;
}
public class ArtistItem{
private String id;
private String title;
private String num;
ArtistItem(String theId, String theTitle, String theNum) {
id = theId;
title = theTitle;
num = theNum;
}
// TODO Implement getters and setters for id, title and num
}
Related
Hi I'm using a 2d array to simulate a vending machine.
I want to declare an array with a set length and make it oversize so it can accommodate me adding items to it.
Ex:
String[][] itemsT1 = new String[][] {null, null, null, null, null, null, null, null, null};
int itemCount = 0;
// The way I've been adding things in my "addItem' method is:
if ( (items.length > 0) && (itemsCount < items.length) ) {
items[itemsCount][0] = nameOfItem;
items[itemsCount][1] = expirationDate;
itemsCount++;
System.out.println("Item added");
}
// so that the end result of the array should be (with nameOfItem = "Water" and expDate = "15") something like this:
{ {"Water", "15"}, null, null, null, null, null, null, null, null}
// and it's scalable to be hypothetically used again:
{ {"Water", "15"}, {"Chocolate", "20"}, {"Juice", "25"}, null, null, null, null, null, null}
I might be back with more questions so thank you for answering, and let me know if I need to provide more!
Declare your 2D String Array and initialize to the number of items you want to handle within your vending machine, let's say 10 Rows (items) with 3 data Columns in each row:
String[][] items = new String[10][3];
Open stream to accept Keyboard input using the Scanner class:
Scanner userInput = new Scanner(System.in);
Now create a for loop to iterate through each item row within the array so that each can be filled by the User. The following is in its' simplest form with no validation. If you just hit the Enter key when asked for an Item Name then the entry process will end:
for (int i = 0; i < items.length; i++) {
System.out.print("Enter a name for item #" + (i + 1) + ": -> ");
String itemName = userInput.nextLine().trim();
if (itemName.isEmpty()) {
break;
}
System.out.print("Enter expiry for item #" + (i + 1) + ": -> ");
String itemExpiry = userInput.nextLine().trim();
System.out.print("Enter price for item #" + (i + 1) + ": -> ");
String itemPrice = userInput.nextLine().trim();
items[i][0] = itemName;
items[i][1] = itemExpiry;
items[i][2] = itemPrice;
System.out.println();
}
Now, display all the entered items contained within the array into the Console Window:
for (String[] diffItems : items) {
if (diffItems[0] != null) {
System.out.println(Arrays.toString(diffItems));
}
}
If you prefer using 2D arrays, at first you'd need to find the first "empty" space in your vending machine -> a null element. (I'll keep it in a method so it's clear and easier to use)
public int getFreeSpaceIndex(final String[][] vendingMachine) {
for (int index = 0; index < vendingMachine.length; index++)
if (vendingMachine[index] == null)
return index;
// meaning there's no empty space, you should use some static field
// to describe this situation to avoid magic numbers in your code
return -1;
}
After you found the element you can insert whatever you want in there
// you've got the itemT1 array that you've created
// and let's say a user inputs the water item down below,
// I simplified it to declaration, cause it's off the topic
final String[] water = new String[] {"Water", "15"};
final int freeSpaceIndex = findFreeSpaceIndex(itemT1);
if (freeSpaceIndex == -1) {
System.err.printf("There's not enough space for the %s item.", Arrays.toString(water));
} else {
itemT1[freeSpaceIndex] = item;
}
Ultimately you can wrap the array into your own data structure and simply make an addItem(String[]) method that will search for an empty space and handle the overflow.
class VendingMachineStock {
private String[][] stock = new String[][] {null, null, null, null, null, null, null, null, null};
// constructors, api...
public boolean hasFreeSpace() {
return getFreeSpaceIndex() != -1;
}
public boolean addItem(final String[] item) {
final int freeSpaceIndex = getFreeSpaceIndex();
if (freeSpaceIndex == -1) {
System.err.printf("There's not enough space for the %s item.", Arrays.toString(water));
return false;
}
stock[freeSpaceIndex] = item;
return true;
}
private int getFreeSpaceIndex() {
for (int index = 0; index < stock.length; index++)
if (stock[index] == null)
return index;
return -1;
}
}
But there're many flaws in a code like this. Anyone can mess up and add String[] {"15", "Water"} or even new String[] {"15", "30", "I'm Foo Bar :)"}.
The right data structure for your problem would actually be a linked list with Item objects (as #DevilsHnd mentioned) and your own limiting structure over it.
class Item {
private final String name;
private int price;
// default getters, setters, consturctor...
}
class VendingMachineStock {
private final LinkedList<Item> stock;
// this will limit your stock list size
private int maxSlots;
// I omit API and constructor intentionally, it's off the
// topic, but you must write it
public void addItem(final Item item) {
// you can either throw exceptions or return boolean
// flag indicating the result, it's up to you.
// in this case I prefer a detailed explanation on why
// the method did not add the item.
if (stock.size() >= maxSlots) {
throw new IllegalStateException("Stock overflow, can't add more items");
}
stock.add(item);
}
}
I'm trying to replace an item in my recycler view and for that I need to get the index of an object(recipe) inside a list in SQLite database and it returns -1.Any idea??.
private void editRecipe(Intent data) {
if (data.hasExtra(Recipe.RECIPE_KEY) && data.hasExtra(Recipe.RECIPE_NAME)&& data.hasExtra(Recipe.RECIPE_DESCRIPTION)&& data.hasExtra(Recipe.RECIPE_DIFFICULTY))
{
Recipe recipe = (Recipe) data.getSerializableExtra(Recipe.RECIPE_KEY);
Long id = data.getExtras().getLong(Recipe.RECIPE_ID);
String name = (String) data.getExtras().get(Recipe.RECIPE_NAME);
String description = (String) data.getExtras().get(Recipe.RECIPE_DESCRIPTION);
int difficulty = (int) data.getExtras().get(Recipe.RECIPE_DIFFICULTY);
//find the recipe in the list
//Boolean result= recipeDataService.update(recipe);
int position = adapter.getRecipes().indexOf(recipe);
if(position >= 0){
//recipe was found
recipe = recipeDataService.getRecipe(id);
Boolean result= recipeDataService.update(recipe);
adapter.replaceItem(position, recipe);
}
}
} }
ยดยดยด
I have a description of a method, but I do not understand how to put it correctly.
/**
* Add an artist to Karaoke<br>
* Find the end of the artist arrangement and add the new artist to that position.<br>
*/
public void addArtist(String name, String category, String image) {
for (int i = 0; i < artistas.length; i++) {
artistas[i] = new Artista(name, category, image);
}
}
But I do not understand how to complete the route of the arrangement.
I appreciate your help in advance.
I think your updated working solution would look like this
public void addArtist(String name, String category, String image) {
artista = Arrays.copyOf(artista, artista.length + 1);
for (int i = 0; i < artistas.length; i++) {
artistas[i] = new Artista(name, category, image);
}
}
Hope this helps!
If you just need to find the first empty index at the end, it should be enough to check for null, because object arrays are initialized with null.
public void addArtist(String name, String category, String image) {
for (int i = 0; i < artistas.length; i++) {
if(artistas[i] == null) {
artistas[i] = new Artista(name, category, image);
break;
}
}
}
Beware: The above code will not work anymore, if there's a null value somewhere inbetween two Artista objects in the array. In that case the new Artista will be inserted into that index instead.
Hey there Stackoverflowers,
I just started programming in Java and encountered a strange problem concerning printing an object. When a new object of type gast is created the user has to enter his or her birthday. This al works fine, however, if I try to print it out I returns 0-0-0. Why is that? By the way, if I create a new datum directly with the parameter constructor it works fine. Wherein lays the problem? I just can't figure it out. I hope you guys can help me out.
Thanks in advance!
public class Datum {
private static String patroon = "\\d{2}-\\d{2}-\\d{4}";
public int dag;
public int maand;
public int jaar;
Datum(int dag, int maand, int jaar) {
System.out.print("constructor: " + dag);
this.dag = dag;
System.out.println(", dag: " + this.dag);
this.maand = maand;
this.jaar = jaar;
}
Datum() {
newDatum();
}
/* */
public static Datum newDatum() {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
Datum datum = new Datum(dag, maand, jaar);
System.out.println(datum);
return datum;
}
else {
return new Datum();
}
}
public String toString() {
return this.dag + "-" + this.maand + "-" + this.jaar;
}
}
Second class:
Gast() {
this.firstName = Opgave5.userInput("Voornaam gast");
this.lastName = Opgave5.userInput("Achternaam gast");
this.geboortedatum = new Datum();
System.out.println("gast: " + this.geboortedatum); // <--- this prints out 0-0-0
}
public String toString() {
return this.firstName + " " + this.lastName + " " + this.geboortedatum;
}
I think you don't understand constructors in Java. You are merely ignoring the result of newDatum() in the constructor. Also, if it did have the expected effect, it might recurse infinitely in the constructor invocation inside newDatum(). Use something like this; allowing newDatum() to edit the instance will work:
Datum() {
newDatum(this);
}
public static void newDatum(Datum instance) {
String input = Opgave5.userInput("Geboortedatum gast");
boolean b = input.matches(patroon);
if (b) {
String[] str = input.split("-");
int dag = Integer.parseInt(str[0]);
int maand = Integer.parseInt(str[1]);
int jaar = Integer.parseInt(str[2]);
instance.dag = dag;
instance.maand = maand;
instance.jaar = jaar;
System.out.println(instance);
}
else {
new Datum();
}
// ^^ Above code may be buggy, see my answer above code
}
This line:
this.geboortedatum = new Datum();
Is using the default constructor. This will set no values. Try to pass the parameters in via constructor like this:
this.geboortedatum = new Datum(1, 2, 3);
If you want to take advantage of the static method you wrote (which is where you ask for user input), then do the following:
this.geboortedatum = Datum.newDatum();
As written in the title, I check my SQL database with following method:
public String[] getRecord(String category){
String[] record = new String[3];
Cursor crsRecord = sqliteDatabase.rawQuery(QUERY_GET_RECORD + category, null);
int i=0;
while(crsRecord.moveToNext()){
record[i] = crsRecord.getString(0);
i++;
}
return record;
}
Now it could be that the line:
Cursor crsRecord = sqliteDatabase.rawQuery(QUERY_GET_RECORD + category, null);
has no result, because I have no appropriate data in my database. How can I check that I have no result?
cursor.moveToFirst();
if (cursor.isAfterLast()){
// You have no results
}
Or, you could just change your code to this:
while(!crsRecord.isAfterLast()){
// Instead of using an int literal to get the colum index,
// use the getColumnIndex method
int index = crsRecord.getColumnIndex(COLUMN_NAME);
if (index == -1) {
// You don't have the column-- do whatever you need to do.
}
else {
record[i] = crsRecord.getString(index);
i++;
}
crsRecord.moveToNext();
}
If there are no records, the while loop never starts.