I have a server, from which i get the values that i need(name, date, city, picture_url). To get them are in getValues class. I'm using Json.
All the values are saved in an ArrayList called array. I would use them in multiple classes. I would like to call the array in FragmentB. This is the code for the ArrayList
private ArrayList<String> array;
`array = new ArrayList<String>();
array.add(finalresult.getString("picture"));
array.add(finalresult.getString("name"));
array.add(finalresult.getString("date"));
array.add(finalresult.getString("city"));`
Then i thought i needed some kind of function, so it can be called, from other classes. I wanted to name the function, then arguments are numbers, so you can select which element you want, then you just return the object you wanted.
public ArrayList<String> getEvent(int pos)
{
return array.get(pos);
}
But here i get an error:
Required: java.util.ArrayList <java.lang.String>
Found: java.lang.String
In Fragment, i want the specific element of the array, and save it in one string, so i can call it later.
Something like this:
public class FragmentB extends android.support.v4.app.ListFragment{
private GetEvents getEvents = new GetEvents();
private String picture1, name1, city1, date1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
picture1 = getEvents.getArray(0);
name1 = getEvents.getArray(1);
city1 = getEvents.getArray(2);
date1 = getEvents.getArray(3);
}
}
I know that this is wrong. What is the correct way to pass the elements, and then call them in the fragment?
Change
public ArrayList<String> getEvent(int pos)
{
return array.get(pos);
}
to:
public String getEvent(int pos)
{
return array.get(pos);
}
But I think you should consider passing info to your fragments via arguments
For the error, it is just that getEvent(int pos) should return a String and not a List<String>.
If (name, city, date, picture) is an object of your application model (I understand that these are used in several places), you may take advantage to create a simple pojo class to hold these infos, e.g.
public class Event {
String name, city, url;
Date date;
// +constructor
// +getters
}
Then you can store, pass as parameter, filter, sort Events and access properties with specific methods without ambiguity.
Actually storing values with different meaning in an array is bad practice: an array should contain objects of the same nature, e.g. a list of Event, a list of city, etc. Think of what will happen if the order in the array changes. Does it make sense to have city at position 0 and name at 1?
Related
The following class has an array of integer
public class customers {
public static int ID[];
public customers(int ID[]) {
ID = new int[10];
ID[0] = 00245;
ID[1] = 76644;
// more
}
//getters and setters
The subclass is defined as follow
public class songs extends customers {
//bunch of fields
The issue rises when within my array of objects. To create it, the following constructor was needed
public songs(int ID, // bunch of fields {
super(ID[0]);
this.ID = ID[];
// bunch of fields
Here, the super() method throws me back an error, that int[] in customers cannot be defined as a simple int.
Same goes when populating my array :
arraylist.add(new songs(ID[0], ...)); // didnt paste other variables
ID[0] is considered a simple int and not a int[].
While I understand the error itself, I don't know what causes it nor how to make java use my array of customers within the arrayList of Object defined in songs.
Thanks in advance !
If you want to send an array through subclass constructor you must first have a non-static (instance) array field in your super class, like this:
private int[] ids;
Be noticed that in java the fields are usually defined in camel case format.
Also you have a syntax error in this line:
super(ID[0])
You are referencing the int parameter defined in songs constructor as if an array, that is not correct.
Your call on super(ID[0]); is wrong: it calls the constructor of your members class, sending to it an int rather than an int[] as specified by your constructor. Moreover, I believe this.ID = ID[]; is wrong as well: "ID[]" in this context doesn't represent anything.
Also, as mentioned, static is probably not the good approach: it means that all Objects of type "Members" will share the same one-and-unique attribute "ID[]"!
More code would help. Especially about your songs, and the "arraylist" you're talking about.
I'm trying to use a class to represent the data that is inputted into an array list. The data inputted contains a string, E30, another string, 1985, then a variable contained in the swithc statement, ratingE30.
I can't get the class to work with the arraylist. If I leave the strings without quotation marks I get a cannot resolve symbol error yet with them it doesnt work either as it says the string is not compatible with my class Data.
Any help would be appreciated.
ArrayList located in public static void main(String[] args ):
ArrayList<Data> arrayListToFile = new ArrayList<Data>();
arrayListToFile.add(new Data[]{"E30",1985,ratingE30});
Data class for the ArrayList located in Main:
private static class Data{
String Model;
String ModelYear;
Data(String Model,String ModelYear){
this.Model=Model;
this.ModelYear=ModelYear;
}
}
I think you want
arrayListToFile.add(new Data("E30",1985,ratingE30));
Although that will only work if you add an appropriate constructor to your Data class.
Firstly you said that you are trying to use the class to represent the data, It has two fields, where is the rating field(or what do you want to do with ratingE30?)?
Maybe what you want is something like this
private static class Data{
String model;
String modelYear;
String rating; // I declared it as String because i have no idea what it contains
Data(String model, String modelYear, String rating){
this.model = model;
this.modelYear = modelYear;
this.rating = rating;
}
}
Secondly if you want to have a List of Data objects you should add Data objects to your list!
For example (using the extended class from above):
ArrayList<Data> arrayListToFile = new ArrayList<Data>();
arrayListToFile.add(new Data("E30", "1985", ratingE30);
Looking at your code I am not sure what did you want with the Data[] array, but the way you initialized it was wrong as well, Data[] array just like the ArrayList requies Data objects but what you passed were just a String, an int and i am not sure about the last.
new Data[] {new Data("E30", "1985", ratingE30)};
If you are not sure how objects/arrays work read more about them
I have 2 java classes, one being color.java and the other being size.java. The color class has my SQL statement pulling from multiple tables and my result set. What I'm trying to do is pass in the itemno and description from color into size. Once I pass those values into size.java it will do additional logic and then come back to color.java to finish.
I've tried using something like this:
public void getValues(String color.rs.itemno, String color.rs.description){
return itemno;
return description;
}
I'm new to java so I may not be on the right track, but looking at other examples I think it goes something like the above.
Okay so there are a couple of things wrong with the above code:
Currently, you have what is known as a mutator method. This is a method which does not return a value. Instead this is used to perform operations within an object, usually passing several parameters through it. In order to return a value, you will make use of an accessor method. For this, you need to state the data type you wish to return.
Next, you have named your variables incorrectly. You may wish to look at this document for the naming conversions here: https://www.javatpoint.com/java-naming-conventions What you have created now, are temporary variables only accessible within that method.
Lastly, you cannot return more than one variable at once. The nearest path will be taken and then the code stops running from there. So in your case, you would only be returning itemno and then the code will stop.
Here is an example how the code should look like keeping the above in mind:
String itemDescription;
int itemNumber;
public void setItemNo(int in)
{
itemNumber = in;
}
public void setItemDescription(String id)
{
itemDescription = id;
}
public int getItemNo()
{
return itemNumber;
}
public String getItemDescription()
{
return itemDescription;
}
I would however recommend making use of a constructor to set these values in the beginning:
public ClassName(int in, String id)
{
itemNumber = in;
itemDescription = id;
}
you need to collect all values from a result set in a container, array or arraylist or other, loop through them and then pass whatever you need to your function. Seen here
(String color.rs.itemno, String color.rs.description)
can should be changed to
(String itemno, String description)
I'm facing problem while trying to sort an ArrayList of custom object. In fact, after the sorting, nothing has change in my ArrayList. Is something wrong with my method?
Here's my Artist custom object property :
public class Artist {
String mNickname;
String mName;
String mDescription;
String mScene;
String mDay;
String mTime;
String mImageURL;
Date mDate;
// getters and setters below like getDate() for mDate...
And here's the method use to sort :
static public ArrayList<Artist> sortArrayByDate(ArrayList<Artist> list) {
Collections.sort(list, new Comparator<Artist>() {
#Override
public int compare(Artist lhs, Artist rhs) {
if (lhs.getDate().getTime() < rhs.getDate().getTime())
return -1;
else if (lhs.getDate().getTime() == rhs.getDate().getTime())
return 0;
else
return 1;
}
});
return list;
}
I know this topic as been discuss many time on StackOverflow, but I can't find why I'm not able to make it work properly. Thanks for your understanding
EDIT : Dates (java.util.date) are create using SimpleDateFormatter
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CANADA_FRENCH);
Why not simply use Date#compareTo() for the comparison since java.util.Date implements the Comparable interface.
It is not necessary for the method to return an instance of the List after it is sorted because the underlying List object will be modified by invoking sort. Basically, the method is invoked by passing a reference value as an argument. So when modifications are made, the changes are reflected on the underlying object pointed to by the reference value. With this approach, the code simply passes the List into the method and then continues using the same reference in the proceeding code, which will point to an underlying List which has been sorted.
Another item to consider is modifying the method to accept an argument of the type Listas opposed to ArrayList, since List is an interface, hence more abstract. This would allow the code to switch the implementation of List being passed to the method. This is important because ArrayList does not guarantee the order of the items in the list is maintained. To guarantee the order of items in the List is maintained used LinkedList.
static public void sortArrayByDate(List<Artist> list) {
Collections.sort(list, new Comparator<Artist>() {
#Override
public int compare(Artist lhs, Artist rhs) {
return lhs.getDate().compareTo(rhs.getDate());
}
});
}
Here is a GitHub Gist I created, that show this method in action, with a complete working example.
I'm having a lot trouble trying to pass my list and using the .get(index) method. It keeps saying "incompatible data type" but I don't know how to make an array list get strings. Can you help? Here's my method:
//a mutator method to store the password list
public void setPasswordList(String newPasswordList)
{
ArrayList<String> pL = new ArrayList<String>(); //intalize array list store it into a list
while(true)
{
pL.add(getUserPassword());
passwordList = newPasswordList;
}
Getter method:
public String getPasswordList(){
return passwordList;
}
The line pL.add(getUserPassword()); will throw an error if the signature of your getUserPassword() function does not specify String as its return type, or a type castable to String.
So, you probabaly want to transform your ArrayList pL into a string by concatenating its elements, or maybe you could even discard the array list variable since anyway you want a string to be returned.
For example:
public void setPasswordList(String newPasswordList) {
while(true) {
passwordList = passwordList + ", " + getUserPassword();
// Hope there is some code to escape from this loop :)
}
}