Dynamically connect parameter to view via DataBinding - java

Hi I have following Problem:
Lets say I have multiple types of DataSets
DataSet1{
#Bindable
public String Name;
#Bindable
public int Duration;
}
DataSet2{
#Bindable
public String Url;
#Bindable
public int StartTime;
}
Now I want create for each parameter in this DataSets an EditTextBox with its text property binds to the parameters. I know how to do this static within the xml layout files. But I have multiple DataSets and I don't want to create foreach of this a specified xml file.
android:text="#={dataSet.Name}"
Is it possible to create this binding programmatically? like:
binding.setBinding(binding.text.text, dataSet.name);
where binding.text the EditTextView.

Related

Spring Boot Restcontroller JSON Response doesnt include any property names but only values

I am trying to get familiar with Java and Spring Boot and I have managed to set up a service and a controller as I needed but there is one minor issue I can not seem to solve.
The Get Mapping should return a List of Classes from a 3rd party library, which it does. The Issue is that it is not including the property names in the JSON response.
#GetMapping("/{symbol}/{timeframe}")
public List<Candlestick> getOHLCV(#PathVariable("symbol") String symbol,
#PathVariable("timeframe") String timeframe) {
return service.getOHLCV(symbol, IntervalConverter.fromString(timeframe));
}
The Candlestick Class holds properties like open, high,low,close but these property names are all missing in the response. Why is that the case and how to solve that?
I get a response array like this:
[[1675190700000,"23143.08000000","23179.36000000","23141.26000000","23178.22000000","766.15847000",1675190999999,"17746710.34454660",22165,"453.83717000","10512390.22459520"]]
Try adding #JsonProperty on property name
public class Candlestick {
#JsonProperty("open")
private String open;
#JsonProperty("high")
private String high;
#JsonProperty("low")
private String low;
#JsonProperty("close")
private String close;
// getters and setters
}

Hash maps to link several domains into one report - Java Eclipse

I am new to Java and am using Java Eclipse, so please be kind! I hope I'm going to pose this question correctly so it makes sense.
I have four domains - each domain is pulling data from four different servers, hence the need to have them separate. But now I need to create a report that links all the data from the four domains into one report. Someone suggested using hashmaps, which I haven't used before. My four domains each have two fields that can be used as a key - CostCenter and Serial. The data being pulled is from machines all over the country. I need all the data for each machine in one report.
This is all being added to an existing project that creates a webpage with tabs for the user to click on for various tables and get data specific to a location, or to create a report for each page for all machines/locations. I just need to add a new link for the user to click on that will create this spreadsheet for them.
I've already created the domains (DAO, DAOImpl, DTO, and so on) and then I was going to create the combined report in my MainService.java. Here are the domains (lists) as declared in my MainService:
public List<Volume> getVolumeReport();
public List<BadFmPumps> getBadFmPumpsReport();
public List<BadCorobPumps> getBadCorobPumpsReport();
public List<McService> getMcServiceReport();
And here is data being pulled from the databases for each of them (domains):
public class Volume {
private String costCenter;
private String DAD;
private String division;
private String model;
private String serial;
private String numDispensers;
private String colorantSys;
private String CCEGals2017;
private String BACGals2017;
private String CCEGals2018;
private String BACGals2018;
private String DNR2017;
private String DNR2018;
private String DNR2019;
public class BadFmPumps {
private String costCenter;
private String model;
private String serial;
private String badFmPumps;
private String over10;
private String under10;
public class BadCorobPumps {
private String costCenter;
private String model;
private String serial;
private String badPumpCount;
public class McService {
private String costCenter;
private String model;
private String serial;
private String crChargeTotals;
private String emgCalls;
So I need to pull this data into one report wherever CostCenter + Serial matches. How do I declare the hashmaps for each object and how do I declare the key?
EDIT ----
I think I have something close here with
public List<Volume> getVolumeReport();
Map<String, Volume> VolumeMap = new HashMap<String, Volume>();
for (Volume dispenser : VolumeList)
{
String volumeKey = new StringBuilder().append(Volume.getCostCenter()).append(Volume.getSerial()).toString();
VolumeMap.put(volumeKey, dispenser);
}
Is this correct? I am getting one syntax error - the Map declaration
Map<String, Volume> VolumeMap = new HashMap<String, Volume>();
is giving me the error
Syntax error on token ";", { expected after this token
Is there something I need to change there?
There are some unusual things in your code. My guess is that you came from C# you are not using proper naming conventions see it here: https://www.oracle.com/technetwork/java/codeconventions-135099.html
You defined your method wrong, the error is not in the Map but the method definition
public List<Volume> getVolumeReport(); <-------- this
Should be
public List<Volume> getVolumeReport() {
And then close your method at its end (using }).
And inside your FOR you trying to direct access the Volume methods when you should use the variable you created: dispenser
String volumeKey = new StringBuilder()
.append(Volume.getCostCenter())
.append(Volume.getSerial())
.toString();
Should be
String volumeKey = new StringBuilder()
.append(dispenser.getCostCenter())
.append(dispenser.getSerial())
.toString();

Create a simple XML-document database Java

I need some Java help.
I have got a class like this
public class Thing {
private String name;
private int price;
public Thing(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
And my main looks like this
public class Main {
public static void main(String[] args) {
Thing Bowl = new Thing("Bowl", 20);
} }
What I would like to do is make a simple XML-document database. So I can add different kind of things in my database. How can I implement this kind of database in my system?
It's not correct to call what you're talking about a database. You just want to save a Java class as an XML file. Jackson is a good library that allows for both JSON and XML encode/decode and using it, can be done as so given a POJO:
ObjectMapper xmlMapper = new XmlMapper();
List<Thing> things = new ArrayList<>();
things.add(bowl);
String xmlData = xmlMapper.writeValueAsString(things);
List<Thing> thingsFromXml = xmlMapper.readValue(xmlData, new TypeReference<List<Thing>>(){});
Although the question is very broad, I'll do my best to guide you along.
An overarching system for XML consists out of various subsystems. First of all, you're going to need a way to parse the XML documents. There are many open source libraries out there that you can use. Even if you insist on writing it from scratch, referencing work that others have made is always useful.
See this:
Which is the best library for XML parsing in java
Then once you have a system in place in which you can parse the documents, you'll need a way to organize the parsed data. The way to approach this is subject to the practical use of the system. For example, if you use XML as the standard format for loading data in a game and thus deal with many different types of data such as items, objects, locations and so forth. You'll want a dynamic way to reload the data, the factory design pattern would work well in this use-case.
See this: https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

Is it possible to build an object like this at runtime in java?

As the title says....
I want to build a POJO with four field variables and at certain runtime events create an instance of this POJO with access to possibly maybe two or three of the fields.
public class Category implements Serializable {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Lets say I create a new Category object but I only want to be able to have access to the name field during runtime. Is there a design pattern I can use to achieve this? I thought about the strategy pattern and looked at the builder but I am still confused if I can do this in java.
Basically the overall goal is to grab an object from a database and return it as a JSON response in jax rs. But sometimes I dont want a complete object returned but only lets say halve of the object to be accessible at during certain runtime events. My apologies if this seems like a dumb question but I know what I want to do but just don't know the best way.
I have the same problem with you, and my project was used springmvc,and the json tool is jackson.With the problem solved, I just use #JsonIgnore.For more details,just read jackson-how-to-prevent-field-serialization
So someone correct me if I am wrong or see a better option than this...with alot of objects this can be alot of extra code for serialization and deserialization...Jackson Provisions is what I need. I can use the annotation #JsonView(DummyClass.class) on the field variable. I will accept this a the best answer in a day or two unless someone else posts a better response.
// View definitions:
class Views {
static class Public { }
static class ExtendedPublic extends PublicView { }
static class Internal extends ExtendedPublicView { }
}
public class Bean {
// Name is public
#JsonView(Views.Public.class) String name;
// Address semi-public
#JsonView(Views.ExtendPublic.class) Address address;
// SSN only for internal usage
#JsonView(Views.Internal.class) SocialSecNumber ssn;
}
With such view definitions, serialization would be done like so:
// short-cut:
objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);
// or fully exploded:
objectMapper.getSerializationConfig().setSerializationView(Views.Public.class);
// (note: can also pre-construct config object with 'mapper.copySerializationConfig'; reuse)
objectMapper.writeValue(out, beanInstance); // will use active view set via Config
// or, starting with 1.5, more convenient (ObjectWriter is reusable too)
objectMapper.viewWriter(ViewsPublic.class).writeValue(out, beanInstance);
This information was pulled from http://wiki.fasterxml.com/JacksonJsonViews
with jackson 2.3, I can do this with JAX-RS
public class Resource {
#JsonView(Views.Public.class)
#GET
#Produces(MediaType.APPLICATION_JSON )
public List<Object> getElements() {
...
return someResultList;
}
}

How to create objects from different data sources/formats

I'm working on project where I need to create objects from different data sources/formats. I would like to know what is the best way to organize source code to make it easy.
Let's say I have class User and I want to have ability to create objects from data from database and JSON. The purpose of it is letting user of my app to browse data online and offline. I'm using GSON and ORMLite. In addition fields in JSON and database may be different, but the "main" fields are the same. Is it a good idea to create class which contains all properties/fields from JSON and database? Something similar to class below:
#DatabaseTable(tableName = "user", daoClass = UserDaoImpl.class)
public class User {
public static final String ID_FIELD_NAME = "id";
public static final String USER_LOGIN_FIELD_NAME = "login";
public static final String USER_EMAIL_FIELD_NAME = "email";
public static final String SERIALIZED_COUNTRY_FIELD_NAME = "user_county";
// DB & JSON
#DatabaseField(generatedId = true, columnName = ID_FIELD_NAME)
int id;
// DB & JSON
#DatabaseField(columnName = USER_LOGIN_FIELD_NAME)
String login;
//DB & JSON
#DatabaseField(columnName = USER_EMAIL_FIELD_NAME)
String email;
//Only JSON
#SerializedName(SERIALIZED_COUNTRY_FIELD_NAME)
String country;
public Track() {
}
}
Is it a good idea to create class which contains all properties/fields from JSON and database?
I think the short answer is yes. You can certain use the same objects to represent the data in the database and via JSON.
When you will get into problems is when you need to change the data representations in the database but don't want to change your JSON API or vice versa. Then you will need 2 separate classes and a mapping function between them.
But if you can get away with one class then that's the best way.
consider the factory pattern, you can use it to abstract the creation of concrete user classes as a function of the data source.
make User into an interface, and have a data-source specific implementation of User for each type of data source.

Categories