Given (for example):
Dog breeds (Name) | id
Labrador Retriever | A1
German Shepherd | A2
Golden Retriever | A3
Now the dog breeds are displayed in a list and someone can select one and i have to store the id from the selected dog.
The question is what is the best way to convert them in each other.
At the Moment in android i have two string array ressources, store in one the names and in the other the ids and have a method which searches for the name in the "name-array", give me the index and then i can get the id trough the second "id-array", because the id must be in the same index.
Thanks
Create a POJO (Plain Old Java Object) with two fields.
public class DogBreed {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Use custom adapter to show it. Then you don't have to worry about mirroring indices. Just use getter on correct object.
Default adapters usually use toString method. So you can use more generic solutions by overriding toString.
#Override
public String toString() {
return name;
}
Related
Let say, I have a student, employee and car class in a different structure in JSON file.
I already parse them and put the respective data to its POJO classes. The things is I wanna display data to inside a recycler view.
But here I have common field both three class is name and weight.
So, I wanna pass to list of generic to recycler view and populate them by calling like this:
tvName.setText(Object(should be generic).getName());
tvWeight.setText(Object(should be generic).getWeight());
It should display name and weight all the student, employee and car .
RecyclerView looks like
---------------------------------------------------------
CarName
CarWeight
---------------------------------------------------------
EmplyoeeName
EmplyoeeWeight
---------------------------------------------------------
StudentName
StudentWeight
---------------------------------------------------------
EmplyoeeName
EmplyoeeWeight
---------------------------------------------------------
CarName
CarWeight
---------------------------------------------------------
CarName
CarWeight
---------------------------------------------------------
StudentName
StudentWeight
Any idea would be highly appreciated.
In order to achieve that, you need something called polymorphism, learn more from StackOverflow, Java Docs and Wikipedia. In order to respect that pattern I would implement the problem like this:
I would create an Interface that has the methods you need:
public interface AttributesInterface {
String getName();
double getWeight();
}
Then I would make every POJO class implement that interface, looking in the end like this:
public class Car implements AttributesInterface {
private String name;
private double weight;
#Override
public String getName() {
return null;
}
#Override
public double getWeight() {
return weight;
}
}
In the adapter you store the list like this. If a class will implement the interface, then you will be able to add it in that array. So you will have an array that will contain Student, Car, Employee in the same time.
private List<AttributesInterface> list = new ArrayList<>();
Then final step is in onBindViewHolder where you get an object from that array and set the corresponding values.
AttributesInterface object = list.get(position);
tvName.setText(object.getName());
tvWeight.setText(String.valueOf(object.getWeight()));
Also, you mentioned that you want a solution to work with multiple classes. As long as you implement the interface in each class that needs to be displayed, you can have a million classes.
You can create only one POJO class and you can add extra variable say type. So your POJO class will look like below.
public class MyClassModel {
private String type=""; // S=Student, C=Car, E=Employee
private String name="", weight="";
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
}
Now you will get type in your RecyclerviewAdapter so you can write your logic according to type of data.
How do you save a JSON Array as an item attribute? AWS documentation is the absolute worst thing ever - it contradicts itself, a lot of things are either redundant or only partially explained, some things aren't explained at all - I don't know how anyone manages to use it.
Anyway, suppose I have a table called Paths, and a path has a name, an ID, and a list of LatLngs (formatted as a JSON Array)
In the class definition for this table, I have
#DynamoDBTable(tableName = "Paths")
public class Path {
private String id;
private String name;
private JSONArray outlineJSON;
with getters and setters like
#DynamoDBRangeKey(attributeName = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
which works fine for strings, booleans and numbers, and the object saves successfully to the table.
AWS documentation mentions JSON several times, and says it can handle lists, but it doesn't explain how to use lists or give any examples.
I used #DynamoDBHashKey for the id, #DynamoDBRangeKey for name, and #DynamoDBAttribute for other strings, numbers or booleans, and I tried it here
#DynamoDBAttribute(attributeName = "outline")
private JSONArray getOutlineJSON() {
return outlineJSON;
}
private void setOutlineJSON(JSONArray outlineJSON) {
this.outlineJSON = outlineJSON;
}
It successfully saved the object but without the array.
How do I save the array? I can't find an explanation anywhere. I think #DynamoDBDocument might have something to do with it, but all the documentation on the subject gives unrelated examples, and I can't find any using a list like my in situation.
EDIT: For now, I have a working solution - I can easily convert my lists to JSONArrays and then convert those to Strings, and vice-versa.
You can define your class to be something like
#DynamoDBTable(tableName = "Paths")
public class Path {
private String id;
private String name;
private LatLang latLangs;
#DynamoDBHashKey(attributeName="id")
public String getId() { return id;}
public void setId(String id) {this.id = id;}
#DynamoDBRangeKey(attributeName = "name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#DynamoDBDocument
public static class LatLang{
public String lat;
public String lang;
}
}
I want to put in a jcombobox, the name and use the id for link the option select and the name.
I get the data of the db, but I don't know the way for add a items.
I try to write a item, with 2 parameters, but in the combobox appear the class name, not the value :
This is my code
rs = (ResultSet) stmt.executeQuery();
while ( rs.next() ) {
cbHabitaciones.addItem(new Item(rs.getInt("id"), rs.getString("tipo") +" - " +rs.getString("precio")));
}
Easiest way for you would be to override toString() method of the class which instances you are putting in the JCombo's model. That way you get your 'nice name' for each item. That class, of course, should contain everything you need for each item, e.g. id and name. On selection change, you can than use the id of the selected item.
If you cannot override 'toString()' or you want to separate objects you already have (e.g. if they are DTO) from the presentation objects, create your own class with only the things you need.
public class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public String toString() {
return this.getName();
}
}
In the below code, I have two objects of same class. One object (A - employeeObjectInDatabase) has all the fields set. Another object (B - employeeObjectForUpdate) has only few of the fields set. basically I need to set not null values of Object B to Object A. Below code has 'if not null' check for each field to set the value. Is there any other better way to get this done?
Is there a better way to replace the code between comments "BLOCK 1 BEGIN" and "BLOCK 1 END"?
In case of classes with few fields, checking for if not null is easy, but in case of 20+ fields there is a lot of if not null check required, hence thought of getting expert opinion.
Sample:
public class Employee {
private String id;
private String name;
private String department;
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 getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public static void main(String[] args) {
Employee newEmployeeObject = new Employee();
newEmployeeObject.setId("A100");
newEmployeeObject.setName("Albert");
newEmployeeObject.setName("Physics");
//newEmployeeObject is persisted into database
Employee employeeObjectForUpdate = new Employee();
employeeObjectForUpdate.setId("A100");
employeeObjectForUpdate.setName("Albert Einstein");
//Inorder to update only the fields that are not null
Employee employeeObjectInDatabase = employeeDao.getEmployee();
//BLOCK 1 BEGIN
if (null != employeeObjectForUpdate.getName())
employeeObjectInDatabase.setName(employeeObjectForUpdate.getName());
if (null != employeeObjectForUpdate.getDepartment())
employeeObjectInDatabase.setDepartment(employeeObjectForUpdate.getDepartment());
//BLOCK 1 END
//persist employeeObjectInDatabase as it has the updated information
}
}
You can move the null check in your setter method
public void setName(String name) {
if(name!=null){
this.name = name;
}
}
Then in your main method, you can you simply call the following:
employeeObjectInDatabase.setName(employeeObjectForUpdate.getName());
If in your Data Access layer when you will populate the db values to your object, the same principle will be applied. That is if the Db column value is null, it wont be setting to the property
You could create a member method to transfer non-null field values to a given object of the same type using reflection.
The following shows a solution using org.apache.commons.beanutils.BeanUtilsBean. See if it helps.
Helper in order to copy non null properties from object to another ? (Java)
Add copy method to Object B. This method should copy its non null values to Object A and return it.And also you can use reflection in this method.
look at this post;
Copy all values from fields in one class to another through reflection
I have a user defined class, say
import java.util.Calendar;
public class Employee{
private String name;
private int age;
private Calendar dob;
private Address address;
private boolean married;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Calendar getDob() {
return dob;
}
public void setDob(Calendar dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
}
class Address{
private int doorNo;
private String streetName;
private String city;
public int getDoorNo() {
return doorNo;
}
public void setDoorNo(int doorNo) {
this.doorNo = doorNo;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
I am creating an object of Employee and populating it with setters. I have to represent the above object to string (encrypted or human-readable) and parse back to get similar object. Actually, I want to save the string equivalent of java object in a file and to read back them to get a java object. I know we have object writing, but they are sensitive to edit. I would prefer if a java object can be converted to String of human readable form. Thanks.
To keep your flattened object human readable and hand editable consider encoding your object into a JSON string using one of the popular JSON libraries. Same JSON library will also provide you APIs to decode a JSON string into your object.
One of the popular JSON library is Gson. Here's an use example: Converting JSON to Java
You should override toString() to convert instances of your class to string. As for recreating instances based on their string representation you can define a static factory method for this.
public class Employee {
...
#Override
public String toString() {
...
}
public static Employee fromString(String str) {
...
}
}
You use these methods like this:
To obtain string representation of an instance to string:
Employee john = ...
String johnString = john.toString();
Note that your toString() method will also be called implicitly whenever there is a need to obtain string representation of one of the instances.
To recreate an instance from string:
Employee john = Employee.fromString(johnString);
If you often need to store instances of the class in a file and read them back, you may also consider serialization. See documentation for Serializable interface as well as ObjectInputStream and ObjectOutputStream. You may also want to familiarize yourself with caveats surrounding serialization by reading the last chapter ("Serialization") in Effective Java, second edition. Most importantly be aware that the serialized form of your class becomes part of your public API.
You might be looking for the toString method:
Returns a string representation of the object. In general, the
toString method returns a string that "textually represents" this
object. The result should be a concise but informative representation
that is easy for a person to read. It is recommended that all
subclasses override this method.
In your case you would be doing something of the sort (to be added in each of your classes):
#Override
public String toString()
{
return "Name = " + name + ...
}
The string can be of any format you wish. To save the object, all that you need to do is to write the text that the toString method returns to a file.
To read them back, however, you will have to implement your own logic. On the other hand, what you can do, is to use something such as XStream (instructions here) which will automatically convert your object to XML.
XML is human readable so that your users can modify whatever they need. Once this is done, you can re-use XStream to read back your object.
Try this
Employee em = new Employee;
//Your code
str obj= JavaScriptSerializer.Serialize();
// whenever you want to get object again
Employee emp = (Employee)JavaScriptSerializer.Deserialize();