how to save arraylist after the app is closed.
This is my global class
public class GlobalClass extends Application {
ArrayList<Trip> allTrips = new ArrayList<>();
public ArrayList<String> allTripsString() {
ArrayList<String> allTripsString = new ArrayList<String>();
for (Trip trip : allTrips){
allTripsString.add(trip.getName());
}
return allTripsString;
}
}
This is my trip class
public class Trip {
/** A map with category as key and the associed list of items as value */
Map<String,List<Item>> expanses;
private String name;
public ArrayList<String> ExpensesCategory = new ArrayList<>();
public ArrayList<String> Adults = new ArrayList<>();
public ArrayList<String> Children = new ArrayList<>();
public ArrayList<String> ShoppingName = new ArrayList<>();
public ArrayList<Double> ShoppingPrice = new ArrayList<>();
public ArrayList<String> ShoppingCategory = new ArrayList<>();
public double budget = 0;
/** An item in the expanses list */
static class Item {
final String name;
final double cost;
final String Category;
public Item(String name, double cost, String Category) {
this.name = name;
this.cost = cost;
this.Category = Category;
}
#Override public String toString() {
return this.name + " (" + this.cost + "$)";
}
public String getName(){
return name;
}
public String getCategory(){
return Category;
}
public double getCost(){
return cost;
}
}
public Trip(String name) {
this.name = name;
this.expanses = new HashMap<String,List<Item>>();
for (String cat: ExpensesCategory) { // init the categories with empty lists
this.expanses.put(cat, new ArrayList<Item>());
}
}
public String getName(){
return name;
}
/** Register a new expanse to the trip. */
public void add(String item, double cost, String category) {
List<Item> list = this.expanses.get(category);
if (list == null)
throw new IllegalArgumentException("Category '"+category+"' does not exist.");
list.add( new Item(item, cost, category) );
}
/** Get the expanses, given a category.
* #return a fresh ArrayList containing the category elements, or null if the category does not exists
*/
public List<Item> getItems(String category) {
List<Item> list = this.expanses.get(category);
if (list == null)
return null;
return new ArrayList<Item>(list);
}
/** Get the expanses, given a category.
* #return a fresh ArrayList containing all the elements
*/
public List<Item> getItems() {
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
return list;
}
public ArrayList<String> getItemsString() {
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
ArrayList<String> listString = new ArrayList<String>();
for (Item item : list){
listString.add(item.getName());
}
return listString;
}
public ArrayList<Double> getItemsCost(){
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
ArrayList<Double> listDouble = new ArrayList<>();
for (Item item : list){
listDouble.add(item.getCost());
}
return listDouble;
}
public ArrayList<String> getItemsCategory() {
List<Item> list = new ArrayList<Item>();
for (List<Item> l: this.expanses.values()) // fill with each category items
list.addAll(l);
ArrayList<String> listString = new ArrayList<String>();
for (Item item : list){
listString.add(item.getCategory());
}
return listString;
}
/** Get the total cost, given a category. */
public double getCost(String category) {
List<Item> list = this.expanses.get(category);
if (list == null)
return -1;
double cost = 0;
for (Item item: list)
cost += item.cost;
return cost;
}
/** Get the total cost. */
public double getCost() {
double cost = 0;
for (List<Item> l: this.expanses.values())
for (Item item: l)
cost += item.cost;
cost *= 1000;
cost = (int)(cost);
cost /= 1000;
return cost;
}
}
I want to save the array list and when I close and open the app the array list (alltrips) is saved. How to do this?
I want to use shared preferences but I don't know how to do this because it is not a string it array list with Trip. Can anyone help me to save the arraylist in shared preferences?
SharedPreferences allows you to save a Set of Strings, so your best scenario is to convert every object into a String and then save this collection of String into sharedpreferences, and then when needed you can rebuild the objects from these Strings.
Or you can save it in file system or DB, but SharedPreferences is lighter and easier if all you want is this. Either way you will need to construct/deconstruct the saved content of your list.
//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
EDIT
simple example
public void saveToSharedPreferences(Context context, List<String> list){
Set<String> set =
list.stream()
.collect(Collectors.toSet()); // Returns in this case a Set, if you need Iterable or Collection it is also available.
PreferenceManager.getDefaultSharedPreferences(context) // Get Default preferences, you could use other.
.edit()
.putStringSet("myKey", set) // Save the Set of Strings (all trips but as Strings) with the key "myKey", this key is up to you.
.apply(); // When possible commit the changes to SharePreferences.
}
public void saveToSharedPreferences(Context context, List<Trip> list){
List<String> stringList = list.stream()
.map(Trip::getName) // This uses this method to transform a Trip into a String
// you could use other method to transform into String but if all you need to save is the name this suffices
// examples: .map( trip -> trip.getName()), .map(trip -> trip.toString()), etc. you choose how to save.
// It should save every state that a Trip has, so when you are reading the saved Strings
// you will be able to reconstruct a Trip with its state from each String.
.collect(Collectors.toList());
saveToSharedPreferences(context, stringList);
}
NOTE i did not test this but it should be ok (currently i do not have Android Studio so there might be some little errors, but from this solution you should be able to finish this. If needed i could give you the complete solution working. As of now i do not have access to my IDE and WorkStation.
I think the most easiest way to so this is you can save your data in SharedPrefences and populate your arraylist from the sharedPrefernces. As sharedPrefernces only store primitive types you can use Gson for converting your object into String and then store that in the sharedPrefrence. Hope that helps!.
You need to save your data into the database or you can follow this Stackoverflow question
Question
You can save serialized object and read them by using those methods :
public static boolean writeObjectInCache(Context context, String key, Object object) {
try {
FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
fos.close();
} catch (IOException ex) {
return false;
}
return true;
}
public static Object readObjectFromCache(Context context, String key) {
try {
FileInputStream fis = context.openFileInput(key);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
return object;
} catch (Exception ex) {
return null;
}
}
To read the list , you should cast the Object by your type :
ArrayList<TypeOfYourObject> list = new ArrayList<>();
list = (ArrayList<TypeOfYourObject>) readObjectFromCache(context, CACHE_KEY);
Don't forget to add those permission in your manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I dont think there is lifecyle method which will be called in production mode . the user just moves out of the activity page . you should probably do whatever you want in onPause method .
Related
So I have this class which reads from 2 files and fills 2 Arraylists
with Contact Objects. Now I want to Merge these Arraylists to a new
Arraylist which then I want to Sort and eliminate duplicates. My
problem is: How do I get the filled Arraylists to another method so I
can do the sorting?
Here is my Code:
import java.util.List;
import java.util.Scanner;
final class Addressbook{
public List<Contact> contacts1 = new ArrayList<Contact>();
public List<Contact> contacts2= new ArrayList<Contact>();
public List<Contact> allcontacts = new ArrayList<Contact>();
public void readContacts1(Scanner scanner1) {
scanner1.useDelimiter(";");
while (scanner1.hasNext()) {
final Contact contact= readContacts1(scanner1);
contacts1.add(Contact);
}
}
public void readContacts2(Scanner scanner2) {
while (scanner2.hasNext()) {
final Contact contact = readContacts2(scanner2);
contacts.add(contact);
}
}
public int ContactSearch1(Contact c) {
for (int i = 0; i < contacts1.size(); i++)
if (contacts1.get(i).equals(c))
return i;
return -1;
}
public int ContactSearch2(Contact c) {
for (int i = 0; i < contacts2.size(); i++)
if (contacts2.get(i).equals(c))
return i;
return -1;
}
private static Contact readContact1(Scanner scanner1) {
scanner1.useDelimiter(";");
final String name= scanner1.next();
final String lastname = scanner1.next();
final String address = scanner1.next();
final String number = scanner1.next();
final Contact contact= new Contact(name, lastname, address, number);
return contact;
}
private static Contact ReadContact2(Scanner scanner2) {
scanner2.useDelimiter(";");
final String name= scanner2.next();
final String lastname = scanner2.next();
final String address = scanner2.next();
final String number = scanner2.next();
final Contact contact= new Contact(name, lastname, address, number);
return contact;
}
}
First, the provided code contains a lot of duplicated parts which may easily be encapsulated in a separate helper class which takes care of reading and searching the lists.
final class Addressbook{
private List<Contact> contacts1;
private List<Contact> contacts2;
private List<Contact> allContacts;
private static class ContactHelper {
public static List<Contact> readContacts(Scanner scanner) {
// scanner.setDelimiter(";"); // it's better to set this parameter in the call
List<Contact> result = new ArrayList<>();
boolean hasData = scanner.hasNext();
while (hasData) {
final String name= scanner.next();
final String lastname = (hasData &= scanner.hasNext()) ? scanner.next() : "NO_LAST_NAME";
final String address = (hasData &= scanner.hasNext()) ? scanner.next() : "NO_ADDRESS";
final String number = (hasData &= scanner.hasNext()) ? scanner.next() : "NO_NUMBER";
result.add(new Contact(name, lastname, address, number));
hasData = scanner.hasNext();
}
return result;
}
public static int indexOfContact(Contact contact, List<Contact> list) {
Objects.requireNonNull(contact);
Objects.requireNonNull(list);
for (int i = 0, n = list.size(); i < n; i++) {
if (contact.equals(list.get(i))) {
return i;
}
}
return -1;
}
}
}
Then appropriate methods to set fields contacts1, contacts2 should use the helper's methods:
// class AddressBook
public void readContacts1(Scanner scanner) {
contacts1 = ContactHelper.readContacts(scanner);
}
public void readContacts2(Scanner scanner) {
contacts2 = ContactHelper.readContacts(scanner);
}
A method to join the lists, sort them, and remove the duplicates can be implemented using TreeSet if class Contact implements interface Comparable required for sorting the contacts in their natural order, otherwise custom comparator must be provided.
// another helper method
public static List<Contact> joinContacts(List<Contact> ... contactLists) {
Set<Contact> sortedWithoutDups = new TreeSet<>();
for (List<Contact> list : contactLists) {
if (null != list) {
sortedWithoutDups.addAll(list);
}
}
return new ArrayList<>(sortedWithoutDups);
}
// setting allContacts
public void joinContacts() {
allContacts = AddressBook.joinContacts(contacts1, contacts2);
}
This task can be resolved using Stream API (allowing for joining more than 2 lists any of which may be null):
// AddressBook
public void joinContacts() {
allContacts = ContactHelper.joinContactLists(contacts1, contacts2);
}
// ContactHelper
public static List<Contact> joinContactLists(List<Contact> ... lists) {
return Arrays.stream(lists) // Stream<List<Contact>>
.filter(Objects::nonNull) // filter out null lists
.flatMap(List::stream) // convert to Stream<Contact>
.sorted() // sort
.distinct() // _and then_ remove duplicates
.collect(Collectors.toList());
}
contacts1.addAll(contacts2);
contacts1.sort((o1, o2) -> o1 < o2 ? o1 : o2);
contacts1.addAll(contacts2)
This adds all contacts2 to contacts1 and contacts1 List will have all the contacts.
Here u can replace o1 < o2 can be replaced with the logic u need to sort.
The easiest way to ensure, that you do not have duplicates in your ArrayList is to copy your list into a Collection that does not allow duplicates (for example a set) and then copy it back into the ArrayList you need. I would recommend to check out this post for this:
Answers to Question: I have an ArrayList, and I want to remove repeated strings from it. How can I do this?
Ultimately your problem could be answered the following way (using the code of mentioned blog post):
allcontacts.addAll(contacts1);
allcontacts.addAll(contacts2);
Set<Contact> set = new HashSet<>(allcontacts);
allcontacts.clear();
allcontacts.addAll(set);
Now you got rid of all duplicates and merged the ArrayLists contacts1 and contacts2 into allcontacts.
You now only have to sort allcontacts, which can be done like this (if Contact implements Comparable):
Collections.sort(allcontacts);
I want to get the model numbers from the list only
['brand: Samsung, model number: VA2210-MH, size: 21.5', 'brand: Philipe, model number: 244E1SB, size: 21.5']
And I set create attributes and getter and setter of all attributes(only model number will be shown) in Monitor
public class Monitor{
public String brand;
public String modelNumber;
public double size;
public Monitor(String brand, String modelNumber, double size){
this.brand = brand;
this.modelNumber = modelNumber;
this.size = size;
}
public void setModelNumber(String amodelNumber){
modelNumber = amodelNumber;
}
public String getModelNumber(){
return modelNumber;
}
}
so I create a list and add the information into the list
and a method to create a set with model number by the method modelNumberSet()
import java.util.*;
public class ComputerShop{
private List<Monitor> monitorList = new ArrayList<>();
public void addMonitor(String brand, String modelNumber, double size){
Monitor newMonitor = new Monitor(brand, modelNumber, size);
monitorList.add(newMonitor);
}
public Set<Monitor> modelNumberSet(){
Set<Monitor> NewSet = new HashSet<>();
for (Monitor m : monitorList) {
NewSet.add(m.getModelNumber());
}
return NewSet;
}
}
I hope the model number will be added into a new set, the output looks like
[VA2210-MH, 244E1SB]
So I use for loop to incase I will add more information in the future, but the error comes out when I use add(). Why the array cannot be added into the new set? Am I using the wrong function?
Is there a better solution I should use?
Change Set<Monitor> to Set<String>. You are adding model numbers to the set and their types are String. You are trying to put a String where a Monitor is expected. Square peg in a round hole.
Fix the modelNumberSet() method as follows:
public Set<String> modelNumberSet(){
Set<String> newSet = new HashSet<>();
for (Monitor m : monitorList) {
newSet.add(m.getModelNumber());
}
return newSet;
}
So, I have been playing around with java streams a bit, and found something very frustrating.
I want to make a list of this type of object (Customer), and after that use a stream to filter out all those objects where glad == false.
package com.company;
public class Customer {
public String name;
public int points;
public boolean glad;
public Customer(String name, int points, boolean glad) {
this.name = name;
this.points = points;
this.glad = glad;
}
public boolean isGlad() {
return this.glad;
}
}
Whenever I try doing it with a regular array, everything seems to work just fine:
Customer kunde1 = new Customer("jens", 20, true);
Customer kunde2 = new Customer("marie", 20, false);
Customer kunde3 = new Customer("niels", 20, false);
Customer kunde4 = new Customer("jens", 20, true);
Customer kunde5 = new Customer("jens", 20, true);
Customer[] kunderne = {kunde1,kunde2,kunde3,kunde4,kunde5};
Customer[] filtered = Stream.of(kunderne)
.filter(Customer::isGlad)
.toArray(Customer[]::new);
But whenever I try to create the stream from something other than an array, like an ArrayList, I am not able to access the object attributes within my lambda statement
ArrayList<Customer> customers = new ArrayList<>();
Customer kunde1 = new Customer("jens", 20, true);
Customer kunde2 = new Customer("marie", 20, false);
Customer kunde3 = new Customer("niels", 20, false);
Customer kunde4 = new Customer("jens", 20, true);
Customer kunde5 = new Customer("jens", 20, true);
customers.add(kunde1);
customers.add(kunde2);
customers.add(kunde3);
customers.add(kunde4);
customers.add(kunde5);
Customer[] filtered = Stream.of(kunderne)
.filter(Customer::isGlad)
.toArray(Customer[]::new);
But this code won't even run. Why does this happen, and why does it only seem to work with arrays?
There is no such a method as Stream.of(List<T>).
You should use cusomters.stream() which will convert your list into the stream.
That's happening because Stream.of(cusomters) is creating the one element Stream with the ArrayList object inside - obviously there is not method
public static boolean isGlad(ArrayList<Customer> customers) {
return false;
}
and this is why the code is not running
When you are passing Customer[] object to the Stream.of instead of of method version
public static<T> Stream<T> of(T t)
overloaded
public static<T> Stream<T> of(T... values)
is being used and everything is fine
Here is what you wanted to do.
Customer[] filtered = Stream.of(kunderne).filter(Customer::isGlad).map(
cust -> new Customer(cust.name, cust.points, cust.glad)).toArray(
Customer[]::new);
for (Customer c : filtered) {
System.out.println(c.name + " " + c.points + " " + c.glad);
}
You needed to map the filtered customer to a new customer and then put those in an array. Another option would be to add a constructor that takes an existing customer and uses that as input. Here is how that would work.
Customer[] filtered = Stream.of(kunderne).filter(Customer::isGlad).map(
Customer::new).toArray(Customer[]::new);
for (Customer c : filtered) {
System.out.println(c.name + " " + c.points + " " + c.glad);
}
// modified customer class with additional constructor
class Customer {
public String name;
public int points;
public boolean glad;
public Customer(String name, int points, boolean glad) {
this.name = name;
this.points = points;
this.glad = glad;
}
public Customer(Customer cust) {
this(cust.name, cust.points, cust.glad);
}
public boolean isGlad() {
return this.glad;
}
}
I have four ArrayLists. I want to sort one of them alphabetically with case ignored and do the same changes in the other three ArrayLists.
ArrayList<String> arrPackage = new ArrayList<>();
ArrayList<String> arrPackageDates = new ArrayList<>();
ArrayList<String> arrPackageDuration = new ArrayList<>();
ArrayList<String> arrPackageFileSize = new ArrayList<>();
// Code to add data to ArrayLists (data is not coming from sqlite database)
...
// Code to sort arrPackage alphabatically with case ignored
Collections.sort(arrPackage, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
but how do I know which indexes were changed?
One approach would be to create a wrapper object Package which contains the four types of metadata which appears in the four current lists. Something like this:
public class Package {
private String name;
private String date;
private String duration;
private String fileSize;
public Package() {
// can include other constructors as well
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// other getters and setters
}
Then sort using a custom comparator which works on Package objects:
List<Package> packages = new ArrayList<>();
Collections.sort(packages, new Comparator<Package>() {
#Override
public int compare(Package p1, Package p2) {
String name1 = p1.getName();
String name2 = p2.getName();
return name1.compareToIgnoreCase(name2);
}
});
As a general disclaimer, the above operation would most likely be performed must more efficiently in a database. So if your data is ultimately coming from a database, you should try to do such heavy lifting there.
A simple easy way would be backing up your ArrayList.
ArrayList<String> backupPackage = arrPackage;
And then use your code to sort the array. Then use a for loop to compare the two arrays.
for (int i = 0; i < backupArray.size(); i++) {
if (!aar.get(i).equals(aar.get(i))) { // then the item has been changed
// ... YOUR CODE
// at this point you know which indexes have been changed and can modify your other arrays in any way you need
}
}
I used this approach:
ArrayList<String> backupPackage = new ArrayList<>();
ArrayList<String> backupPackageDates = new ArrayList<>();
ArrayList<String> backupPackageDuration = new ArrayList<>();
ArrayList<String> backupPackageFileSize = new ArrayList<>();
for(int j=0;j<arrPackage.size();j++) {
backupPackage.add(arrPackage.get(j));
}
for(int j=0;j<arrPackageDates.size();j++) {
backupPackageDates.add(arrPackageDates.get(j));
}
for(int j=0;j<arrPackageDuration.size();j++) {
backupPackageDuration.add(arrPackageDuration.get(j));
}
for(int j=0;j<arrPackageFileSize.size();j++) {
backupPackageFileSize.add(arrPackageFileSize.get(j));
}
Collections.sort(arrPackage, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});
int newindex;
for(int i=0; i<backupPackage.size(); i++) {
newindex = backupPackage.indexOf(arrPackage.get(i));
if(newindex != i) {
arrPackageDates.set(i, backupPackageDates.get(newindex));
arrPackageDuration.set(i, backupPackageDuration.get(newindex));
arrPackageFileSize.set(i, backupPackageFileSize.get(newindex));
}
}
backupPackage.clear();
backupPackageDuration.clear();
backupPackageDuration.clear();
backupPackageFileSize.clear();
Hi I'm having some trouble getting started with a problem in a Java course learning Swing and starting on JTables and getting data into them. It's going to be hard to explain so I'm just going to post the code I was given, along with the question.
The question is:
The getData() method needs to return an Object[][] containing the data represented by the class.
The first class is MusicAlbum
class MusicAlbum {
private String id;
private String name;
private String genre;
private boolean isCompilation;
private int track_count;
public MusicAlbum(String id, String name, String genre, boolean isCompilation, int track_count) {
this.id = id;
this.name = name;
this.genre = genre;
this.isCompilation = isCompilation;
this.track_count = track_count;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getGenre() {
return genre;
}
public boolean isCompilation() {
return isCompilation;
}
public int getTrackCount() {
return track_count;
}
public boolean equals(Object obj) {
if (obj instanceof MusicAlbum)
return this.id.equalsIgnoreCase(((MusicAlbum)obj).id);
return super.equals(obj);
}
}
The class I have to implement the methods in is MusicDataObject (at the bottom)
import java.util.Random;
import java.util.Scanner;
public class MusicDataObject {
private List<MusicAlbum> albums = new ArrayList<>();
private Random random = new Random(); // for generating IDs
public void addAlbum(MusicAlbum album) throws IllegalArgumentException {
if (searchAlbum(album.getId()) != null)
throw new IllegalArgumentException("Album ID is not new!");
albums.add(album);
}
public MusicAlbum searchAlbum(String id) {
for (MusicAlbum album : albums) {
if (album.getId().equalsIgnoreCase(id)) {
return album;
}
}
return null;
}
public MusicAlbum removeAlbum(String id) {
MusicAlbum album = searchAlbum(id);
albums.remove(album);
return album;
}
public void updateAlbum(MusicAlbum album)
throws IllegalArgumentException {
if (removeAlbum(album.getId()) == null)
throw new IllegalArgumentException("Album ID does not exist!");
addAlbum(album);
}
public String generateID() {
String formatter = "A%0" + (int)Math.ceil(Math.log10(albums.size() * 2) + 1) + "d";
String ID;
do {
ID = String.format(formatter, random.nextInt(albums.size() * 2 + 1));
} while (searchAlbum(ID) != null);
return ID;
}
public void saveData(String fileName) throws IOException {
// make sure that the file exists or try to create it
File fout = new File(fileName);
if (!fout.exists() && !fout.createNewFile())
return;
PrintWriter out = new PrintWriter(fout);
for (MusicAlbum album: albums) {
out.println(serializeAlbum(album));
}
out.close();
}
public String serializeAlbum(MusicAlbum album) {
return String.format(
"%s;%s;%s;%b;%d",
album.getId(),
album.getName(),
album.getGenre(),
album.isCompilation(),
album.getTrackCount());
}
public void loadFile(String fileName) throws FileNotFoundException {
albums = new ArrayList<>();
Scanner in = new Scanner(new File(fileName));
while (in.hasNext()) {
// --- split the next line with the character ";"
String line = in.nextLine();
String[] tokens = line.split(";");
// --- construct a new MusicAlbum using the resulting tokens. NOTE: This isn't very robust.
// If a line doesn't contain enough data or the data is invalid, this will crash
albums.add(new MusicAlbum(
tokens[0],
tokens[1],
tokens[2],
Boolean.parseBoolean(tokens[3]),
Integer.parseInt(tokens[4])
));
}
}
// ----- these methods need to be implemented
public Object[][] getData() {
// TODO
}
public String[] getColumnNames() {
// TODO
}
}
The sample data being used is in a txt file, formatted as so:
A01;Defiance;Soundtrack;true;24
A02;Insomniac;Punk Rock;false;14
A03;A Great Day For The Race;Gypsy Jazz;false;10
A04;Viva La Internet;Ska;false;31
A05;New Surrender;Rock;false;17
So basically it's this getData() method they want me to implement that is giving me grief. I don't fully understand what they want me to do, nor do I fully understand what the Object[][] does.
I hope I have been clear enough, and I will appreciate all help given. Also please try to explain things as best you can and dumb them down as much as possible, I'm new to a lot of this :)
Thanks for your time.
Object[][] is a 2-dimensional array. Each of its element is an Object[], a one-dimensional array.
Your task is to create a 2 dimensional array, having one element (Object[]) for each of your MusicAlbum. An Object[] should hold the properties of a MusicAlbum like id, name, genre, isCompilation and track_count.
You can create an object array like this:
Object[] arr = new Object[] { "some", "values", 23, true };
You can create a 2 dimensional array like this:
Object[][] arr2d = new Object[size][];
And you can iterate over all your MusicAlbums, create an Object[] for each of them containing the properties of that music album, and set it in the arr2d.
You can set/get elements of a 2-dimensional array just like any other arrays:
// Set first element:
arr2d[0] = arr;
// Get first element:
Object[] firstElement = arr2d[0];
The getColumnNames() method should just return a String[] (a String array) containing the column names, the names of the properties.
And it might be obvious but note that the order you return the column names and the order of the property values (in the elements of the Object[]) should be the same.