I have an object which I need to pass into an ArrayList. The ArrayList is contained within an external method, which is in another class.
I've debugged the program and know that the information being passed into the 'Application' Constructor is being put into the 'app' object. My problem is moving it from here to the 'GuestsAttending' Method.
Any help would be greatly appreciated.
Booking Screen Method:
public void saveBookingInfo(View view) {
GuestsAttending sendApplication = new GuestsAttending();
EditText applicantNameText = (EditText) findViewById(R.id.applicantNameTextField);
EditText itemToBurnText = (EditText) findViewById(R.id.itemToBurnTextField);
String appName = applicantNameText.getText().toString();
String appItemToBurn = itemToBurnText.getText().toString();
if (appItemToBurn.isEmpty() || appName.isEmpty()) {
Toast.makeText(BookingScreen.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
}
else {
Application app = new Application(appItemToBurn, appName);
sendApplication.getGuestsAttending(app);
this.finish();
}
}
GuestsAttending Method:
public void getGuestsAttending(Application app){
peopleAttending.add(app);
}
Application Class:
public class Application {
private String name;
private String item;
public Application(String applicantName, String applicantItem) {
name = applicantName;
item = applicantItem;
}
}
For clarity, change "getGuestAttending" to "addGuestAttending". If "peopleAttending" is an array, your method won't work. Change "peopleAttending" to a List or Set, then it will work. If "peopleAttending" needs to be an array, you can't add items to it unless you declare it big enough to hold all your guests. Then you have to keep track of the number of guests, so you know where to insert new guests. In other words, don't use an array, use a List:
List attendingGuests = new LinkedList();
I found a different solution. Instead of creating the object in another class and passing it into the external method call as a parameter, I created the object within the external method, and passed a couple of strings to the method, which I passed into another classes' constructor to make the object within the method.
Related
I'm struggling with an assignment of mine and I can't figure out how to add another element to my list.
import java.util.ArrayList;
public class Ballot {
private ArrayList<Candidate> ballot;
private String officeName;
public Ballot(String officeName) {
this.officeName = officeName;
ArrayList<Candidate> ballot = new ArrayList<Candidate>();
}
public String getOfficeName() {
return officeName;
}
public void addCandidate(Candidate c) {
ballot.add(c);
}
public ArrayList<Candidate> getCandidates() {
return ballot;
}
public static void main(String[] args) {
Ballot b = new Ballot("Election");
b.addCandidate(new Candidate("Sarah", "President"));
System.out.println(b);
}
}
When I try to run the document, it throws a NullPointerException. What am I doing wrong?
The constructor initializes a local variable named ballot that hides the data member with the same name. Then, when you try to add to it, it fails with a NullPointerException, since it was never initialized. If you initialize it you should be OK:
public Ballot(String officeName) {
this.officeName = officeName;
ballot = new ArrayList<Candidate>(); // Here!
}
You're not initializing your list of candidates properly in the Ballot constructor. You need to do:
this.ballot = new ArrayList<Candidate>();
Right now you're just creating a local variable named ballot in the constructor which shadows the actual class field. Since it has never been initialized, you end up getting a NullPointerException when you eventually try to add an element to it.
Also, as a best practice, use interfaces instead of the concrete type. This makes it easy to change implementations later. So instead of defining the field as private ArrayList<Candidate> ballot;, define it as private List<Candidate> ballot;.
As simple that you are not using this object. You are never initiliazing your object
Correct way
public Ballot(String officeName) {
this.officeName = officeName;
this.ballot = new ArrayList<Candidate>();
}
You're overriding your class variable with a local variable of the same name. Either initialize the list directly
private List<Candidate> ballot = new Arraylist<>();
or initialize it in the constructor with
ballot = new ArrayList<>();
FYI: You shouldn't assign implementation classes for your local variables and return values if you can help it. "ballot" should just be the List interface as should the getter. That way if you ever want to change the implementation, you don't have to change everything. It could be an ArrayList, LinkedList, Stack, Vector, etc and it won't matter because they're all using the List interface.
I am currently working on an app that will use many objects as information holders (music things - artist, song, id of album cover img, and another id of 2nd img).
I decided that it would be the best to create "Track" class and use it to make objects and store them in ArrayList.
I created the class, I created the list, but I'm having trouble with accessing it (I want to change the ImageViews and TextViews basing on current Track object).
Here's the Track Class: (Track.java separate)
public class Track {
private String mNameArtist;
private String mNameTrack;
private int mTabResource;
private int mCoverResource;
public Track(String nameArtist, String nameTrack, int tabResourceId, int coverResourceId){
mNameArtist = nameArtist;
mNameTrack = nameTrack;
mTabResource = tabResourceId;
mCoverResource = coverResourceId;
}
public String getArtistName() {
return mNameArtist;
}
public String getTrackName() {
return mNameTrack;
}
public int getTabResourceId() {
return mTabResource;
}
public int getCoverResourceID() {
return mCoverResource;
}}
And here's ArrayList declaration: (PlayActivity.java, inside onCreate method)
ArrayList<Track> Tracks = new ArrayList<Track>();
Tracks.add(new Track("Artist Name", "Track Name", R.drawable.tabtemplate, R.drawable.testcover));
Tracks.add(new Track("Pink Floyd", "Comfortably Numb Solo 1", R.drawable.CNS1Tab, R.drawable.pink_floyd_the_wall));
There are more positions, but you get the idea.
Everything seems to work fine up to this point.
When I want to access it inside another method (even in the same PlayActivity.java) nothing happens or I see errors. I tried many different approaches but every single one fails. For example:
Track.getTabResource(); // can't even use the method.
Tracks.get(3); // does not work as well.
I just can not use objects or that arraylist inside my methods. The "Tracks array" won't even show up in Android Studio when typing. Track does, but I can't access positions from Array.
So to sum up, is there any other way I can use my Objects (ArrayList) items inside other classes and methods?
Thank you for your help in advance.
Create List as instance variable and access through Object of that class.
public class PlayActivity {
List<Track> tracks = new ArrayList<Track>();
public void onCreate() {
tracks.add(new Track("Artist Name", "Track Name", R.drawable.tabtemplate, R.drawable.testcover));
tracks.add(
new Track("Pink Floyd", "Comfortably Numb Solo 1", R.drawable.CNS1Tab, R.drawable.pink_floyd_the_wall));
}
public List<Track> getAllTracks() {
return Collections.unmodifiableList(tracks);
}
public Track getTrack(int index) {
return tracks.get(index);
}
}
I'm coding an Android app with Firebase and want to write an object to the database:
public class newEvent {
public String whoEv;
public String whereEv;
public String whenEv;
public String whatEv;
public newEvent() {}
public newEvent(String whoEv, String whereEv, String whenEv, String whatEv) {
this.whoEv = whoEv;
this.whereEv = whereEv;
this.whenEv = whenEv;
this.whatEv = whatEv;
}
}
This works, but as you can see they are all 'just' strings. What i want is to have the first argument to be a List, Firebase doesnt allow String[] uploads/writings.
The reason is to be able to pass more names into the whoEv as separated Strings/Objects. (to give each name a boolean if they are coming or not).
Now to the exact problem:
public newEvent(List<String> whoEv, String whereEv, String whenEv, String whatEv) {
this.whoEv = whoEv;
this.whereEv = whereEv;
this.whenEv = whenEv;
this.whatEv = whatEv;
}
When i use this, i have no clue how to write the proper code:
newEvent test = new newEvent(List<String>("derp","max"), "Amsterdam", "31/12/2016", "NewYears Eve");
The above obviously doesnt work. Expression expected or unexpected token. What am i missing or doing wrong? Already thanks for reading this!
Edit: Total idiot idea to use List<String>if i want to pass boolean values with the strings... Dont got clue what to use instead though.
Fixed it:
newEvent test = new newEvent("Meppel", "31/12/2016", "Oudjaarsdag", new String[]{"derp", "Sir", "max"});
And in the class as:
`public class newEvent {
public ArrayList<String> wie;
public String waar;
public String wanneer;
public String wat;
public newEvent() {}
public newEvent(String waar, String wanneer, String wat, String... wie) {
this.wie = new ArrayList<>(Arrays.asList(wie));
this.waar = waar;
this.wanneer = wanneer;
this.wat = wat;
}
List is an Interface, you can't directly use it with out a implementation class. You can use one of default jdk provided classes which implements List interface. example ArrayList, LinkedList.
Go through this link on List Implementations and you will understand how you can pass a list of string as argument.
Is it Java? May be you need add the word "new" before List...
And don't forget List is an interface type, so here need use some inheritance class. ArrayList for example
I was wondering if it was possible to call the methods of an external class without actually having to declare an object of that class. They way I've got it set up causes the ArrayList stored within the object empties every time the method the object is used in is called.
If I can call the method without an object, then I can fix my problem.
Thanks in advance.
calling class:
public class BookingScreen extends Activity {
GAClass sendApplication = new GAClass();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking_screen);
}
public void saveBookingInfo(View view) {
EditText applicantNameText = (EditText) findViewById(R.id.applicantNameTextField);
EditText itemToBurnText = (EditText) findViewById(R.id.itemToBurnTextField);
String appName = applicantNameText.getText().toString();
String appItemToBurn = itemToBurnText.getText().toString();
if (appItemToBurn.isEmpty() || appName.isEmpty()) {
Toast.makeText(BookingScreen.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
}
else {
sendApplication.storeApplication(appName, appItemToBurn);
this.finish();
}
}
External method class:
public class GAClass {
ArrayList<Application> peopleAttending;
public void storeApplication(String name, String item){
peopleAttending = new ArrayList<>(10);
peopleAttending.add(new Application(name, item));
}
}
You can do something like below
public class GAClass {
public static ArrayList<Application> peopleAttending=null;
public static void storeApplication(String name, String item){
if(null==peopleAttending){
peopleAttending = new ArrayList();
}
peopleAttending.add(new Application(name, item));
}
}
You can invoke above method like below
GAClass.storeApplication(str_name,str_item);
when you make peopleAttending arraylist static it can be access in static method and
if(null==peopleAttending){
peopleAttending = new ArrayList();
}
Above code ensure first time initialization if peopleAttending 9s null
Use static methods. You can call a static method without creating object of enclosing class.
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
What exactly are you trying to achieve?
The static methods in a class would not need an instance of the class so you can make the methods you need (that do not require the state of the object - i.e. do not need a particular object to work on) static and call them like this:
ClassWithStaticMethods.staticMethod() ;
This class is where I want to call the arrays and set the arrays to empty within the parameters
public class ElectronicsEquipmentSupplier {
private int currentMonth;
private int currentYear;
private String rangeOfProducts;
private CustomerDetailsList details; //Contains the customer details array
private PurchaseOrderList pal; //Contains the purchase array
public ElectronicsEquipmentSupplier(int currentMonth, int currentYear,
String rangeOfProducts ) {
this.currentMonth = currentMonth;
this.currentYear = currentYear;
this.rangeOfProducts = rangeOfProducts;
}
}
This is the class where the array is created. It pulls information from a separate class called PurchaseOrder and then sets the list.
public class PurchaseOrderList {
private ArrayList<PurchaseOrder> purchaseCollection;
public PurchaseOrderList() {
purchaseCollection = new ArrayList<PurchaseOrder>();
}
The CustomerDetailsList class is essentially the same. Just not sure as to the best way to set the array to empty when called in the ElectronicsEquipmentSupplier.
Simply wrap the collection's own clear() method with a publicly-accessible method in your PurchaseOrderClass:
public class PurchaseOrderList {
private ArrayList<PurchaseOrder> purchaseCollection;
public PurchaseOrderList() {
purchaseCollection = new ArrayList<PurchaseOrder>();
}
//THIS IS THE IMPORTANT PART
public void clearPurchaseCollection() {
purchaseCollection.clear();
//You could also accomplish the same thing by reinitializing the list:
//purchaseCollection = new ArrayList<PurchaseOrder>();
}
}
Note however, that calling new PurchaseOrderList() already guarantees an empty purchaseCollection list, since you initialize it in the constructor that way.
So the only time you would need to call clearPurchaseCollection() is if you are reusing this object and want to clean it out first. Depending on the rest of your application, that may be necessary, but it may also just be simpler to throw away that instance and create a new PurchaseOrderList(). Totally depends on the situation.