Adding List<object> to class - class

New programmer here, I'm trying to add a List object to a list within another class but it keeps giving me an error.I've been stuck on this problem for hours now
void main()
{
List<Hobbies> hobby;
Hobbies hobbies = new Hobbies("Football");
hobby.add(hobbies);
User user1 = new User("Harris", 22, hobby);
print(user1.getAge());
}
class User
{
String name;
int age;
List<Hobbies> hobbies;
User(String name, int age, List<Hobbies> hobbies)
{
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
getAge()
{
print(name);
}
}
class Hobbies
{
String name;
Hobbies(String name)
{
this.name = name;
}
getAge()
{
print(name);
}
}
The error i keep getting
TypeError: C.JSNull_methods.add$1 is not a functionError: TypeError: C.JSNull_methods.add$1 is not a function

You mixed a lot of things here, but let's try to unwrap it all one by one. :)
So few things regarding naming conventions to make your life easier:
Don't use plurals for object names if they are representing one item, and not a list of something.
Always use plurals for property of type list.
Getter methods should always return a type, if you miss that part, you won't see compile time errors your upper project has at the moment trying to print variables instead of returning values, and than again printing in main file for 2nd time...
If you follow those principles, you would get your objects looking like this
class User {
String name;
int age;
List<Hobby> hobbies;
User(String name, int age, List<Hobby> hobbies) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
}
int getAge() => print(name);
}
class Hobby {
String name;
Hobby(String name) {
this.name = name;
}
String getName() => this.name;
}
After this is sorted, let's approach adding data and initialising those objects:
void main() {
List<Hobby> hobbies = [Hobby("Football")];
User user1 = new User("Harris", 22, hobbies);
print(user1.getAge().toString());
}

You need to initialize a List, otherwise it is null and null has no add, so do this:
final hobby = List<Hobbies>();
// or final List<Hobbies> hobby = [];
// or final hobby = <Hobby>[];
Hobbies hobbies = new Hobbies("Football");
hobby.add(hobbies);
final user1 = User("Harris", 22, hobby);

Related

DART/FLUTTER - Check if a class value has already been instantiated

I have a class with the following attributes in Dart
class StartValue {
final int id;
final String firstName;
final String lastName;
StartValue({this.id, this.firstName, this.lastName})
}
and Ill initiate that classe with the values:
StartValue(
id: 1,
firstName: 'First',
lastName: 'LastName'
)
The question is what kind of validation i need to do to never instance a class StartValue with the NAME = 'First' again? Assuming I can only instantiate the class once with firstName = 'First'.
How do I do an instance validation to verify that each instance does not contain the firstName = "First" ?
I have to do something like:
StartValues.contains("First")
Keep in mind that I have almost 1000 classes instantiated, so I will have to check one by one if the value "First" contains in each class, this is my question
You have to iterate through every class to check if the firstName is taken, but I recommend using the == operator instead of .contains(). Why would you have 1000 instances? Can you put us in context?
Use a class-static Set of all ids seen so far. This will be quick to identify whether an item has already been generated.
Something like:
class Person {
final int id;
final String name;
static var seenIds = <int>{};
Person({
required this.id,
required this.name,
}) {
if (!seenIds.add(id)) throw ArgumentError('id $id already seen');
}
}
Keeping thousands of instances / names in memory is bad design as they are way too many instances / names you don't need at that moment. You go for local sql database like sqflite or you go for cloud database like Cloud Firestore to fetch the user you need and validate it.
If you still want to do it in-memory you can use a factory constructor, a private constructor and a static HashSet to check user instances.
If you need explanation then comment below. Full code example:
import 'dart:collection';
class Person {
final int id;
final String firstName;
final String lastName;
static HashSet<String> allNames = HashSet<String>();
factory Person({
required int id,
required String firstName,
required String lastName,
}) {
if (!allNames.add(firstName)) {
throw ArgumentError("Person with firstname $firstName already exists");
}
return Person._(id: id, firstName: firstName, lastName: lastName);
}
Person._({
required this.id,
required this.firstName,
required this.lastName
});
}

method in ArangoRepository extension class using COLLECT in query annotation to group by and count not working

I have a simple node like this below
#Document("users")
public class User {
#Id // db document field: _key
private String id;
#ArangoId // db document field: _id
private String arangoId;
private String firstName;
private String lastName;
private String country;
public User() {
super();
}
public User(String id) {
this.id = id;
}
public User(String id, String country) {
this.id = id;
this.country = country;
}
// getter & setter
#Override
public String toString() {
return "User [id=" + id + ", name=" + firstName + ", surname=" + lastName + "]";
}
public String getId() {
return id;
}
}
here is the repository class but the method getListOfCountryAndNumUsers returns null even though i have inserted users with different countries into the database.
public interface UserRepository extends ArangoRepository<User, String> {
#Query("FOR u IN users COLLECT country = u.country WITH COUNT INTO length RETURN
{\"country\" : country, \"count\" : length }")
Iterable<CountryAndNumUsers> getListOfCountryAndNumUsers();
}
I think the problem could be with the the syntax of my query in the query annotation. I didnt see any direct example of using collect operation in the spring data arango db part of arangodb documentation here but I saw the collect operation in the section "high level operations" of arangoDb documentation here
Please Help. Thanks. !
So I discovered my error. It was in a class I didn't add in the question. That is the class for the return object of the method getListOfCountryAndNumUsers()
i.e class CountryAndNumUsers.
public class CountryAndNumUsers {
private String country;
private Integer numberOfUsers;
public CountryAndNumUsers(String country, Integer numberOfUsers) {
this.country = country;
this.numberOfUsers = numberOfUsers;
}
public String getCountry() {
return country;
}
public Integer getNumberOfUsers() {
return numberOfUsers;
}
}
so there was a mapping mismatch since the query returns an object with different field names. I changed the query to this below so that it matches
#Query("FOR u IN users COLLECT country = u.country WITH COUNT INTO length RETURN {\"country\" : country, \"numberOfUsers\" : length }")

update mongodb document using java object

I have one User class like this:
#Document(collection = "users")
public class User {
#Id
private String id;
String username;
String password;
String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "User[id=" + id + ", username=" + username + ", password=" + password + ", description"
+ description + "]";
}
}
I am able to perform limited update. Like:
Query searchQuery = new Query(Criteria.where("id").is("shashi"));
mongoDBClient.updateFirst(searchQuery, Update.update("password", "newpassword"), User.class);
Now if I want to update rest other fields(username and description) of User class, I need to call updateFirst method so many times.
I want to avoid this and pass the entire object to updateFirst method. Something like:
mongoDBClient.updateFirst(searchQuery, Update.update(userObject), User.class);
Basically, I want to edit all/multiple fields in one call using java POJO object. How I can achieve this?
Edit/All multiple fields in one call using java POJO object, can be done as shown below
1) Query the document which need to be updated --> we get the java object
2) Do all modifications in the java object
3) Save the object
Code:
Query query = new Query();
query.addCriteria(Criteria.where("id").is("shashi"));
User user = mongoOperation.findOne(query, User.class);
//modify the user object with the properties need to be updated
//Modify password and other fields
user.setPassword("newpassword");
user.setDescription("new description");
user.setUsername("NewUserName");
//save the modified object
mongoOperation.save(user);

dropdownchoice with choicerenderer, how to get values

i have problem trying to get some values. this is my situation (wicket)
i have a dropdownchoice study_template, i don't have problem populating the DDC, the problem is when i try to get some value (id or name). this is the code
ChoiceRenderer choiceRenderer = new ChoiceRenderer("name", "id");
study_template = new DropDownChoice( "study_template",new PropertyModel( this, "selectedTemplate" ),template_names , choiceRenderer);
template_names is a list< SelectOption > with the values obtain from a DB. this works OK.
this is the class that i use to populate the DDC
public class SelectOption implements java.io.Serializable {
private long id;
private String name;
public SelectOption(long id, String name ) {
this.id = id; this.name=name;
}
public long getId()
{return id; }
public String getName()
{return name; }
}
normally i can get the value with study_template.getModelObject(), but in this case it doesn't work, i don't have any ideas about to obtain the id and the name , i know that i need GETID() and GETNAME(), but i don't know how to use it, any help will be appreciated
You could use something as below:
public class SpikePage extends WebPage {
class Person {
String id;
String name;
public Person(String id, String name) {
this.id = id;
this.name = name;
}
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 SpikePage() {
Person employee = new Person("E001", "ABC");
Person manager = new Person("E002", "XYZ");
List personList = new ArrayList(2);
personList.add(employee);
personList.add(manager);
Form form = new Form("form");
final DropDownChoice personDropDownChoice = new DropDownChoice("person", new ArrayList(personList), new IChoiceRenderer() {
#Override
public Object getDisplayValue(Person object) {
return object.getId().concat("-").concat(object.getName());
}
#Override
public String getIdValue(Person object, int index) {
return object.getId();
}
});
personDropDownChoice.setOutputMarkupId(true);
personDropDownChoice.setNullValid(false);
form.add(personDropDownChoice);
final Label label = new Label("name");
label.setOutputMarkupId(true);
form.add(label);
personDropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") {
#Override
protected void onUpdate(AjaxRequestTarget target) {
Person selectedPerson = personDropDownChoice.getModelObject();
label.setDefaultModelObject("Hi ".concat(selectedPerson.getName()));
target.add(label);
}
});
add(form);
}
}
Thanks for your answer, i already get it work
i use this
private SelectOption selectedTemplate;
and then
selectedTemplate.getId();

"DataNucleus Enhancer completed with an error"

Am trying to create a model class to store an Entity in Google App Engine using Eclipse.But when i save my work i get the error message:
org.datanucleus.metadata.MetaDataManager initialiseFileMetaDataForUse.
SEVERE: Class "com.packagename.classname" has been specified with an object-id class javax.jdo.identity.StringIdentity yet no fields have been identified as primary key fields. Please notate using the "primary-key" tag against the fields that should be considered part of the primary key.
If my understanding of JPA is correct, i do not need a primary-key for an entity since i already have a #Id tag.Here is my class.
#Entity
public class MyCLassName {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private static String userName;
private static String location;
private static Date dateOfBirth;
private static int age;
private static String gender;
private static String teamName;
private static int weight;
//Constructor with arguments
public MyClassName(String userName, String location, String gender, int age, Date DOB, int weight) {
MyClassName.userName = userName;
MyClassName.location = location;
MyClassName.gender = gender;
MyClassName.age=age;
MyClassName = DOB;
MyClassName.weight = weight;
}
//setter methods
public static void setUserName(String userName) {
MyClassName.userName = userName;
}
public static void setLocation(String location) {
MyClassName.location = location;
}
public static void setGender(String gender) {
MyClassName.gender = gender;
}
public static void setAge(int age) {
MyClassName.age = age;
}
public static void setDateOfBirth(Date dateOfBirth) {
MyClassName.dateOfBirth = dateOfBirth;
}
public static void setWeight(int weight) {
MyClassName.weight = weight;
}
//getter methods
public static String getUserName() {
return userName;
}
public static int getWeight() {
return weight;
}
public static String getLocation() {
return location;
}
public static String getGender() {
return gender;
}
public static String getTeamName() {
return teamName;
}
public static Date getDateOfBirth() {
return dateOfBirth;
}
public static int getAge() {
return age;
}
}
What exactly am i doing wrong here?
Your understanding of JPA is partially correct. You do not need to assign the primary key because you have used the #Id and #GeneratedValue annotation. The JPA implementation will automatically generate the primary key value as a long integer. However it still needs a field in which to store this ID value. It is trying to do that in userName. See Java Tutorial ID Generation Type: IDENTITY for example.