So i'm trying to add items (which have to be static) to an ArrayList using this class template:
AllEventInformationStatic.java:
public class AllEventInformationStatic {
public static int id;
public static String name;
public static String type;
public static String date;
public static String desc;
public static String location;
public AllEventInformationStatic(int id, String name, String type, String date, String desc, String location)
{
AllEventInformationStatic.id = id;
AllEventInformationStatic.name = name;
AllEventInformationStatic.type = type;
AllEventInformationStatic.date = date;
AllEventInformationStatic.desc = desc;
AllEventInformationStatic.location = location;
}
}
AllEventResponseStatic.java:
public class AllEventResponseStatic {
public static ArrayList<AllEventInformationStatic> events;
}
And here is the iteration to fill the ArrayList:
AllEventResponseStatic.events = new ArrayList<AllEventInformationStatic>();
for (int i = 0; i < allEventResponse.events.size(); i++)
{
AllEventResponseStatic.events.
add(new AllEventInformationStatic(42, "bowling",
"event", "11/12/2015",
"enjoy it", "paris"));
String name = AllEventResponseStatic.events.get(0).name;
}
String name_bis = AllEventResponseStatic.events.get(0).name;
So the variable name display "bowling" but name_bis is Null.
it seems like it just clear the whole arraylist after the iteration and I have don't know why..
If you have any idea where the problem is?
Assuming you mean allEventResponseStatic in loop condition and not allEventResponse.
AllEventResponseStatic.events = new ArrayList<AllEventInformationStatic>();
After this call the size of list is zero so loop is never called. Hence you get null on index 0 after the loop
for (int i = 0; i < allEventResponseStatic.events.size(); i++)
{
AllEventResponseStatic.events.
add(new AllEventInformationStatic(42, "bowling",
"event", "11/12/2015",
"enjoy it", "paris"));
String name = AllEventResponseStatic.events.get(0).name;
}
Also, please research what static keyword does, as it is useless here and causes far bigger problems in your code.
Related
I have some codes that fetch some data from my API. My question is how can I list all the objects that I fetched before without using this jsonData.get(0), I expect something like jsonData.get(i), so I assume using something like below, but I can't use it, so how can I do that? Thanks.
for (int i=0;i<jsonData.length();i++){
MainActivity.java
List<Promo> jsonData = response.body();
Log.i("TESTER",""+jsonData);
String promoID = jsonData.get(0).getId_promo();
String promoTipe = jsonData.get(0).getPromo_type();
String promoValue = jsonData.get(0).getValue_based();
String promoName = jsonData.get(0).getPromo_name();
With POJO class that looks like this
Promo.java
public class Promo {
#SerializedName("id_promo")
private String id_promo;
#SerializedName("promo_name")
private String promo_name;
#SerializedName("promo_type")
private String promo_type;
#SerializedName("value_based")
private String value_based;
#SerializedName("quota")
private String quota;
#SerializedName("id_event")
private String id_event;
#SerializedName("description")
private String description;
public String getId_promo() {
return id_promo;
}
public void setId_promo(String id_promo) {
this.id_promo = id_promo;
}
public String getPromo_name() {
return promo_name;
}
}
ApiUrl.java
#FormUrlEncoded
#POST("promopublic")
Call<List<Promo>> getPromo(
#Field("id_event") String id_event,
#Field("total_buyer") String totalBuyer,
#Field("id_user") String id_user,
#Field("id_ticket") String id_ticket);
Using for loop like below solved my problem
for (int i=0;i<jsonData.size();i++){}
I do use strust-json library for converting java object to json automatically. The task is to provide the following output from the server to client:
{
"results":
{
"id": 1,
"text": "Option 1"
},
{
"id": 2,
"text": "Option 2"
}
}
I've created object with array properties:
public class ResultsOrganisationUnit {
private Integer[] id = new Integer[100];
private String[] text = new String[100];
public Integer[] getId() {
return id;
}
public void setId(Integer[] id) {
this.id = id;
}
public String[] getText() {
return text;
}
public void setText(String[] text) {
this.text = text;
}
}
Initialized it:
results = new ResultsOrganisationUnit();
and then later I tried to fill it out using for-each cycle:
for (OrganisationUnitNameHistory children : children2){
results.setId(new Integer[] {children.getOrganisationunitCode()});
results.setText(new String[] {children.getName()});
}
The thing is, I only get the last value of array in the output from client side.
{"results":{"id":[3509],"text":["text 1"]}}
However, the object children for example has all 5 values. It seems like I'm overriding the same array value each time, instead of filling out the new one. I'm confused where is that logical error, which I'm making. It must be something simple..
You should wrap id and text into new class, and store collection of them inside result:
public class OrganisationUnit {
private Integer id;
private String text;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
public class Results {
private List<OrganisationUnit> results = new ArrayList<>();
public List<OrganisationUnit> getResults() {
return results;
}
public void setResults(List<OrganisationUnit> results) {
this.results = results;
}
}
Fill it using loop:
Results results = new Results();
for (OrganisationUnitNameHistory children : children2) {
OrganisationUnit ou = new OrganisationUnit();
ou.setId(children.getOrganisationunitCode());
ou.setText(children.getName());
results.getResults().add(ou);
}
Or directly without using Result class:
List<OrganisationUnit> results = new ArrayList<>();
for (OrganisationUnitNameHistory children : children2) {
OrganisationUnit ou = new OrganisationUnit();
ou.setId(children.getOrganisationunitCode());
ou.setText(children.getName());
results.add(ou);
}
You are getting the last value, because that is what you ask your code to do.
I am not sure what kind of variabel the children2 is, but lets say its a List<ResultsOrganisationUnit> then one solution would be to:
private Integer[] ids = new Integer[100];
private String[] texts = new String[100];
for ( int i=0; i < children2.size(); i++) {
ids[i] = children2[i].getOrganisationunitCode();
texts[i] = children2[i].getName();
}
results.setId(ids);
results.setText(texts);
But still the task as you are referring to is not accomplished by your code.
What you will be looking at is something similar to the following, depending on the values you provide:
{
"results":
{
"id":[1, 2, 3],
"text":["text 1", "text 2", "text 3"]
}
}
To be able to get what you are asking for in the comment is to create your OrganisationUnit like this:
public class OrganisationUnit{
private Integer id;
private String text;
public Integer getId(){return id;}
public void setId(Integer id){this.id = id;}
public String getText(){return text;}
public void setText(String text){this.text = text;}
}
And then store the values for the results in a List<OrganisationUnit>
List<OrganisationUnit> results = new ArrayList();
for (OrganisationUnitNameHistory child : children2) {
OrganisationUnit tempChild = new OrganisationUnit();
tempChild.setId(child.getOrganisationunitCode());
tempChild.setText(child.getName());
results.add(tempChild);
}
The results that you return should be according what you are looking for in the comment field.
The structure of your json does not follow the pattern, since results, so you left it look like, should be an array.
See that https://www.json.org/.
What could be done would be the following structure:
{
results:
[
{"id": 1, "text": "Option 1"},
{"id": 2, "text": "Option 2"}
]
}
You need to put in your array a value, however you are always updating your references to a new array:
...
private Integer[] id = new Integer [100];
...
public void setId(Integer[] id){
// here you are adding the reference to a new array, overwriting your id reference to which you started with a new Integer[100]
this.id = id;
}
In order for the array to store the ids you may need a new property to store the current position. And your setId should get a reference to an Integer instead of an Integers Array, and add to this array the value.
private Integer[] id = new Integer[100];
private int nextPosition = 0;
...
// I omit the treatment here so that it does not add a position beyond what its array allows for simplification purposes.
public void setId(Integer[] id) {
this.id[nextPosition] = id;
nextPosition = nextPosition + 1;
}
...
So you would persist more values, but from what I understood is not exactly what you need, since the structure of the outcome would continue to be the same for which you are complaining:
// No association between ids and texts
{
"results":
{
"id": [3509, 8987, 1234, 777, 987],
"text": ["text 1", "text 2", "text 3"]
}
}
Note that results is an array of a complex object, not a Value Object such as String and Integer. Perhaps the ideal would be you to create a new object to behave and associate the id and text properties.
public class ResultsOrganisationChild {
private Integer id;
private String text;
public ResultsOrganisationChild(Integer id, String text){
this.id = id;
this.text = text;
}
// add some gets and sets
}
Optionally, you could use a List instead of an array, because then you will not have to worry about your object growing beyond what you might have initially foreseen, besides not having to worry about the next position:
public class ResultsOrganisationUnit {
private List<ResultsOrganisationChild> list = new ArrayList<>();
public void addChild(ResultsOrganisationChild child) {
list.add(child);
}
public List<ResultsOrganisationChild> getChild() {
return this.list;
}
}
Your for-each would look like this:
ResultsOrganisationUnit results = new ResultsOrganisationUnit();
for(OrganizationUnitNameHistory children: children2) {
ResultsOrganisationChild child = new ResultsOrganisationChild (children.getOrganisationunitCode(), children.getName());
results.addChild(child);
}
I need your help in changing the value of a boolean variable based on the available values in a List. I defined a class called Student:
public class Student {
private Integer id;//Getter and Setter
private String name;//Getter and Setter
private String location;//Getter and Setter
private String remarks;//Getter and Setter
private boolean disable;//Getter and Setter
public Student(Integer id, String name, String location, String remarks, boolean disable){
this.id = id;
this.name = name;
this.location = location;
this.remarks=remarks;
this.disable=disable;
}
By default in the bean, the value of the disable is true. In the program, I have two lists which are employeeList and selectedEmployees. The employeeList has the values and the selectedEmployees List has the selected values:
private List<Student> employeeList = new ArrayList<Student>();
private List<Student> selectedEmployees;
private boolean disable;
#PostConstruct
public void init() {
//add Employees
disable=true;
Student w1 = new Student(111, "AAAA", "ZZZZ", "", disable);
Student w2 = new Student(222, "CCCCC", "ZZZZZ", "OUT", disable);
Student w3 = new Student(333, "BBBBBB", "YYYYYYY", "IN", disable);
employeeList.add(w1);
employeeList.add(w2);
employeeList.add(w3);
}
However, I am having a method which is called EnableInputText that will be called to check if any of the above values is in the selectedEmployees List, then it should change the value of the disable variable to false:
public void EnableInputText(SelectEvent event) {
for(int i=0;i<=selectedEmployees.size();i++){
for(int j=0;j<=employeeList.size();j++){
if(selectedEmployees.get(i).getId().equals(employeeList.get(j).getId()))
{
selectedEmployees.get(j).setDisable(false);
break;
}
}
}
}
But with the above code, I am getting the error:
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 at
java.util.ArrayList.RangeCheck(ArrayList.java:547) at
java.util.ArrayList.get(ArrayList.java:322)
selectedEmployees.get(j).setDisable(false);
i think you meant to use i instead of j for that line?
or on the flip side probably:
employeeList.get(j).setDisable(false);
so i have a three class video store GUI and it is supposed to save records of videos in stock. however it saves the video objects using serialization but for some reason ,even though i am not getting any errors, only the numerical values are making it through..
notice how the leftmost three columns and the rightmost column are all empty. this is because they are meant to have strings in them, and yet they dont...
as i said im not getting any errors so this truly confuses me.
constructor of VideoStore.java(the GUI class):
public VideoStore() {
initComponents();
model = (DefaultTableModel)displayVideos.getModel();
try{
BinaryFile = new BinaryFile();
BinaryFile.load();
}
catch(Exception e){
}
for(int j = 1; j < BinaryFile.videosList.size(); j ++) {
Video load = (Video)BinaryFile.videosList.get(j);
String tempName = load.getVideoName();
String tempProd = load.getProducer();
String tempRat = load.getRating();
String tempGenre = load.getGenre();
short tempNum = load.getVidNum();
float tempPrice = load.getvideoPrice();
try {
Object[] row = {ID, tempName, tempProd, tempGenre, tempPrice, tempNum, tempRat};
model.addRow(row);
} catch(Exception e){
}
ID++;
}
}
and then the BinaryFile class that i use to handle the .ser file:
public void load(){
try
{
FileInputStream fileIn = new FileInputStream("/Users/hanaezz/Desktop/output.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
videosList = (ArrayList)in.readObject();
in.close();
fileIn.close();
} catch(Exception i)
{
i.printStackTrace();
return;
}
}
public static void adderoo(Video v) {
videosList.add(v);
}
finally, the video class that is in the ArrayList:
private static String videoName;
private static String producer;
private static String rating;
private static String genre;
private short videoNumber;
private float videoPrice;
Static variabled are NOT serialized, you should put:
private String videoName;
private String producer;
private String rating;
private String genre;
private short videoNumber;
private float videoPrice;
in your video class.
The only static variable you should put in a Serializable class is serialVersionUID (which is used by the serialization and deserialization process). As in:
private static final long serialVersionUID = 1L;
I have these codes:
public class CentroImpl implements Centro {
//Atributos
private String nombre;
private String direccion;
private Integer numeroPlantas;
private Integer numeroSotanos;
public Set<Espacio> espacio;
//Constructor
public CentroImpl(String nombre, String direccion, Integer numeroPlantas, Integer numeroSotanos){
checkPlantas(numeroPlantas);
checkSotanos(numeroSotanos);
this.nombre = nombre;
this.direccion = direccion;
this.numeroPlantas = numeroPlantas;
this.numeroSotanos = numeroSotanos;
this.espacio = new TreeSet<Espacio>();
}
#Override
public Set<Despacho> getDespachos() {
}
getDespacho is supposed to go through the list of 'Espacios' (places) in a building (centro) and tell me how many of them are Despachos (offices). As you can see in Espacio class there is a type defined.
public class EspacioImpl implements Espacio {
//Atributos
private TipoEspacio tipo;
private String nombre;
private Integer planta;
private Integer aforo;
//Constructores
public EspacioImpl(TipoEspacio tipo, String nombre, Integer planta, Integer aforo) {
checkerAforo(aforo);
this.nombre = nombre;
this.planta = planta;
this.aforo = aforo;
this.tipo = tipo;
}
But I have not learned yet how to access it, and I haven't been able to find anything understandable around. Thank you for your help.
Assuming Despacho extends Espacio and TipoEspacio is enum:
#Override
public Set<Despacho> getDespachos() {
Set<Despacho> despachos = new HashSet<Despacho>();
for (Espacio e : espacio) {
// Not sure, depends on the definition of TipoEspacio
if (e.getTipo() == TipoEspacio.DESPACHO && e instanceof Despacho) {
despachos.put((Despacho)e);
}
}
return despachos;
}
This answer assumes that you have a collection of EspacioImpls called espacios, and that the enum name for a Despacho is Despacho. You then have to do something with numDespachos (like return it). This also assumes that EspacioImpl has a method called getTipo. You need this because the tipo member is private, and so it cannot be accessed outside the class without having a getter.
int numDespachos = 0;
for(EspacioImpl e : espacios)
{
if(e.getTipo() == TipoEspacio.Despacho)
++numDespachos;
}