I'm using Firebase as a backend, I was able to fetch the data but I can't map it to a Java class. I also tried to map using JSONObject, but the problem is I should ignore the key(1) since I'm querying based on the email value.
Data
users
1:
email: sample#email.com
firstName: Big
lastName: Ben
groups:
instructor: true
Firebase related code:
Firebase ref = new Firebase("firebaseURL");
Query queryRef = ref.orderByChild("email").equalTo(mEmailEdit.getText().toString()).limitToFirst(1);
// Attach an listener to read the data at our posts reference
queryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
System.out.println("user : " + user);
System.out.println("children : " + snapshot.getChildren().iterator().next());
mProgressDialog.dismiss();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
User.java
public class User {
private String email;
private String firstName;
private String lastName;
private Group group;
public User(){}
public User(String email, String firstName, String lastName) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return email.equals(user.email);
}
#Override
public int hashCode() {
return email.hashCode();
}
public class Group{
private boolean isInstructor;
private boolean isManager;
public Group(){}
public Group(boolean isInstructor, boolean isManager) {
this.isInstructor = isInstructor;
this.isManager = isManager;
}
public boolean isInstructor() {
return isInstructor;
}
public void setIsInstructor(boolean isInstructor) {
this.isInstructor = isInstructor;
}
public boolean isManager() {
return isManager;
}
public void setIsManager(boolean isManager) {
this.isManager = isManager;
}
#Override
public String toString() {
return "Group{" +
"isInstructor=" + isInstructor +
", isManager=" + isManager +
'}';
}
}
#Override
public String toString() {
return "User{" +
"email='" + email + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", group=" + group +
'}';
}
}
I already get it. From onDataChanged method, I placed the code below to map the data to User class.
snapshot.getChildren().iterator().next().getValue(User.class)
// snapshot.getChildren().iterator().next() // returns the child of the returned data
// .getValue(User.class) // since we already retrieved the child, and we're
// // now referring to User class data, we can now
// // map the data using Firebase method (getValue(Class<T>))
Related
Context - So there are two classes that uses inheritance. The EmployeeService is the parent class and the EmployeeInfo is the child class.
What do I need help with - So I am trying to insert an arrayList to the parent class that combines the information of the experience and position and makes a new arrayList called serviceList.
And when I call a super() in the child class, I should be able to call the arrayList rather than the String variables (experience, position).
To put it short, I should basically be able to pass an arrayList as the third parameter in the child class employeeInfo method instead of String experience or String position
Parent class -
public class EmployeeService () {
private String experience;
private String position;
public EmployeeService (String experience, String position) {
this.setExperience (experience);
this.setPosition(position);
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String toString() {
return "Experience - " + experience + "Position" + " - " + position;
}
}
Child class -
public class EmployeeInfo () {
private String firstName;
private String address;
public EmployeeInfo (String firstName, String address,String experience, String position) {
super(experience, position);
this.setFirstName (firstName);
this.setAddress(address);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Name - " + firstName + "Address" + " - " + address + super.toString();
}
}
Just add the property and an additional constructor to the parent class as follows:
import java.util.ArrayList;
import java.util.List;
public class EmployeeService {
private String experience;
private String position;
private List<String> serviceList;
public EmployeeService (String experience, String position) {
this.setExperience (experience);
this.setPosition(position);
}
public EmployeeService (String experience, String position, List<String> serviceList) {
this(experience, position);
this.serviceList = new ArrayList<>(serviceList);
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String toString() {
return "Experience - " + experience + "Position" + " - " + position;
}
}
Then adapt your child class:
import java.util.List;
public class EmployeeInfo extends EmployeeService {
private String firstName;
private String address;
public EmployeeInfo (String firstName, String address, String experience, String position) {
super(experience, position);
this.setFirstName (firstName);
this.setAddress(address);
}
public EmployeeInfo (String firstName, String address, String experience, String position, List<String> serviceList) {
super(experience, position, serviceList);
this.setFirstName (firstName);
this.setAddress(address);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Name - " + firstName + "Address" + " - " + address + super.toString();
}
}
I have tried to reorganised my database by adding a child called ("Reviews") that should include reviews added by the users but I keep getting a null displayed on the screen. I can only assume that the variables have not been saved into my modal class. I thought that my calling getReview() in my modal class should work:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference(); // getReference() is the root
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Information info = snapshot.getValue(Information.class);
assert info != null;
String txt = "Medical Clinic: " + info.getName() + " \n\n " + "Review: " + info.getReview() + "\n\nServices Provided: " + info.getDorevitch() + " : " + info.getSkin_Cancer() + " : " + info.getEar_Suctioning();
list.add(txt);
// list.add(snapshot.getValue().toString());
}
adapter.notifyDataSetChanged();
}
This is my modal class
enter code hepublic class Information { // variables have to match in firebase database or it will show null
private String Address;
private String Name;
private String Phone_No;
private String Suburb;
private String State;
private String Postcode;
private String Doctor;
private String Dorevitch;
private String Skin_Cancer;
private String Ear_Suctioning;
private String Reviews;
public Information() {
}
public Information(String address, String name, String phone_No, String suburb, String state, String postcode, String dorevitch, String skin_cancer, String ear_suctioning, String doctor, String review) {
Address = address;
Name = name;
Phone_No = phone_No;
Suburb = suburb;
State = state;
Postcode = postcode;
Doctor = doctor;
Dorevitch = dorevitch;
Skin_Cancer = skin_cancer;
Ear_Suctioning = ear_suctioning;
Reviews = review;
}
public String getDorevitch() {
return Dorevitch;
}
public void setDorevitch(String dorevitch) {
Dorevitch = dorevitch;
}
public String getSkin_Cancer() {
return Skin_Cancer;
}
public void setSkin_Cancer(String skin_Cancer) {
Skin_Cancer = skin_Cancer;
}
public String getEar_Suctioning() {
return Ear_Suctioning;
}
public void setEar_Suctioning(String ear_Suctioning) {
Ear_Suctioning = ear_Suctioning;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getDoctor() {
return Doctor;
}
public void setDoctor(String doctor) {
Doctor = doctor;
}
public String getSuburb() {
return Suburb;
}
public void setSuburb(String suburb) {
Suburb = suburb;
}
public String getReview() {
return Reviews;
}
public void setReview(String review) {
Reviews = review;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone_No() {
return Phone_No;
}
public void setPhone_No(String phone_No) {
Phone_No = phone_No;
}
public String getPostcode() {
return Postcode;
}
public void setPostcode(String postcode) {
Postcode = postcode;
}
I can get it to work but don't know why it is only working if I pull out from the database by doing the following code and not using my modal class?
String reviews = String.valueOf(snapshot.child("Reviews").getValue());
String services = String.valueOf(snapshot.child("Services").getValue());
What is the difference between String.valueof and toString()?
i was trying to show Json output in my Android app. I'm dropping the site link here: https://jsonplaceholder.typicode.com/users
When i try to show ResponseDTO.java output in AddressPage, it works. But when change it to Address.java or AddressDTO.java, i get null value in my app(in AddressPage)
AddressPage.java:
public class AdressPage extends AppCompatActivity {
String id, usr_name;
List<Address> userAdressList;
TextView street, suite, city, zipcode, latText, lngText;
List<GeoDTO> geoDTOList;
Float lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_address_page_adapter);
defVars();
get_parameters();
request();
}
public void get_parameters() {
Bundle bundle = getIntent().getExtras();
id = bundle.getString("post_id");
usr_name = bundle.getString("user_name");
}
public void defVars() {
street = findViewById(R.id.street);
suite = findViewById(R.id.suite);
city = findViewById(R.id.city);
zipcode = findViewById(R.id.zipcode);
latText = findViewById(R.id.lat);
lngText = findViewById(R.id.lng);
}
public void assignment(List<Address> addresses) {
street.setText(""+addresses.get(0).getStreet());
suite.setText(""+addresses.get(0).getSuite());
city.setText(""+addresses.get(0).getCity());
zipcode.setText(""+addresses.get(0).getZipcode());
/*zipcode.setText(id);
street.setText(id);
suite.setText(usr_name);
city.setText(usr_name);*/
}
public void request() {
userAdressList = new ArrayList<>();
Call<List<Address>> call = ManagerAll.getInstance().managerGetAdress(id, usr_name);
call.enqueue(new Callback<List<Address>>() {
#Override
public void onResponse(Call<List<Address>> call, Response<List<Address>> response) {
if (response.isSuccessful()) {
userAdressList = response.body();
assignment(userAdressList);
}
}
#Override
public void onFailure(Call<List<Address>> call, Throwable t) {
}
});
}
}
AddressDTO or Address (Same codes):
public class Address implements Serializable {
private String zipcode;
private Geo geo;
private String suite;
private String city;
private String street;
public void setZipcode(String zipcode){
this.zipcode = zipcode;
}
public String getZipcode(){
return zipcode;
}
public void setGeo(Geo geo){
this.geo = geo;
}
public Geo getGeo(){
return geo;
}
public void setSuite(String suite){
this.suite = suite;
}
public String getSuite(){
return suite;
}
public void setCity(String city){
this.city = city;
}
public String getCity(){
return city;
}
public void setStreet(String street){
this.street = street;
}
public String getStreet(){
return street;
}
#Override
public String toString(){
return
"Address{" +
"zipcode = '" + zipcode + '\'' +
",geo = '" + geo + '\'' +
",suite = '" + suite + '\'' +
",city = '" + city + '\'' +
",street = '" + street + '\'' +
"}";
}
}
RestApi interface:
public interface RestApi {
#GET("/users")
Call<List<ResponseDTO>> bring();
#GET("/users") Call<List<ResponseDTO>> bringResponse(#Query("id")String id, #Query("username")String usr_name);
#GET("/users") Call<List<Address>> bringAdress(#Query("id")String id, #Query("username")String usr_name);
//#GET("/users") Call<List<GeoDTO>> bringGeo(#Query("id")String id, #Query("username")String usr_name);
}
ManagerAll.java:
public class ManagerAll extends BaseManager {
private static ManagerAll ourInstance = new ManagerAll();
public static synchronized ManagerAll getInstance() {
return ourInstance;
}
public Call<List<ResponseDTO>> bringCall() {
Call<List<ResponseDTO>> x = getRestApi().bring();
return x;
}
public Call<List<Address>> managerGetAdress(String post, String username) {
Call<List<Address>> y = getRestApi().bringAdress(post, username);
return y;
}
public Call<List<ResponseDTO>> managerBringResponse(String post, String username) {
Call<List<ResponseDTO>> z = getRestApi().bringResponse(post, username);
return z;
}
}
This is ResponseDTO:
public class ResponseDTO implements Serializable {
private String website;
private AddressDTO address;
private String phone;
private String name;
private CompanyDTO company;
private int id;
private String email;
private String username;
public void setWebsite(String website){
this.website = website;
}
public String getWebsite(){
return website;
}
public void setAddress(AddressDTO address){
this.address = address;
}
public AddressDTO getAddress(){
return address;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getPhone(){
return phone;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setCompany(CompanyDTO company){
this.company = company;
}
public CompanyDTO getCompany(){
return company;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return username;
}
#Override
public String toString(){
return
"ResponseDTO{" +
"website = '" + website + '\'' +
",address = '" + address + '\'' +
",phone = '" + phone + '\'' +
",name = '" + name + '\'' +
",company = '" + company + '\'' +
",id = '" + id + '\'' +
",email = '" + email + '\'' +
",username = '" + username + '\'' +
"}";
}
}
As i said, when i set the list in AddressPage AddressDto(or Address) to Response i can get datas. But it gives me null value when i set it to AddressDto.
GeoDTO:
public class GeoDTO implements Serializable {
private String lng;
private String lat;
public void setLng(String lng){
this.lng = lng;
}
public String getLng(){
return lng;
}
public void setLat(String lat){
this.lat = lat;
}
public String getLat(){
return lat;
}
#Override
public String toString(){
return
"GeoDTO{" +
"lng = '" + lng + '\'' +
",lat = '" + lat + '\'' +
"}";
}
}
CompanyDTO:
public class CompanyDTO implements Serializable {
private String bs;
private String catchPhrase;
private String name;
public void setBs(String bs){
this.bs = bs;
}
public String getBs(){
return bs;
}
public void setCatchPhrase(String catchPhrase){
this.catchPhrase = catchPhrase;
}
public String getCatchPhrase(){
return catchPhrase;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
#Override
public String toString(){
return
"CompanyDTO{" +
"bs = '" + bs + '\'' +
",catchPhrase = '" + catchPhrase + '\'' +
",name = '" + name + '\'' +
"}";
}
}
Address class is not similar to your json response so you are not getting data from your service . You can read first ResponseDTO data then read address data from json.
I have my entity class called employee and I want to soft delete my entity when I select and press delete button. I can able to select multiple employees as well, So in Java I used List of employee Entities and I want to update whole list into database table if I use merge of entityManager I can able to update only one row i.e only one entity so how do I solve this problem?
Here is some sample code.
#Entity
#Table(name="EmpInfo",schema="Auth")
public class EmpInfo{
#Id
#Column(name="EmpId")
private String userId;
#Column(name="EmailId")
private String emailId;
#Column(name="FirstName")
private String firstName;
#Column(name="LastName")
private String lastName;
#Column(name="MiddleName")
private String middleName;
#Column(name="UserAttributes")
private String userAttributes;
#Column(name="AddedDate")
private Timestamp addedDate;
#Column(name="ModifiedDate")
private Timestamp modifiedDate;
#Column(name="LastLoginDate")
private Timestamp lastLoginDate;
#Column(name="IsDeleted")
private int isDeleted;
#Column(name="AddedBy")
private String addedBy;
#Transient
private String addedByEmailId;
public String getAddedByEmailId() {
return addedByEmailId;
}
public void setAddedByEmailId(String addedByEmailId) {
this.addedByEmailId = addedByEmailId;
}
public EmpInfo() {
// TODO Auto-generated constructor stub
}
public EmpInfo(EmpInfo uInfo){
super();
this.userId=uInfo.userId;
this.emailId=uInfo.emailId;
this.firstName=uInfo.firstName;
this.lastName=uInfo.lastName;
this.middleName=uInfo.middleName;
this.userAttributes=uInfo.userAttributes;
this.addedDate=uInfo.addedDate;
this.lastLoginDate=uInfo.lastLoginDate;
this.modifiedDate=uInfo.modifiedDate;
this.addedBy=uInfo.addedBy;
this.roles=uInfo.roles;
}
public List<RoleName> getRoles() {
return roles;
}
public void setRoles(List<RoleName> roles) {
this.roles = roles;
}
public int getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(int isDeleted) {
this.isDeleted = isDeleted;
}
public Date getAddedDate() {
return addedDate;
}
public void setAddedDate(Timestamp addedDate) {
this.addedDate = addedDate;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Timestamp modifiedDate) {
this.modifiedDate = modifiedDate;
}
public Date getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(Timestamp lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getUserAttributes() {
return userAttributes;
}
public void setUserAttributes(String userAttributes) {
this.userAttributes = userAttributes;
}
public String getAddedBy() {
return addedBy;
}
public void setAddedBy(String addedBy) {
this.addedBy = addedBy;
}
#Override
public String toString() {
return "EmpInfo [userId=" + userId + ", emailId=" + emailId + ", firstName=" + firstName + ", lastName="
+ lastName + ", middleName=" + middleName + ", userAttributes=" + userAttributes + ", addedDate="
+ addedDate + ", modifiedDate=" + modifiedDate + ", lastLoginDate=" + lastLoginDate + ", isDeleted="
+ isDeleted + ", addedBy=" + addedBy + "]";
}
}
public interface EmpInfoRepository extends JpaRepository<EmpInfo, String> {
}
use this to save list of entities as follows
#Autowired
private EmpInfoRepository empInfoRepository;
empInfoRepository.save(listOfEntity)
Since there is no custom implementation defined, implementation done by SimpleJpaRepository will be used, which will update the entities according to the #Id annotated field
I have done this is the past with mySQL but I need to use Oracle:
This is a very simple register user:
application.properties
#Oracle database setup
spring.datasource.url=jdbc:oracle:thin:#999.999.999.11:1521:d3SID
spring.datasource.username=userName
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
server.port = 4000
UserInformation model
#Entity
public class UserInformation {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "firstName")
#Min(2) #Max(15)
#NotNull
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "userName")
private String userName;
#Column(name = "password")
private String password;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof UserInformation)) {
return false;
}
UserInformation that = (UserInformation) o;
return id.equals(that.id);
}
#Override
public int hashCode() {
return id.hashCode();
}
#Override
public String toString() {
return "Applicant{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", userName='" + userName + '\'' + ", password='" +
password + '\'' + '}';
}
}
JPA repo
public interface UserLoginRepo extends JpaRepository<UserInformation, Long> {}
Controller method
#RequestMapping(value = "/register", method = RequestMethod.POST)
public UserInformation registerUser(#RequestBody UserInformation user){
return userService.save(user);
}
When I run SELECT * FROM USERINFORMATION; nothing displays.
From my understanding I should not need to set up JPA config since I am doing it in applications.properties.
Did you check if the UserInformation object is coming from request body? As I know you shouldn't use "#RequestBody", just put "UserInformation user" must be in the parameters.