Why passed to another activity Serializable object is null - java

I've tried pass object between activities exactly like in How to pass an object from one activity to another on Android
and SerializableTask is creating correctly but when I want to read this in next activity it is null.
Task task = listOfTask.get(position);
Log.i(TAG, "recyclerViewEditTask: edit clicked for title: " +
task.getTitle());
SerializabledTask sTask = new SerializabledTask(task.getTitle(),
task.getDetails(), task.getTimeToDo(), task.getTag(),
task.getId(), task.isDone());
if(sTask == null)
Log.e(TAG, "recyclerViewEditTask: sTask IS NULL");
else {
Log.i(TAG, "recyclerViewEditTask: sTaskInfo: " + sTask.toString());
Intent editIntent = new Intent(ListOfTasksActivity.this, EditTaskActivity.class);
editIntent.putExtra("task", sTask);
startActivity(editIntent);
then it goes to another activity
activity that try to get Serializable object:
Intent i = getIntent();
SerializabledTask sTask = (SerializabledTask) i.getSerializableExtra("task");
if(sTask == null)
Log.e(TAG, "onCreate: sTASK IS NULL" );
and "onCreate: sTASK IS NULL" is calling
when I tried to pass single String it works properly
Serializables class:
public class SerializabledTask implements Serializable {
String title, details, timeToDo, tag;
int id;
boolean done;
Task task;
public SerializabledTask(String title, String details, String timeToDo, String tag, int id, boolean done) {
this.title = title;
this.details = details;
this.timeToDo = timeToDo;
this.tag = tag;
this.id = id;
this.done = done;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getTimeToDo() {
return timeToDo;
}
public void setTimeToDo(String timeToDo) {
this.timeToDo = timeToDo;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
#Override
public String toString() {
return "SerializabledTask{" +
"title='" + title + '\'' +
", details='" + details + '\'' +
", timeToDo='" + timeToDo + '\'' +
", tag='" + tag + '\'' +
", id=" + id +
", done=" + done +
", task=" + task +
'}';
}

Your model class SerializableTask must implement Serializable for your code to work.
public class SerializableTask implements Serializable {
...
}
Also it's highly recommended to use Parcelable instead of Serializable, because it's a lot faster.
Source : http://www.developerphil.com/parcelable-vs-serializable/

Related

How to get the covid info of a country with java, JSON

I am making a java file in which you enter the country and then it shows you the covid-19 info of that country. The site which I am using is https://covid19.mathdro.id/api/countries/
here i want it such that the user enter the country and it adds the countries name to the website eg if the user entered India it should do this
https://covid19.mathdro.id/api/countries/India
Any help would be neccessary, Thanks
You can use Retrofit to call the APIs
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.Response;
public class Retrofit_Example {
public static void main(String[] args) {
OkHttpClient.Builder client = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://covid19.mathdro.id/")
.addConverterFactory(GsonConverterFactory.create())
.client(client.build())
.build();
Service service = retrofit.create(Service.class);
Call<Response1> responseCall = service.getData("India");
try {
Response<Response1> response = responseCall.execute();
Response1 apiResponse = response.body();
System.out.println(apiResponse);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You will have to create POJOs from the JSON response coming from the api first and also the retrofit client.
POJO for respone
public class Response1 {
private Confirmed confirmed;
private Deaths deaths;
private String lastUpdate;
private Recovered recovered;
public Confirmed getConfirmed() {
return confirmed;
}
public void setConfirmed(Confirmed confirmed) {
this.confirmed = confirmed;
}
public Deaths getDeaths() {
return deaths;
}
public void setDeaths(Deaths deaths) {
this.deaths = deaths;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Recovered getRecovered() {
return recovered;
}
public void setRecovered(Recovered recovered) {
this.recovered = recovered;
}
#Override
public String toString() {
return "Response1{" +
"confirmed=" + confirmed +
", deaths=" + deaths +
", lastUpdate='" + lastUpdate + '\'' +
", recovered=" + recovered +
'}';
}
}
public class Recovered {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Recovered{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Deaths {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Deaths{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
public class Confirmed {
private String detail;
private Long value;
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
#Override
public String toString() {
return "Confirmed{" +
"detail='" + detail + '\'' +
", value=" + value +
'}';
}
}
Retrofit Client
public interface Service {
#GET("/api/countries/{country}")
public Call<Response1> getData(#Path("country")String country);
}

Reading JSON - Retrofit - Android Studio

i really ned help with this. Im not being able to read the JSON and i dont know what im doing wrong.
I will drop my code here.
I have this Json
{
"id": "288",
"name": "Tarjeta Shopping",
"secure_thumbnail": "https://www.mercadopago.com/org-img/MP3/API/logos/288.gif",
"thumbnail": "http://img.mlstatic.com/org-img/MP3/API/logos/288.gif",
"processing_mode": "aggregator",
"merchant_account_id": null
}
This is my class that should represent that JSON
public class Tarjeta {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("secure_thumbnail")
#Expose
private String secureThumbnail;
#SerializedName("thumbnail")
#Expose
private String thumbnail;
#SerializedName("processing_mode")
#Expose
private String processingMode;
#SerializedName("merchant_account_id")
#Expose
private Object merchantAccountId;
public Tarjeta() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecureThumbnail() {
return secureThumbnail;
}
public void setSecureThumbnail(String secureThumbnail) {
this.secureThumbnail = secureThumbnail;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getProcessingMode() {
return processingMode;
}
public void setProcessingMode(String processingMode) {
this.processingMode = processingMode;
}
public Object getMerchantAccountId() {
return merchantAccountId;
}
public void setMerchantAccountId(Object merchantAccountId) {
this.merchantAccountId = merchantAccountId;
}
#Override
public String toString() {
return "Tarjeta{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", secureThumbnail='" + secureThumbnail + '\'' +
", thumbnail='" + thumbnail + '\'' +
", processingMode='" + processingMode + '\'' +
", merchantAccountId=" + merchantAccountId +
'}';
}
}
this is my GET method
#GET("payment_methods/card_issuers")
Call<Tarjeta> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);
And this is where i try to read it.
botonTest2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Test boton 2 clickeado");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ServicePago servicePago = retrofit.create(ServicePago.class);
Call<Tarjeta> contenedorTarjetaCall = servicePago.getTarjetas2(apiKey,"visa");
contenedorTarjetaCall.enqueue(new Callback<Tarjeta>() {
#Override
public void onResponse(Call<Tarjeta> call, Response<Tarjeta> response) {
Toast.makeText(MainActivity.this, "BIEN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Tarjeta> call, Throwable t) {
Toast.makeText(MainActivity.this, "ALGO SALIO MAL", Toast.LENGTH_SHORT).show();
}
});
}
});
Im habing this error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I think my class is correctly modelated, im completly lost.
since you did not post your entire JSON I'm going to answer with a rough idea hope it helps.
the error states that the received JSON is not a Tarjeta but an array of Tarjeta. so to fix it I guess you just have to wrap your response in a list type. so it goes something like this:
#GET("payment_methods/card_issuers")
Call<List<Tarjeta>> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);

How do I send an ArrayList of Object though Intent?

I am trying to pass an array list of an object called popular people through the extras.
I have implemented parcelable interface in the object
public class PopularPeople implements Parcelable {
#SerializedName("popularity")
private double popularity;
#SerializedName("name")
private String name;
#SerializedName("profile_path")
private String profilePath;
#SerializedName("id")
private int id;
#SerializedName("adult")
private boolean adult;
public void setPopularity(double popularity){
this.popularity = popularity;
}
public double getPopularity(){
return popularity;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setProfilePath(String profilePath){
this.profilePath = profilePath;
}
public String getProfilePath(){
return profilePath;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setAdult(boolean adult){
this.adult = adult;
}
public boolean isAdult(){
return adult;
}
#Override
public String toString(){
return
"PopularPeople{" +
"popularity = '" + popularity + '\'' +
",name = '" + name + '\'' +
",profile_path = '" + profilePath + '\'' +
",id = '" + id + '\'' +
",adult = '" + adult + '\'' +
"}";
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeDouble(this.popularity);
dest.writeString(this.name);
dest.writeString(this.profilePath);
dest.writeInt(this.id);
dest.writeByte(this.adult ? (byte) 1 : (byte) 0);
}
public PopularPeople() {
}
protected PopularPeople(Parcel in) {
this.popularity = in.readDouble();
this.name = in.readString();
this.profilePath = in.readString();
this.id = in.readInt();
this.adult = in.readByte() != 0;
}
public static final Parcelable.Creator<PopularPeople> CREATOR = new Parcelable.Creator<PopularPeople>() {
#Override
public PopularPeople createFromParcel(Parcel source) {
return new PopularPeople(source);
}
#Override
public PopularPeople[] newArray(int size) {
return new PopularPeople[size];
}
};
}
Now in an activity, I am creating a new popular people object and creating a list of PopularPeople from another object Cast
detailCastSeeAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// we need to convert CAST to POPULARPEOPLE. We only need name, profile path and ID.
ArrayList<PopularPeople> popularPeople = new ArrayList<>();
Bundle b = new Bundle();
for(Cast c : cast){
PopularPeople p = new PopularPeople();
p.setName(c.getName());
p.setId(c.getId());
p.setProfilePath(c.getProfilePath());
popularPeople.add(p);
Timber.e("Added %s",c.getName());
}
Timber.e("Length before sendin list %d",popularPeople.size());
Intent i = new Intent(MovieDetailActivity.this, PopularPeopleActivity.class);
b.putParcelableArrayList(AppConstants.CAST_LIST,popularPeople);
i.putExtras(b);
i.putExtra(AppConstants.TAG,AppConstants.MOVIE_CAST);
startActivity(i);
}
});
Now when I recieve this in the other class, the recieved array list is still empty and not populated with the list of data I sent in from the other activity.
b = getIntent().getExtras();
if (b != null){
ArrayList<PopularPeople> peopleList =
b.getParcelableArrayList(AppConstants.CAST_LIST);
tag = b != null ? b.getString(AppConstants.TAG) : null;
}else{
Toast.makeText(this, "Error loading. Please try again..", Toast.LENGTH_SHORT).show();
finish();
// return is required as we dont want to execute the code below and just want the activity to close.
return;
}
In the second activity where I recieve the intent, if I log out the size of popular people it gives out 0. How do I fix this?
You might want to consider saving the Arraylist to SharedPreferences and pass the key to it through an intent extra.
I experienced it to be the easiest to use Gson and json to write an Arraylist of Custom Objects to SharedPreferences.
Here is a good tutorial on how to do that: https://youtu.be/jcliHGR3CHo
But if you want to use parcelable I would recommend you to watch this tutorial: https://youtu.be/WBbsvqSu0is
I hope this could help you!
Instead of going with "parceable", you can go with "serializable".
try this way may this help you
First you want to make
Class Venue implements Serializable
public class Venue implements Serializable { /** * */
private static final long serialVersionUID = 1L; }
In your FirstActivity do this way
ArrayList<Venue> VenueArrayList = new ArrayList<Venue>();
Intent intent = new Intent(this,secondActivity.class);
intent.putExtra("VenueArrayList", VenueArrayList);
In your SecondActivity do this way
ArrayList<Venue> VenueArrayList; VenueArrayList = (ArrayList<Venue>)
getIntent().getSerializableExtra( "VenueArrayList");

Stax API XML parsing produces null results

I have been trying to get this over for a while now with little or no success. Right now, I am really out of options. I will appreciate some assistance or pointers towards the right direction.... since I believe I am not doing somethings very well.
After parsing with the code below, I have null values in most of the fields: Result{id=30c26c8a-8bdf-4d4d-8f8d-a19661f16877, name=Andriod_Office_Task, owner =generated.Owner#53d8d10a, comment=, creationTime=2016-09-09T19:30, modificationTime=2016-09-09T19:30:05+02:00, reportId=null, taskid=null, host=null, port=null, nvt=null, scanNVTVersion=null, threat=null, severity=null, description=null}
The parsing methods (other methods are excluded for brevity):
private List<Result> readDocument(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
List<Result> results = new ArrayList<>();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("result"))
results.add(readResult(parser));
break;
case XMLStreamReader.END_ELEMENT:
return results;
}
}
throw new XMLStreamException("Premature end of file");
}
public Result readResult(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
Result result = new Result();
result.setId(parser.getAttributeValue(null, "id"));
Report report = new Report();
Task task = new Task();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("name"))
result.setName(readCharacters(parser));
else if (elementName.equals("host"))
result.setHost(readCharacters(parser));
else if (elementName.equals("owner"))
result.setOwner(readOwner(parser));
else if (elementName.equals("comment"))
result.setComment(readCharacters(parser));
else if (elementName.equals("creation_time"))
result.setCreationTime(readCreationTime(parser));
else if (elementName.equals("modification_time"))
result.setModificationTime(readCharacters(parser));
else if (elementName.equals("report"))
report.setId(readReport(parser));
else if (elementName.equals("task"))
task.setId(readTask(parser));
else if (elementName.equals("user_tags"))
result.setUserTags(readUserTags(parser));
else if (elementName.equals("port"))
result.setPort(readCharacters(parser));
else if (elementName.equals("nvt"))
result.setNvt(readNvt(parser));
else if (elementName.equals("scan_nvt_version"))
result.setScanNVTVersion(readCharacters(parser));
else if (elementName.equals("threat"))
result.setThreat(readCharacters(parser));
else if (elementName.equals("severity"))
result.setSeverity(readCharacters(parser));
else if (elementName.equals("qod"))
result.setQod((Qod) readQod(parser));
else if (elementName.equals("description"))
result.setDescription(readCharacters(parser));
break;
case XMLStreamReader.END_ELEMENT:
}
return result;
}
throw new XMLStreamException("Premature end of file");
}
private String readCharacters(XMLStreamReader reader) throws XMLStreamException {
StringBuilder result = new StringBuilder();
while (reader.hasNext()) {
int eventType = reader.next();
switch (eventType) {
case XMLStreamReader.CHARACTERS:
result.append(reader.getText());
break;
case XMLStreamReader.END_ELEMENT:
return result.toString();
}
}
throw new XMLStreamException("Premature end of file");
}
}
The result class is below :
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Result {
#XmlAttribute
private String id;
#XmlElement
private String name;
#XmlElement
private Task task;
#XmlElement
private String comment;
#XmlElement(name = "creation_time")
String creationTime;
#XmlElement(name = "modification_time")
private String modificationTime;
// TODO user_tags
#XmlElement
private UserTags userTags;
#XmlElement
private Owner owner;
#XmlElement
private Qod qod;
/**
* // * The report the result belongs to (only when details were requested)
* //
*/
#XmlElementWrapper(name = "report")
#XmlElement(name = "reportId")
private String reportId;
#XmlElement
private String host;
#XmlElement
private String port;
#XmlElement
private NVT nvt;
#XmlElement(name = "scan_nvt_version")
private String scanNVTVersion;
#XmlElement
private String threat;
#XmlElement
private String severity;
#XmlElement
private String description;
public Result() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCreationTime() {
return creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public String getModificationTime() {
return modificationTime;
}
public void setModificationTime(String modificationTime) {
this.modificationTime = modificationTime;
}
public UserTags getUserTags() {
return userTags;
}
public void setUserTags(UserTags userTags) {
this.userTags = userTags;
}
public Qod getQod() {
return qod;
}
public void setQod(Qod qod) {
this.qod = qod;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public String getReportId() {
return reportId;
}
public void setReportId(String reportId) {
this.reportId = reportId;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public NVT getNvt() {
return nvt;
}
public void setNvt(NVT nvt) {
this.nvt = nvt;
}
public String getScanNVTVersion() {
return scanNVTVersion;
}
public void setScanNVTVersion(String scanNVTVersion) {
this.scanNVTVersion = scanNVTVersion;
}
public String getThreat() {
return threat;
}
public void setThreat(String threat) {
this.threat = threat;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Result{" + "id=" + id +
", name=" + name + ", owner =" + owner +
", comment=" + comment + ", creationTime=" + creationTime + ", modificationTime=" + modificationTime
+ ", reportId=" + reportId + ", taskid=" + task + ", host=" + host + ", port=" + port + ", nvt=" + nvt
+ ", scanNVTVersion=" + scanNVTVersion + ", threat=" + threat + ", severity=" + severity
+ ", description=" + description + '}';
}
}
<get_results_response status="200" status_text="OK">
<result id="30c26c8a-8bdf-4d4d-8f8d-a19661f16877">
<name>Trace route</name>
<owner>
<name>admin</name>
</owner>
<comment/>
<creation_time>2016-09-09T19:30:05+02:00</creation_time>
<modification_time>2016-09-09T19:30:05+02:00</modification_time>
< id="2a6d7f75-f6b7-40b2-a792-b558fada375b"/>
<task id="e59ac66b-5b59-4756-bace-37bb1106276d">
<name>Andriod_Office_Task</name>
</task>
<user_tags>
<count>0</count>re
</user_tags>
<host>172.16.53.178</host>
<port>general/tcp</port>
<nvt oid="1.3.6.1.4.1.25623.1.0.51662">
<name>Traceroute</name>
<family>General</family>
<cvss_base>0.0</cvss_base>
<cve>NOCVE</cve>
<bid>NOBID</bid>
<xref>NOXREF</xref>
<tags>cvss_base_vector=AV:N/AC:L/Au:N/C:N/I:N/A:N|qod_type=remote_banner|solution=Block unwanted packets from escaping your network.|summary=A traceroute from the scanning server to the target system was
conducted. This traceroute is provided primarily for informational
value only. In the vast majority of cases, it does not represent a
vulnerability. However, if the displayed traceroute contains any
private addresses that should not have been publicly visible, then you
have an issue you need to correct.</tags>
<cert/>
</nvt>
<scan_nvt_version>$Revision: 2837 $</scan_nvt_version>
<threat>Log</threat>
<severity>0.0</severity>
<qod>
<value>80</value>
<type>remote_banner</type>
</qod>
<description>Here is the route from 192.168.14.128 to 172.16.53.178:
192.168.14.128
172.16.53.178</description>
</result>
<filters id="">
<term>first=1 rows=-1 sort=name</term>
<keywords>
<keyword>
<column>first</column>
<relation>=</relation>
<value>1</value>
</keyword>
<keyword>
<column>rows</column>
<relation>=</relation>
<value>-1</value>
</keyword>
<keyword>
<column>sort</column>
<relation>=</relation>
<value>name</value>
</keyword>
</keywords>
</filters>
<sort>
<field>name
<order>ascending</order></field>
</sort>
<results max="-1" start="1"/>
<result_count>3444
<filtered>1</filtered>
<page>1</page></result_count>
</get_results_response>
After some research and attempts with some common xml parsing approaches, I ended up using jackson-dataformat-xml approach. While this might not be the best it gave me what I wanted with much less code. Basically, I had to adapt the annotations in the model classes as below :
#JsonIgnoreProperties(ignoreUnknown=true)
#JacksonXmlRootElement(localName = "results")
public class Results {
#JacksonXmlProperty(localName = "result")
#JacksonXmlElementWrapper(useWrapping = false)
public Result [] result;
public Results() {
}
public Result[] getResult() {
return result;
}
public void setResult(Result[] result) {
this.result = result;
}
#Override
public String toString() {
return "Results [result=" + Arrays.toString(result) + "]";
}
And some adaptations for the parsing class:
public class GetReportsResponseHandler extends DefaultHandler<GetReportsResponse> {
private XmlMapper mapper = new XmlMapper();
public GetReportsResponseHandler() {
super(new GetReportsResponse(), "get_reports_response");
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
mapper.setAnnotationIntrospector(pair);
}
#Override
protected void parseStartElement(XMLStreamReader parser) throws XMLStreamException, IOException {
if ("report".equals(parser.getName().toString())){
Report report = mapper.readValue(parser, Report.class);
response.addReport(report);
}

How to print contents of a class object by field?

I have a POJO class, Location that is used to map a JSON file to a class using Jackson. The current implementation can print out every Location object in the class by calling,Location's toString() but I'm wondering how I can print for example, just the location with id= "2", which would be name="Desert"
At the moment, I use a toString method like this to print all the contents of Location:
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
Does anyone know how I can print specific locations within the Location object based on a field id?
This is an example of what is stored in the Location class when I call toString() on it:
http://hastebin.com/eruxateduz.vhdl
An example of one of the Locations within the Location object:
[Location [location=null, id=1, description=You are in the city of Tiberius. You see a long street with high buildings and a castle.You see an exit to the south., weight=100, name=Tiberius, exit=[Exit [title=Desert, direction=South]]]
This is the POJO location class I use to map the JSON fields to the class:
public class Location {
private Location[] location;
private int id;
private String description;
private String weight;
private String name;
private Exit[] exit;
private boolean visited = false;
private boolean goalLocation;
private int approximateDistanceFromGoal = 0;
private Location parent;
public Location[] getLocation() {
return location;
}
public void setLocation(Location[] location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public Exit[] getExit() {
return exit;
}
public void setExit(Exit[] exit) {
this.exit = exit;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isGoalLocation() {
return goalLocation;
}
public void setGoalLocation(boolean goalLocation) {
this.goalLocation = goalLocation;
}
public int getApproximateDistanceFromGoal() {
return approximateDistanceFromGoal;
}
public void setApproximateDistanceFromGoal(int approximateDistanceFromGoal) {
this.approximateDistanceFromGoal = approximateDistanceFromGoal;
}
public Location getParent() {
return parent;
}
public void setParent(Location parent) {
this.parent = parent;
}
#Override
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
You need the above dependency to define predicate unless you want to do it on your own.
public class Location {
private int id;
// more stuff here
private Predicate<Integer> filter;
public Location() {
this.filter = TruePredicate.INSTANCE;
}
public Location(int idFilter) {
this.filter = new EqualPrediate(idFilter);
}
public String toString() {
StringBuilder buffer = new StringBuilder();
if(filter.apply(this.id)) {
buffer.append("Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]");
}
return buffer.toString();
}
}
This code is a simplified Visitor Pattern where the
'Visitor' -> your predicate
'this' -> 'this.id'
This works because your toString() is invoking the toString() of the nested Location objects which also have their predicates for filtering set.
If you aren't in control of their construction where you can propogate the filter then you can take this approach:
public String toString() {
StringBuilder buffer = new StringBuilder();
int i = 0;
for(Location l = this; i < locations.length; l = locations[i++])
if(filter.apply(l.id) {
buffer.append("Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]");
}
return buffer.toString();
}
Stream.of(location).filters(l -> l.getId() == 2).foreach(System.out::println);
Does that work?
You can have a try with gson, which inputs a object and outputs a JSON or in the opposite side.
After u make the object a JSONObject, you can ergodic the JSON in order to ergodic object.

Categories