I get java.io.IOException: java.lang.NullPointerException: Argument Error: Parameter url is null.
xhtml file:
<p:dataTable var="vehicleTransactionList" value="#{viewCompanyManagedBean.vehicleTransactionList}">
<p:column headerText="#{messages.saptrn}">
<h:outputText value="#{vehicleTransactionList.vehicleTransactionId}" />
</p:column>
<p:column headerText="#{messages.scalepics}">
<p:contentFlow value="#{viewCompanyManagedBean.vehicleTransactionList}" var="newimage">
<p:graphicImage value="#{newimage.imageLocations}" styleClass="content" />
<div class="caption">#{newimage.imageLocations}</div>
</p:contentFlow>
</p:column>
</p:dataTable>
The error is on the 2nd column #{newimage.imageLocations}
Managed Bean:
package com.company.beans;
import com.company.entities.Company;
import com.company.entities.Scale;
import com.company.entities.ScaleMeasurement;
import com.company.entities.VehicleTransaction;
import com.company.services.db.ScaleMeasurementService;
import com.company.services.db.ScaleService;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.primefaces.event.SelectEvent;
import sunw.io.Serializable;
#SuppressWarnings("deprecation")
#ManagedBean
#ViewScoped
public class ViewCompanyManagedBean implements Serializable {
static Logger webRecySys = null;
static {
webRecySys = Logger.getLogger("com.company.webRecySys");
}
public ViewCompanyManagedBean() {
}
#PostConstruct
public void populateCompanyData() {
prepareData(new Date());
images = new ArrayList<String>();
for (int i = 1; i <= 7; i++) {
images.add("file_" + i + ".jpg");
}
}
#PostConstruct
public void onDateSelect(SelectEvent event) throws UnknownHostException {
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String date = format.format(event.getObject());
try {
Date selectedDate = format.parse(date);
prepareData(selectedDate);
} catch (ParseException e) {
e.printStackTrace();
}
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO, "Date Selected",format.format(event.getObject())));
}
private void prepareData(Date forData) {
ScaleService ss = new ScaleService();
ScaleMeasurementService sms = new ScaleMeasurementService();
Scale right = ss.find(getRightScale());
Scale left = ss.find(getLeftScale());
this.measurements = sms.getMeasurementForScale(right,forData);
this.measurements.addAll(sms.getMeasurementForScale(left,forData));
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
this.fileName = "Shredder_Measurements_"+ sdf.format(forData);
for ( ScaleMeasurement s : measurements ) {
if ( s.getScale().getScaleId().equalsIgnoreCase(rightScale) ) {
this.rightScaleMeasurementSum += s.getMeasurement();
}
if ( s.getScale().getScaleId().equalsIgnoreCase(leftScale) ) {
this.leftScaleMeasurementSum += s.getMeasurement();
}
}
vehicleTransactionList = getVehicleTransactionList( sdf.format(forData) , (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest() );
}
private ArrayList<VehicleTransaction> getVehicleTransactionList(String fileDateFormat,HttpServletRequest request) {
ResourceBundle resourceb = ResourceBundle.getBundle("com.company.messages.image");
String imgRootPath = resourceb.getString("imagerootpath");
ArrayList<VehicleTransaction> images = new ArrayList<VehicleTransaction>();
String name = request.getLocalName();
if ( name != null ) {
if ( name.startsWith("0") ) {
name = "localhost";
}
}
else {
name = "localhost";
}
Scale scale = new ScaleService().find("01");
Company c = new ScaleService().getCompanyFromScale(scale);
String companyName = c.getCompanyName().trim().replace(" ", "_");
String URL = "http://"+name+":"+request.getLocalPort()+imgRootPath+"/"+companyName+"/"+fileDateFormat+"/";
ArrayList<String> picUrls = new ArrayList<String>();
Document doc;
try {
doc = Jsoup.connect(URL).get();
for (Element file : doc.select("a")) {
String urlPathToFile = file.attr("href");
String fileName = file.text();
if ( urlPathToFile.endsWith(".jpg") && fileName.endsWith(".jpg") ) {
String picUrl = "http://"+name+":"+request.getLocalPort()+imgRootPath+"/"+companyName+"/"+fileDateFormat+"/"+fileName;
picUrls.add(picUrl);
}
}
} catch (IOException e) {
webRecySys.logp(Level.WARNING, this.getClass().getCanonicalName() , "getAllImagesList", "Cannot get list of Images: "+e.getMessage() );
}
ArrayList<String> vehicleTransactionIdList = getVehicleTransactionIds(picUrls);
for ( String vehicleTransactionId : vehicleTransactionIdList) {
ArrayList<String> imagesForTransaction = getVehicleTransaction(vehicleTransactionId,picUrls);
VehicleTransaction s = new VehicleTransaction(imagesForTransaction, vehicleTransactionId);
images.add(s);
}
return images;
}
private ArrayList<String> getVehicleTransaction(String vehicleTransactionId,ArrayList<String> picUrls) {
ArrayList<String> imagesForTransaction = new ArrayList<String>();
for (String url : picUrls) {
if ( url.contains(vehicleTransactionId)) {
imagesForTransaction.add(url);
}
}
return imagesForTransaction;
}
private ArrayList<String> getVehicleTransactionIds(ArrayList<String> picUrls) {
ArrayList<String> vehicleTransactionIds = new ArrayList<String>();
for ( String pic : picUrls ) {
String vehicleTransactionId = pic.substring(pic.lastIndexOf("/")+1);
vehicleTransactionId = vehicleTransactionId.substring(0,vehicleTransactionId.indexOf("_"));
if ( !existsInArl(vehicleTransactionId,vehicleTransactionIds) ) {
vehicleTransactionIds.add(vehicleTransactionId);
}
}
return vehicleTransactionIds;
}
private boolean existsInArl (String s , ArrayList<String> arl) {
boolean exists = false;
for ( String c : arl ) {
if ( c.equalsIgnoreCase(s) ) {
exists = true;
}
}
return exists;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<ScaleMeasurement> getMeasurements() {
return measurements;
}
public void setMeasurements(List<ScaleMeasurement> measurements) {
this.measurements = measurements;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public String getRightScale() {
return rightScale;
}
public void setRightScale(String rightScale) {
this.rightScale = rightScale;
}
public String getLeftScale() {
return leftScale;
}
public void setLeftScale(String leftScale) {
this.leftScale = leftScale;
}
public int getRightScaleMeasurementSum() {
return rightScaleMeasurementSum;
}
public void setRightScaleMeasurementSum(int rightScaleMeasurementSum) {
this.rightScaleMeasurementSum = rightScaleMeasurementSum;
}
public int getLeftScaleMeasurementSum() {
return leftScaleMeasurementSum;
}
public void setLeftScaleMeasurementSum(int leftScaleMeasurementSum) {
this.leftScaleMeasurementSum = leftScaleMeasurementSum;
}
public ArrayList<VehicleTransaction> getVehicleTransactionList() {
return vehicleTransactionList;
}
public void setVehicleTransactionList(
ArrayList<VehicleTransaction> vehicleTransactionList) {
this.vehicleTransactionList = vehicleTransactionList;
}
// Used for Calendar
private Date date;
// Used for Shredder Measurements
private List<ScaleMeasurement> measurements = new ArrayList<ScaleMeasurement>();
private String fileName;
private String rightScale = "02";
private String leftScale = "03";
private int rightScaleMeasurementSum;
private int leftScaleMeasurementSum;
// Used for Pictures
private List<String> images;
private ArrayList<VehicleTransaction> vehicleTransactionList = new ArrayList<VehicleTransaction>();
private static final long serialVersionUID = 7449888248791054139L;
}
VehicleTransaction Pojo:
package com.company.entities;
import java.util.ArrayList;
public class VehicleTransaction {
public VehicleTransaction() {
}
public VehicleTransaction(ArrayList<String> imageLocations, String vehicleTransactionId) {
super();
this.imageLocations = imageLocations;
this.vehicleTransactionId = vehicleTransactionId;
}
public ArrayList<String> getImageLocations() {
return imageLocations;
}
public void setImageLocations(ArrayList<String> imageLocations) {
this.imageLocations = imageLocations;
}
public String getVehicleTransactionId() {
return vehicleTransactionId;
}
public void setVehicleTransactionId(String vehicleTransactionId) {
this.vehicleTransactionId = vehicleTransactionId;
}
private ArrayList<String> imageLocations;
private String vehicleTransactionId;
}
What's my mistake?
resolved - the right xhtml code is:
<p:column headerText="#{messages.scalepics}">
<p:contentFlow value="#{vehicleTransactionList.imageLocations}" var="images">
<p:graphicImage value="#{images}" styleClass="content" />
<div class="caption">#{images}</div>
</p:contentFlow>
</p:column>
Whereas the wrong code was:
<p:contentFlow value="#{viewCompanyManagedBean.vehicleTransactionList}" var="newimage">
<p:graphicImage value="#{newimage.imageLocations}" styleClass="content" />
<div class="caption">#{newimage.imageLocations}</div>
Related
This is my JSP file
<html>
<head>
<title>Todo's for ${name}</title>
</head>
<body>
<h1>Your ToDo's</h1>
<table>
<caption>Your Todo's are as follows:</caption>
<thead>
<tr>
<th>Description</th>
<th>Target Date</th>
<th>Is it completed?</th>
</tr>
</thead>
<tbody>
<th:block th:each="todo : ${todos}">
<tr>
<td th:text="${todo.desc}"></td>
<td th:text="${todo.targetDate}"></td>
<td th:text="${todo.done}"></td>
</tr>
</th:block>
</tbody>
</table>
<br/>
Add Todo
</body>
</html>
This is my TodoService.java file
package com.example.springboot.demo.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Service;
import com.in28minutes.springboot.web.model.Todo;
#Service
public class TodoService {
private static List<Todo> todos = new ArrayList<Todo>();
private static int todoCount = 3;
static {
todos.add(new Todo(1, "Prakriti", "Learn Spring MVC", new Date(),
false));
todos.add(new Todo(2, "Prakriti", "Learn Struts", new Date(), false));
todos.add(new Todo(3, "Prakriti", "Learn Hibernate", new Date(),
false));
}
public List<Todo> retrieveTodos(String user) {
List<Todo> filteredTodos = new ArrayList<Todo>();
for (Todo todo : todos) {
if (todo.getUser().equals(user)) {
filteredTodos.add(todo);
}
}
return filteredTodos;
}
public void addTodo(String name, String desc, Date targetDate,
boolean isDone) {
todos.add(new Todo(++todoCount, name, desc, targetDate, isDone));
}
public void deleteTodo(int id) {
Iterator<Todo> iterator = todos.iterator();
while (iterator.hasNext()) {
Todo todo = iterator.next();
if (todo.getId() == id) {
iterator.remove();
}
}
}
}
I have three values in the table but it doesn't retrieve them, can't understand why I have used the thymeleaf block properly only. Below is my TodoController.java file.
package com.example.springboot.demo.controller;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.example.springboot.demo.service.LoginService;
import com.example.springboot.demo.service.TodoService;
#Controller
#SessionAttributes("name")
public class TodoController {
#Autowired
TodoService service;
#RequestMapping(value="/list-todos", method=RequestMethod.GET)
public String showTodosList(ModelMap model) {
String name=(String)model.get("name");
model.put("todos",service.retrieveTodos(name));
return "list-todos";
}
#RequestMapping(value="/add-todos", method=RequestMethod.GET)
public String showaddTodoPage(ModelMap model) {
return "add-todos";
}
#RequestMapping(value="/add-todos", method=RequestMethod.POST)
public String addTodos(ModelMap model, #RequestParam String desc) {
service.addTodo((String)model.get("name"), desc, new Date(), false);
return "redirect:/list-todos";
}
}
This is my Todo.java
package com.in28minutes.springboot.web.model;
import java.util.Date;
public class Todo {
private int id;
private String user;
private String desc;
private Date targetDate;
private boolean isDone;
public Todo(int id, String user, String desc, Date targetDate,
boolean isDone) {
super();
this.id = id;
this.user = user;
this.desc = desc;
this.targetDate = targetDate;
this.isDone = isDone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getTargetDate() {
return targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
public boolean isDone() {
return isDone;
}
public void setDone(boolean isDone) {
this.isDone = isDone;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Todo other = (Todo) obj;
if (id != other.id) {
return false;
}
return true;
}
#Override
public String toString() {
return String.format(
"Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]", id,
user, desc, targetDate, isDone);
}
}
Output:
Please let me know what's needed to be done for the values to be displayed in the table.
Try using,
<tr th:each="todo : ${todos}">
<td th:text="${todo.desc}"></td>
<td th:text="${todo.targetDate}"></td>
<td th:text="${todo.done}"></td>
</tr>
i have i a class StudentAdmissinAssoDTO that have Other class references
as below
StudentAdmissinAssoDTO
package com.rasvek.cg.entity;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonBackReference;
public class StudentAdmissinAssoDTO
{
private PrimaryStudentAdmission primaryAdmission;
private StudentDetails studentDetailsDto;
private StudentJoiningDetails studentJoiningDetails;
private StudentPresentClassDetails studentPresentClassDetails;
private StudentGeneralDetails studentGeneralDetails;
private StudentPrevSchoolDetails studentPrevSchoolDetails;
private StudentParentDetails studentParentDetails;
private MasterAddress masterAddress;
private List<AssocFeeStudent> assocFeeStudentId;
public StudentDetails getStudentDetailsDto() {
return studentDetailsDto;
}
public void ListStudentDetailsDto(StudentDetails studentDetailsDto) {
this.studentDetailsDto = studentDetailsDto;
}
public PrimaryStudentAdmission getPrimaryAdmission() {
return primaryAdmission;
}
public void ListPrimaryAdmission(PrimaryStudentAdmission primaryAdmission) {
this.primaryAdmission = primaryAdmission;
}
public StudentJoiningDetails getStudentJoiningDetails() {
return studentJoiningDetails;
}
public void ListStudentJoiningDetails(StudentJoiningDetails studentJoiningDetails) {
this.studentJoiningDetails = studentJoiningDetails;
}
public StudentPresentClassDetails getStudentPresentClassDetails() {
return studentPresentClassDetails;
}
public void ListStudentPresentClassDetails(StudentPresentClassDetails studentPresentClassDetails) {
this.studentPresentClassDetails = studentPresentClassDetails;
}
public StudentGeneralDetails getStudentGeneralDetails() {
return studentGeneralDetails;
}
public void ListStudentGeneralDetails(StudentGeneralDetails studentGeneralDetails) {
this.studentGeneralDetails = studentGeneralDetails;
}
public StudentPrevSchoolDetails getStudentPrevSchoolDetails() {
return studentPrevSchoolDetails;
}
public void ListStudentPrevSchoolDetails(StudentPrevSchoolDetails studentPrevSchoolDetails) {
this.studentPrevSchoolDetails = studentPrevSchoolDetails;
}
public StudentParentDetails getStudentParentDetails() {
return studentParentDetails;
}
public void ListStudentParentDetails(StudentParentDetails studentParentDetails) {
this.studentParentDetails = studentParentDetails;
}
public MasterAddress getMasterAddress() {
return masterAddress;
}
public void ListMasterAddress(MasterAddress masterAddress) {
this.masterAddress = masterAddress;
}
public List<AssocFeeStudent> getAssocFeeStudentId() {
return assocFeeStudentId;
}
public void ListAssocFeeStudentId(List<AssocFeeStudent> assocFeeStudentId) {
this.assocFeeStudentId = assocFeeStudentId;
}
}
and i am getting this Exception
(http-nio-8017-exec-3:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter):
[org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.logWarningIfNecessary(AbstractJackson2HttpMessageConverter.java:205)]
Failed to evaluate Jackson deserialization for type [[simple type, class com.rasvek.cg.entity.StudentAdmissinAssoDTO]]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': no back reference property found from type [collection type; class java.util.Set, contains [simple type, class com.rasvek.cg.entity.MasterAddress]]
please look at MasterAddress
package com.rasvek.cg.entity;
//Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
/**
* MasterAddress generated by hbm2java
*/
#Entity
#Table(name = "master_address", catalog = "campus_guru_01")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "addressId")
public class MasterAddress implements java.io.Serializable {
private Integer addressId;
private Integer studentAdmissionId;
private String isSame;
private MasterAddressCountry masterAddressCountry;
private MasterAddressDistrict masterAddressDistrict;
private MasterAddressState masterAddressState;
private String houseNum;
private String streetAddress;
private String citymandal;
private String pincode;
private String addressType;
private Set<AssocStaffAddress> assocStaffAddresses = new HashSet<AssocStaffAddress>(0);
private Set<AssocStudentAddress> assocStudentAddresses = new HashSet<AssocStudentAddress>(0);
public MasterAddress() {
}
public MasterAddress(MasterAddressCountry masterAddressCountry, MasterAddressDistrict masterAddressDistrict,
MasterAddressState masterAddressState) {
this.masterAddressCountry = masterAddressCountry;
this.masterAddressDistrict = masterAddressDistrict;
this.masterAddressState = masterAddressState;
}
public MasterAddress(MasterAddressCountry masterAddressCountry, MasterAddressDistrict masterAddressDistrict, MasterAddressState masterAddressState, String houseNum, String streetAddress, String citymandal, String pincode, String addressType, Set<AssocStaffAddress> assocStaffAddresses, Set<AssocStudentAddress> assocStudentAddresses) {
this.masterAddressCountry = masterAddressCountry;
this.masterAddressDistrict = masterAddressDistrict;
this.masterAddressState = masterAddressState;
this.houseNum = houseNum;
this.streetAddress = streetAddress;
this.citymandal = citymandal;
this.pincode = pincode;
this.addressType = addressType;
this.assocStaffAddresses = assocStaffAddresses;
this.assocStudentAddresses = assocStudentAddresses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "address_id", unique = true, nullable = false)
public Integer getAddressId() {
return this.addressId;
}
public void setAddressId(Integer addressId) {
this.addressId = addressId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "country_id", nullable = false)
public MasterAddressCountry getMasterAddressCountry() {
return this.masterAddressCountry;
}
public void setMasterAddressCountry(MasterAddressCountry masterAddressCountry) {
this.masterAddressCountry = masterAddressCountry;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "district_id", nullable = false)
public MasterAddressDistrict getMasterAddressDistrict() {
return this.masterAddressDistrict;
}
public void setMasterAddressDistrict(MasterAddressDistrict masterAddressDistrict) {
this.masterAddressDistrict = masterAddressDistrict;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "state_id", nullable = false)
public MasterAddressState getMasterAddressState() {
return this.masterAddressState;
}
public void setMasterAddressState(MasterAddressState masterAddressState) {
this.masterAddressState = masterAddressState;
}
#Column(name = "house_num", length = 45)
public String getHouseNum() {
return this.houseNum;
}
public void setHouseNum(String houseNum) {
this.houseNum = houseNum;
}
#Column(name = "street_address", length = 45)
public String getStreetAddress() {
return this.streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
#Column(name="citymandal")
public String getCitymandal() {
return this.citymandal;
}
public void setCitymandal(String citymandal) {
this.citymandal = citymandal;
}
#Column(name = "pincode", length = 45)
public String getPincode() {
return this.pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
#Column(name = "address_type", length = 9)
public String getAddressType() {
return this.addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "masterAddress")
public Set<AssocStaffAddress> getAssocStaffAddresses() {
return this.assocStaffAddresses;
}
public void setAssocStaffAddresses(Set<AssocStaffAddress> assocStaffAddresses) {
this.assocStaffAddresses = assocStaffAddresses;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "masterAddress")
public Set<AssocStudentAddress> getAssocStudentAddresses() {
return this.assocStudentAddresses;
}
public void setAssocStudentAddresses(Set<AssocStudentAddress> assocStudentAddresses) {
this.assocStudentAddresses = assocStudentAddresses;
}
#Column(name="student_admission_id")
public Integer getStudentAdmissionId() {
return studentAdmissionId;
}
public void setStudentAdmissionId(Integer studentAdmissionId) {
this.studentAdmissionId = studentAdmissionId;
}
#Column(name="is_same")
public String getIsSame() {
return isSame;
}
public void setIsSame(String isSame) {
this.isSame = isSame;
}
}
there is no dependency Dependency Between StudentAdmissinAssoDTO and MasterAddress .
i am just using StudentAdmissinAssoDTO to make nested json objects .
so that i can get them in the controller
like bellow
MasterAddress masterAddress =null;
masterAddress = studentAdmissinAssoDTO.getMasterAddress();
why i am getting this Exception
(http-nio-8017-exec-3:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter): [org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.logWarningIfNecessary(AbstractJackson2HttpMessageConverter.java:205)]
Failed to evaluate Jackson deserialization for type [[simple type, class com.rasvek.cg.entity.StudentAdmissinAssoDTO]]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': no back reference property found from type [collection type; class java.util.Set, contains [simple type, class com.rasvek.cg.entity.MasterAddress]
can any one Explain why its happening so. thank you!.
i found my mistake there was i misplace of #JsonManagedReference in MasterDistrict Class of MasterAddress
I'm working on an application and I need to save and load data from an ObservableArrayList to an XML file. I've made a model class with Double and Integer Properties for the ObservableList:
package application.Model;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
#XmlRootElement
#XmlType(name = "Object", propOrder = {"diameter", "handeling", "aantal", "basisUren", "correctie", "toeslagUren", "totaalUren", "totaalMat", "totaal"})
public class Berekening {
private final SimpleIntegerProperty diameter;
private final SimpleIntegerProperty handeling;
private final SimpleIntegerProperty aantal;
private final SimpleDoubleProperty basisUren;
private final SimpleDoubleProperty correctie;
private final SimpleDoubleProperty toeslagUren;
private final SimpleDoubleProperty totaalUren;
private final SimpleDoubleProperty totaalMat;
private final SimpleDoubleProperty totaal;
public Berekening() {
this(null, null, null, null, null, null, null, null, null);
}
public Berekening(Integer diameter, Integer handeling, Integer aantal, Double basisUren, Double correctie, Double toeslagUren, Double totaalUren, Double totaalMat, Double totaal) {
this.diameter = new SimpleIntegerProperty(diameter);
this.handeling = new SimpleIntegerProperty(handeling);
this.aantal = new SimpleIntegerProperty(aantal);
this.basisUren = new SimpleDoubleProperty(basisUren);
this.correctie = new SimpleDoubleProperty(correctie);
this.toeslagUren = new SimpleDoubleProperty(toeslagUren);
this.totaalUren = new SimpleDoubleProperty(totaalUren);
this.totaalMat = new SimpleDoubleProperty(totaalMat);
this.totaal = new SimpleDoubleProperty(totaal);
}
#XmlElement (name = "value1", required = false)
public Integer getDiameter() {
return diameter.get();
}
public void setDiameter(int diameter) {
this.diameter.set(diameter);
}
public IntegerProperty diameterProperty(){
return diameter;
}
#XmlElement (name = "value2", required = false)
public Integer getHandeling() {
return handeling.get();
}
public void setHandeling(int handeling) {
this.handeling.set(handeling);
}
public IntegerProperty handelingProperty(){
return handeling;
}
#XmlElement (name = "value3", required = false)
public Integer getAantal() {
return aantal.get();
}
public void setAantal(int aantal) {
this.aantal.set(aantal);
}
public IntegerProperty aantalProperty(){
return aantal;
}
#XmlElement (name = "value4", required = false)
public Double getBasisUren(){
return basisUren.get();
}
public void setBasisUren(double value) {
this.basisUren.set(value);
}
public DoubleProperty basisUrenProperty(){
return basisUren;
}
#XmlElement (name = "value5", required = false)
public Double getCorrectie(){
return correctie.get();
}
public void setCorrectie(double value) {
this.correctie.set(value);
}
public DoubleProperty correctieProperty(){
return correctie;
}
#XmlElement (name = "value6", required = false)
public Double getToeslagUren(){
return toeslagUren.get();
}
public void setToeslagUren(double value) {
this.toeslagUren.set(value);
}
public DoubleProperty toeslagUrenProperty(){
return toeslagUren;
}
#XmlElement (name = "value7", required = false)
public Double getTotaalUren(){
return totaalUren.get();
}
public void setTotaalUren(double value) {
this.totaalUren.set(value);
}
public DoubleProperty totaalUrenProperty(){
return totaalUren;
}
#XmlElement (name = "value8", required = false)
public Double getTotaalMat(){
return totaalMat.get();
}
public void setTotaalMat(double value) {
this.totaalMat.set(value);
}
public DoubleProperty totaalMatProperty(){
return totaalMat;
}
#XmlElement (name = "value9", required = false)
public Double getTotaal(){
return totaal.get();
}
public void setTotaal(double value) {
this.totaal.set(value);
}
public DoubleProperty totaalProperty(){
return totaal;
}
}
This is the list class:
package application.Model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
public class BerekeningList {
#XmlElement(name = "berekening")
List<Berekening> berekeningen = new ArrayList<>();
public List<Berekening> getBerekeningen() {
return berekeningen;
}
}
And the ListWrapper:
package application.Model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import application.MainApp;
import application.Util.BerekeningListAdapter;
import javafx.collections.ObservableList;
#XmlRootElement (name = "Berekeningen")
public class BerekeningListWrapper{
private ObservableList<Berekening> berekening;
#XmlJavaTypeAdapter(BerekeningListAdapter.class)
public ObservableList<Berekening> getBerekeningen(){
return berekening;
}
public void setBerekenings(ObservableList<Berekening> berekenings) {
this.berekening = berekenings;
}
}
I use this method to Save the data to a file:
public void saveBerekeningDataToFile(File file) {
try {
JAXBContext context = JAXBContext
.newInstance(BerekeningListWrapper.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
BerekeningListWrapper wrapper = new BerekeningListWrapper();
wrapper.setBerekenings(berekeningData);
m.marshal(wrapper, file);
setBerekeningFilePath(file);
} catch (Exception e) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not save data");
alert.setContentText("Could not save data to file:\n" + file.getPath());
alert.showAndWait();
}
}
And the resulting xml file (the saving seems to work fine):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Berekeningen>
<berekeningen>
<berekening value1="15" value2="5" value3="5" value4="1.25" value5="5.0" value6="6.25" value7="270.0" value8="30.0" value9="300.0"/>
</berekeningen>
The issue is loading the data back into my application, i'm using this method:
public void loadBerekeningDataFromFile(File file){
try {
JAXBContext context = JAXBContext
.newInstance(BerekeningListWrapper.class);
Unmarshaller um = context.createUnmarshaller();
BerekeningListWrapper wrapper = (BerekeningListWrapper)um.unmarshal(file);
berekeningData.clear();
berekeningData.addAll(wrapper.getBerekeningen());
setBerekeningFilePath(file);
} catch (Exception e){
e.printStackTrace();
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Could not load data");
alert.setContentText("Could not load data from file:\n" + file.getPath());
alert.showAndWait();
}
}
Resulting in a stack trace starting with:
javax.xml.bind.UnmarshalException: Unable to create an instance of
application.Model.Berekening
etc
Caused by: java.lang.NullPointerException
at application.Model.Berekening.<init>(Berekening.java:32)
at application.Model.Berekening.<init>(Berekening.java:28)
... 84 more
So the unmarshalexception is caused by a NullPointerException in my model class at the lines:
this.diameter = new SimpleIntegerProperty(diameter);
and
this(null, null, null, null, null, null, null, null, null);
I don't know how I can resolve this issue, I've tried out many different tutorials and answers on StackOverflow, but nothing I found neems to work.
Any help is much appreciated!
You can't initialize a SimpleIntegerProperty with null. The constructor you are calling takes an int, so there is an implicit call ("unboxing") to diameter.intValue() when you call new SimpleIntegerProperty(diameter). Obviously, if diameter is null, this results in a NullPointerException.
Make the default values for the numeric types non-null:
public Berekening() {
this(0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
}
for example.
If you really need to support null values (and this is a less-preferred option, imho) use ObjectProperty instead of IntegerProperty and DoubleProperty:
public class Berekening {
private final ObjectProperty<Integer> diameter;
private final ObjectProperty<Integer> handeling;
private final ObjectProperty<Integer> aantal;
private final ObjectProperty<Double> basisUren;
private final ObjectProperty<Double> correctie;
private final ObjectProperty<Double> toeslagUren;
private final ObjectProperty<Double> totaalUren;
private final ObjectProperty<Double> totaalMat;
private final ObjectProperty<Double> totaal;
public Berekening() {
this(null, null, null, null, null, null, null, null, null);
}
public Berekening(Integer diameter, Integer handeling, Integer aantal, Double basisUren, Double correctie, Double toeslagUren, Double totaalUren, Double totaalMat, Double totaal) {
this.diameter = new SimpleObjectProperty<>(diameter);
this.handeling = new SimpleObjectProperty<>(handeling);
this.aantal = new SimpleObjectProperty<>(aantal);
this.basisUren = new SimpleObjectProperty<>(basisUren);
this.correctie = new SimpleObjectProperty<>(correctie);
this.toeslagUren = new SimpleObjectProperty<>(toeslagUren);
this.totaalUren = new SimpleObjectProperty<>(totaalUren);
this.totaalMat = new SimpleObjectProperty<>(totaalMat);
this.totaal = new SimpleObjectProperty<>(totaal);
}
// ...
}
Below is library app. In its current state, the app is only able to search for single words. Searches like "Harry Potter" yield no result. I was told to use an URLEncoder but I tried and even that didn't work. Below are my java files.'
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<Books>>, SearchView.OnQueryTextListener {
LoaderManager loaderManager;
String mQuery;
SearchView mSearchView;
MenuItem mMenuSearchItem;
private static final String LOG_TAG = MainActivity.class.getName();
private static final String GOOGLE_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?maxResults=40&q=";
private String url = GOOGLE_REQUEST_URL + "android";
private static final int BOOK_LOADER_ID = 1;
private BookAdapter adapter;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView bookListView = (ListView) findViewById(R.id.list);
adapter = new BookAdapter(this, new ArrayList<Books>());
bookListView.setAdapter(adapter);
loaderManager = getLoaderManager();
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Books currentBook = adapter.getItem(position);
Uri bookUri = Uri.parse(currentBook.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookUri);
startActivity(websiteIntent);
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
#Override
public boolean onQueryTextSubmit(String query) {
if(isOnline()){
url = GOOGLE_REQUEST_URL + query;
loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
}else{
Toast.makeText(this, "No Internet Connection Found!", Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mQuery = newText;
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
mMenuSearchItem = menu.findItem(R.id.menu_search);
mSearchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
if (mSearchView != null) {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean queryTextFocused) {
if (!queryTextFocused) {
if (TextUtils.isEmpty(mQuery))
adapter.clear();
}
}
});
}
return true;
}
#Override
public Loader<List<Books>> onCreateLoader(int i, Bundle bundle) {
return new BookLoader(this, url);
}
#Override
public void onLoadFinished(Loader<List<Books>> loader, List<Books> books) {
adapter.clear();
if (books != null && !books.isEmpty()) {
adapter.addAll(books);
}
}
#Override
public void onLoaderReset(Loader<List<Books>> loader) {
adapter.clear();
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
BookUtils.java
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public final class BookUtils {
private static final String LOG_TAG = BookUtils.class.getSimpleName();
private BookUtils() {}
public static List<Books> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {jsonResponse = makeHttpRequest(url);}
catch (IOException e) {Log.e(LOG_TAG, "Problem making the HTTP request.", e);}
List<Books> books = extractFeatureFromJson(jsonResponse);
return books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {url = new URL(stringUrl);}
catch (MalformedURLException e) {Log.e(LOG_TAG, "Problem building the URL ", e);}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {return jsonResponse;}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());}
}
catch (IOException e) {Log.e(LOG_TAG, "Problem retrieving the book JSON results.", e);}
finally {
if (urlConnection != null) {urlConnection.disconnect();}
if (inputStream != null) {inputStream.close();}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Books> extractFeatureFromJson(String bookJSON) {
if (TextUtils.isEmpty(bookJSON)) {return null;}
List<Books> books = new ArrayList<>();
try {
JSONObject jsonResponse = new JSONObject(bookJSON);
JSONArray booksArray = jsonResponse.getJSONArray("items");
for (int i = 0; i < booksArray.length(); i++) {
JSONObject currentBook = booksArray.getJSONObject(i);
JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
JSONArray authorsArray = volumeInfo.getJSONArray("authors");
String title = "", publisher = "", publishedDate = "", language = "", pageCount = "", printType = "", maturityRating = "", authors = "";
if(volumeInfo.has("title")){
language = volumeInfo.getString("language");
}
for (int j = 0; j < authorsArray.length(); j++) {
if (volumeInfo.has("authors")){
authors = authorsArray.getString(j);
}
}
if(volumeInfo.has("publisher")){
publisher = volumeInfo.getString("publisher");
}
if(volumeInfo.has("publishedDate")){
publishedDate = volumeInfo.getString("publishedDate");
}
if(volumeInfo.has("language")){
language = volumeInfo.getString("language");
}
if(volumeInfo.has("pageCount")){
pageCount = volumeInfo.getString("pageCount");
}
if(volumeInfo.has("printType")){
printType = volumeInfo.getString("printType");
}
if(volumeInfo.has("maturityRating")){
maturityRating = volumeInfo.getString("maturityRating");
}
Books book = new Books(title, authors, publisher, publishedDate, language, pageCount, printType, maturityRating);
books.add(book);
}
}
catch (JSONException e) {Log.e("QueryUtils", "Problem parsing the book JSON results", e);}
return books;
}
}
Books.java
public class Books {
private String mTitle;
private String mAuthors;
private String mPublisher;
private String mPublishingDate;
private String mLanguage;
private String mCount;
private String mPrintType;
private String mMaturityRating;
private String mURL;
public Books(String title, String authors, String publisher, String publishingDate, String language, String count, String printType, String maturityRating) {
mTitle = title;
mAuthors = authors;
mPublisher = publisher;
mPublishingDate = publishingDate;
mLanguage = language;
mCount = count;
mPrintType = printType;
mMaturityRating = maturityRating;
}
public String getTitle() {return mTitle;}
public String getAuthors(){return mAuthors;}
public String getPublisher(){return mPublisher;}
public String getPublishedDate(){return mPublishingDate;}
public String getLanguage(){return mLanguage;}
public String getCount(){return mCount;}
public String getPrintType(){return mPrintType;}
public String getMaturityRating(){return mMaturityRating;}
public String getUrl() {return mURL;}
}
BookLoader.java
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.List;
public class BookLoader extends AsyncTaskLoader<List<Books>> {
private static final String LOG_TAG = BookLoader.class.getName();
private String mUrl;
public BookLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {forceLoad();}
#Override
public List<Books> loadInBackground() {
if (mUrl == null) {return null;}
List<Books> books = BookUtils.fetchBookData(mUrl);
return books;
}
}
BookAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Books> {
public BookAdapter(Context context, List<Books> books) {
super(context, 0, books);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {listItemView = LayoutInflater.from(getContext()).inflate(R.layout.book_list_item, parent, false);}
Books currentBook = getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.book_title);
title.setText(currentBook.getTitle());
TextView authors = (TextView) listItemView.findViewById(R.id.book_author);
authors.setText(currentBook.getAuthors());
TextView publisher = (TextView) listItemView.findViewById(R.id.book_publisher);
publisher.setText(currentBook.getPublisher());
TextView publishingDate = (TextView) listItemView.findViewById(R.id.book_publishing_date);
publishingDate.setText(currentBook.getPublishedDate());
TextView language = (TextView) listItemView.findViewById(R.id.book_language);
language.setText(currentBook.getLanguage());
TextView pageCount = (TextView) listItemView.findViewById(R.id.book_page_count);
pageCount.setText(currentBook.getCount());
TextView printType = (TextView) listItemView.findViewById(R.id.book_print_type);
printType.setText(currentBook.getPrintType());
TextView maturityRating = (TextView) listItemView.findViewById(R.id.book_maturity_rating);
maturityRating.setText(currentBook.getMaturityRating());
return listItemView;
}
}
On my onQueryTextSubmit method, I tried replacing url = GOOGLE_REQUEST_URL + query; with:
Uri.Builder uriBuilder = Uri.parse(GOOGLE_REQUEST_URL).buildUpon().appendQueryParameter("q", query);
url = uriBuilder.toString();
But it didn't work.
I have a problem with my adapter. I already succeeded to display some informations from my JSON (codeLieu and libelle) that looks like this:
[
{
"codeLieu": "OTAG",
"libelle": "50 Otages",
"distance": null,
"ligne": [
{
"numLigne": "2"
},
{
"numLigne": "C2"
},
{
"numLigne": "12"
},
{
"numLigne": "23"
}
]
},
...
]
Here is my model:
package material.romain.com.projentreprise.Adapter;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class Response implements Serializable{
private String codeLieu;
private String libelle;
private String distance;
private List<LigneEntities> ligne;
public String getCode() {
return codeLieu;
}
public void setCode(String codeLieu) {
this.codeLieu = codeLieu;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public List<LigneEntities> getLigne() {return ligne;}
public void setLigne(List<LigneEntities> ligne) {
this.ligne = ligne;
}
public static class LigneEntities {
private String numLigne;
public String getLigne() {
return numLigne;
}
public void setLigne(String numLigne) {
this.numLigne = numLigne;
}
}
}
And finally this is my adapter :
package material.romain.com.projentreprise.Adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.iconics.IconicsDrawable;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
import material.romain.com.projentreprise.R;
import material.romain.com.projentreprise.Util.CircularTextView;
import material.romain.com.projentreprise.Util.ColorLigne;
public class ListAdapter extends BaseAdapter implements Filterable {
private ArrayList<Response> arret;
private Context context;
private LayoutInflater inflater;
private MyFilter mFilter;
private ArrayList<Response> mSearchArret;
public ListAdapter(Context mContext, ArrayList<Response> mArretItem) {
this.context = mContext;
this.arret = mArretItem;
this.mSearchArret = mArretItem;
getFilter();
}
#Override
public int getCount() {
return mSearchArret.size();
}
#Override
public Object getItem(int position) {
return mSearchArret.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Response item = (Response) getItem(position);
ColorLigne.ViewHolder holder = null;
if (convertView == null) {
holder = new ColorLigne.ViewHolder();
inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.each_list_item, parent, false);
holder.circleImage = (CircleImageView) convertView.findViewById(R.id.circleView);
holder.textArret = (TextView) convertView.findViewById(R.id.tvListArret);
holder.circle = (CircularTextView) convertView.findViewById(R.id.tvArretColor);
convertView.setTag(holder);
} else {
holder = (ColorLigne.ViewHolder) convertView.getTag();
}
Drawable color = new ColorDrawable(ContextCompat.getColor(context, R.color.tanVert));
Drawable image = new IconicsDrawable(context).icon(FontAwesome.Icon.faw_bus).color(Color.WHITE).sizeDp(48).paddingDp(10);
LayerDrawable ld = new LayerDrawable(new Drawable[]{color, image});
holder.circleImage.setImageDrawable(ld);
holder.textArret.setText(item.getLibelle());
return convertView;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new MyFilter();
}
return mFilter;
}
class MyFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (prefix != null && prefix.length() > 0) {
ArrayList<Response> tempList = new ArrayList<>();
for (Response value : arret) {
if (value.getLibelle().toLowerCase().contains(prefix.toString().toLowerCase())) {
tempList.add(value);
}
}
results.count = tempList.size();
results.values = tempList;
} else {
results.count = arret.size();
results.values = arret;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
try {
mSearchArret = (ArrayList<Response>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
And I would like to get strings from "ligne" but it's in a list and I don't know how to access it. My goal is to put the strings into a circleTextView.
Edit:
I tried this in getView method
Response item = getItem(position);
for(Response value: arret){
value = item;
String ligneItem = value.getLigne().toString();
ColorLigne.setColorLigne(ligneItem, holder, context);
holder.circle.setText(ligneItem);
holder.circle.setStrokeWidth(0);
}
Add below method to your Response.java
public String getItems() {
StringBuilder builder = new StringBuilder();
for (LigneEntities entity : getLigne()) { //loop through every item from the list
builder.append(entity.getLigne() + ","); //add to StringBuilder
}
builder.replace(builder.length() - 1, builder.length(), "");//remove last ,(semicolon)
return builder.toString();
}
setting to your CircleTextView
holder.circle.setText(item.getItems());