I want to create a js array of type
Name(
{title : "Mr.",firstname : "Bill",lastname : "Gates"},
{title : "Mr.",firstname : "Bill",lastname : "Gates"},
{title : "Mr.",firstname : "Bill",lastname : "Gates"}
)
So basically i want to create associated array.
All the examples are like converting javascript array to java but in my case i want the other way round. I will be filling this array from java.
JSArray and JsMixedArray seems to be doing this but i could figure out how to add to them.
One approach could be to use a JSNI method to create the items/entries of your Array/Map as follows:
JsArray arr = JavaScriptObject.createArray().cast();
arr.push(newEntry("Mr.", "Bill", "Gates"));
....
private final native JavaScriptObject newEntry(String title,
String firstname, String lastname)/*-{
return {title: title, firstname: firstname, lastname: lastname};
}-*/;
You could also try to create the data structure you have in mind using the JSON utility methods: Put JSONObjects inside a JSONArray.
Variable $wnd.v will contain an array of objects.
Note: you will need to find a way how to convert your Java objects to a JSON (i used restygwt).
class PersonList {
List<Person> list;
}
class Person {
String title;
String firstName;
String lastName;
public Person () {}
public Person(String title, String firstName, String lastName) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
}
}
public class Main implements EntryPoint {
public interface PersonCodec extends JsonEncoderDecoder<PersonList> {
}
PersonCodec personCodec = GWT.create(PersonCodec.class);
public void onModuleLoad() {
List<Person> list = new ArrayList<Person>();
list.add(new Person("Mr.", "Bill", "Gates"));
list.add(new Person("Mr.", "Andrey", "Mormysh"));
PersonList personList = new PersonList();
personList.list = list;
String json = personCodec.encode(personList).toString();
setPersonList(json);
}
public static native void setPersonList(String personListJson)/*-{
$wnd.v = eval("(" + personListJson + ")").list;
alert($wnd.v[0].firstName); // Output: 'Bill'
}-*/;
}
You can create empty JavaScriptObject from Java but you cannot populate them from there, so use the dark side of the force:
private native JavaScriptObject putString(JavaScriptObject jso, String key, String value)/*-{
jso[key] = value;
return jso;
}-*/;
private native JavaScriptObject putObject(JavaScriptObject jso, String key, JavaScriptObject value)/*-{
jso[key] = value;
return jso;
}-*/;
void someJavaFunction() {
JavaScriptObject fromJava = JavaScriptObject.createObject();
fromJava = putString(fromJava, "foo", "bar");
fromJava = putObject(fromJava, "baz", fromJava);
}
Related
Im trying to access the Spring splitting method from Person class in Main class, but it doesn't show me only the last result from the text. Its working very good when im integrating System.out.prinln in Person class, in method body but In this homework im not aloud to use System.out in Person class, only in Main class. The result must split the text in "Surname , Name , City". Where am i doing wrong? Thank you!
public class Person {
public String surname;
public String name;
public String city;
public Person(String text) {
String[] person = text.split(" ");
for (int i = 0; i < person.length; i++) {
String surname = person[i].split("[.]")[0];
String name = person[i].split("[./]")[1];
String city = person[i].split("/")[1];
this.surname = surname;
this.name = name;
this.city = city;
}
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person("John.Davidson/Berlin Michael.Barton/Rome Ivan.Perkinson/Munich");
System.out.println(p1.surname + p1.name + p1.city);
// the result is the only the last persons info
}
}
I am trying to achieve many-to-many relationship in Room Persistence Library. I am trying to create a Notes App with Tags.
The idea is:
A note will have multiple tags.
A tag will have multiple notes.
Show all notes in RecyclerView along with Tags.
To achieve this, I have created two models Note.java, Tag.java and TagJoin model to store the relationship b/w notes and tags. Achieving one-to-one is very easy using #Relation annotation.
Here are my models
#Entity(tableName = "notes")
public class Note {
#PrimaryKey
#NonNull
public final String id;
#ColumnInfo(name = "note")
public String note;
#Ignore
public List<Tag> tags;
#Ignore
public Note(String note) {
this(UUID.randomUUID().toString(), note);
}
public Note(String id, String note) {
this.id = id;
this.note = note;
}
public String getId() {
return id;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
#Entity(tableName = "note_tag_join",
primaryKeys = {"noteId", "tagId"},
foreignKeys = {
#ForeignKey(
entity = Note.class,
parentColumns = "id",
childColumns = "noteId",
onDelete = CASCADE),
#ForeignKey(
entity = Tag.class,
parentColumns = "id",
childColumns = "tagId",
onDelete = CASCADE)},
indices = {
#Index(value = "noteId"),
#Index(value = "tagId")
}
)
public static class TagJoin {
#NonNull
public final String noteId;
#NonNull
public final String tagId;
public TagJoin(String noteId, String tagId) {
this.noteId = noteId;
this.tagId = tagId;
}
}
}
Tags Model:
#Entity(tableName = "tags", indices = {#Index(value = "name", unique = true)})
public class Tag {
#PrimaryKey
#NonNull
public String id;
#ColumnInfo(name = "name")
public String name;
#Ignore
public Tag(String name) {
this(UUID.randomUUID().toString(), name);
}
public Tag(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Notes Dao:
#Dao
public interface NoteDao {
#Query("SELECT * FROM notes ORDER BY id DESC")
LiveData<List<Note>> getAllNotes();
#Insert
long insert(Note note);
#Update
void update(Note note);
#Delete
void delete(Note note);
#Query("DELETE FROM notes")
void deleteAll();
#Query("SELECT COUNT(*) FROM notes")
int getNotesCount();
#Query("SELECT notes.* FROM notes\n" +
"INNER JOIN note_tag_join ON notes.id=note_tag_join.noteId\n" +
"WHERE note_tag_join.tagId=:tagId")
List<Note> getAllNotesOfTag(String tagId);
#Insert
void insert(Note.TagJoin... joins);
#Delete
void delete(Note.TagJoin... joins);
}
So far everything is good. Now I want to show the Notes in RecyclerView but I can't find a way to fetch all Notes along with Tags at once. One way is, getting the tags of each note in onBindViewHolder method which I think is wrong as we have to query the db each time row is displayed.
Please provide me suggestions.
PS: I have followed the code provided in this article
https://commonsware.com/AndroidArch/previews/mn-relations-in-room
I'm trying to bind a list of data to a data grid, but can't do it. I'm giving my code here.
I have made a class like this:
public class Book
{
int bookID;
string bookName;
string athourName;
public Book(int BookID, string BookName, string AuthorName)
{
bookID = BookID;
bookName = BookName;
athourName = AuthorName;
}
}
Under form load event, I wrote the following code:
private void Form1_Load(object sender, EventArgs e)
{
Book Book1 = new Book(001, "Java", "Harbart");
Book Book2 = new Book(002, "C", "Balaguru");
string[] BookArray = new string[10];
BookArray[0] = Book1.ToString();
BookArray[1] = Book2.ToString();
List<Book> Obj = new List<Book>();
Obj.Add(Book1);
Obj.Add(Book2);
dataGridView1.DataSource = Obj;
}
This doesn't give any error, but also not showing any data in the data grid. I have a feeling I'm missing something in between. A clarification on how to bind data to data grid would be very helpful.
The DataGridView requires public properties to autogenerate its columns. It will not work with fields, either public or private.
Change your class to this:
public class Book
{
public int bookID { get; set; }
public string bookName { get; set; }
public string athourName { get; set; }
public Book(int BookID, string BookName, string AuthorName)
{
bookID = BookID;
bookName = BookName;
athourName = AuthorName;
}
}
That uses auto-properties but you can of course use the longhand syntax as well.
How do I obtain values of an array that is located inside a java object in a jsp page?
I have set an object attribute so that in the jsp page I can call the object like so
${obj.property}
My question is how would I obtain property String [] example from Object obj?
<c:forEach var="prop" items="${obj.example}">
<td>${prop}</td>
</c:forEach>
I get Errors that tell me the class obj.Obj does not have the property property 'example'
and obviously I don't get the data out.
Actual errors:
org.apache.jasper.JasperException: javax.el.PropertyNotFoundException: The class 'roommate.Roommate' does not have the property 'favProfessors'.
javax.el.PropertyNotFoundException: The class 'roommate.Roommate' does not have the property 'favProfessors'
And my actual class:
package roommate;
public class Roommate{
public String firstname;
public String lastname;
public String gender;
public String place;
public String[] favProfessors;
public Roommate(String fname, String lname, String roommateGender, String hangout,String[] professors) {
firstname= fname;
lastname= lname;
gender= roommateGender;
place= hangout;
favProfessors= professors;
}
public String getFirstname()
{
return firstname;
}
public void setFirstname(String newFirstname)
{
this.firstname = newFirstname;
}
public String getLastname()
{
return lastname;
}
public void setLastname(String newLastname)
{
this.lastname = newLastname;
}
public String getGender()
{
return gender;
}
public void setGender(String newGender)
{
this.gender = newGender;
}
public String getHangout()
{
return place;
}
public void setHangout(String newPlace)
{
this.place = newPlace;
}
public String[] getProfessors()
{
return favProfessors;
}
public void setProfessors(final String[] newfavProfessors)
{
this.favProfessors = newfavProfessors;
}
public void addRoommate(String fname, String lname, String roommateGender, String hangout,String[] professors)
{
}
}
I create the object in my servlet as well ass the Atrribute
String [] profArray = request.getParameterValues("professor");
Roommate roommate= new Roommate(
session.getAttribute("fname").toString(),
session.getAttribute("lname").toString(),
session.getAttribute("gender").toString(),
session.getAttribute("hangout").toString(),
profArray);
session.setAttribute("roommate",roommate);
I asked this earlier but did not receive a clear answer. I think my issue is in pulling the data out in the jsp alone in my forEach that I mentioned at the top
javax.el.PropertyNotFoundException: The class 'roommate.Roommate' does not have the property 'favProfessors'
Java is right. You do not have a getFavProfessors() method in that class. It's instead the following:
public String[] getProfessors()
{
return favProfessors;
}
You have 2 options: use ${roommate.professors} instead, or fix the getter method name to be getFavProfessors().
In contrary to what most starters think, EL does not access private properties directly. EL just calls the public getter/setter methods according the Javabeans specification. The real private property behind it can have a completely different name or even not exist at all.
ok I have this (beginner again)
.
// ADD FRIEND TO FRIEND LIST
Query<FriendList> query1 = mongo.createQuery(FriendList.class);
query1.field("lowerCaseUserName").equal(on.lowerCaseUserName);
query1.field("passwordHash").equal(on.passwordHash);
query1.field("uuid").equal(on.uuid);
UpdateOperations<FriendList>up1=mongo.createUpdateOperations(FriendList.class).add("friendList",buddyUuid,false);
Im inserting a friend into the Array. The "friendList" is a String Array.
Would like to be able to implement removal now.
Can i just write the same code and replace the ".add" with removexxx...something?
Im thinking it's a good ide but maybe not :)
#Entity
public class FriendList {
#Id private ObjectId id;
public Date lastAccessedDate;
#Indexed(name="uuid", unique=true,dropDups=true)
private String uuid;
#Indexed(value=IndexDirection.ASC, name="lowerCaseUserName", unique=true,dropDups=true)
public String lowerCaseUserName;
public String passwordHash = "";
List<String> friendList;
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<String> getFriendList() {
return friendList;
}
public void insertFriend(String friend) {
this.friendList.add(friend);
}
// #PrePersist void prePersist() {
// lastAccessedDate = new Date();
// }
}
Query<FriendList> query1 = mongo.createQuery(FriendList.class);
query1.field("lowerCaseUserName").equal(on.lowerCaseUserName);
query1.field("passwordHash").equal(on.passwordHash);
query1.field("uuid").equal(on.uuid);
UpdateOperations<FriendList>up1=mongo.createUpdateOperations(FriendList.class).removeAll("friendList",buddyUuid);
This should remove the buddyUuid from the list.
If you could guarantee that the friendList contains unique UUID's then you could use removeFirst || removeLast method.
removeFirst/Last/All
Hope this helps!