Add items from ArrayList to Array and show in JList - arrays

I am trying to add all the items from ArrayList<String> to String[] array which is in another class but i am fail to do that. I have tried many of the ways but to not avail. The String[] array in another class does not display any item. Hence, I was fail to add the array to the JList. I have no idea to deal with it. Here is my code:
public class bookbook extends JFrame{
java.util.List<String> timeList = new ArrayList<String>();
public bookbook(){
selectTime.timeArr = new String[ timeList.size() ];
timeList.toArray(selectTime.timeArr);
}
}
public class SelectTime extends JFrame{
String[] timeArr = {};
private JList jlstTime = new JList(timeArr);
public SelectTime(){
jpTicket.add(jlstTime);
}
}
I really need your help. Thanks!

You are modifying the JList array directly, which, as the documentation states, will result in an undefined behaviour. Try this code: Added the function updateList to the class SelectTime to do it using the appropiate methods
public class bookbook extends JFrame{
java.util.List<String> timeList = new ArrayList<String>();
public bookbook(){
String [] timeArr = new String[ timeList.size() ];
timeList.toArray(selectTime.timeArr);
selectTime.updateList(timeArr);
}
}
-
public class SelectTime extends JFrame{
String[] timeArr = {};
private JList jlstTime = new JList(timeArr);
public SelectTime(){
jpTicket.add(jlstTime);
}
public void updateList(String [] array)
{
jlstTime.setListData(array);
jlstTime.invalidate();
}
}

Related

I am not able to deserialize my json response in listview

This is my code of my class which gets the json response in "resp".
public class Caller extends Thread {
public CallSoap cs;
public String resp, Blood_Group, City;
ClassObj object;
Gson gson = new GsonBuilder().create();
public void run() {
try {
cs = new CallSoap();
resp = cs.CallGetDonorList(Blood_Group, City);
object = gson.fromJson(resp,ClassObj.class);
int a = 0;
}catch(Exception ex)
{
MainActivity.rslt=ex.toString();
}
}
}
resp has value like this:
[{
"Donor_Id":1,
"Donor_Name":"Rakesh",
"Donor_ContactNo":9044234578,
"Blood_Group":"A+",
"City":"Lucknow"},
{....}
]
and I have created a class to serialize these values as:
import com.google.gson.annotations.SerializedName;
public class ClassObj {
#SerializedName("Donor_Id")
private int Donor_Id;
#SerializedName("Donor_Name")
private String Donor_Name;
#SerializedName("Donor_ContactNo")
private String Donor_ContactNo;
#SerializedName("Blood_Group")
private String Blood_Group;
#SerializedName("City")
private String City;
}
You're trying to deserialize an array of donor objects, not just a single one. As such, you'll need to specify the type correctly:
//declaration
ClassObj[] objects;
//deserialization
objects = gson.fromJson(resp,ClassObj[].class);
I would also strongly consider naming your classes and variables appropriately, i.e. ClassObj could be Donor and objects could be donors.

Storing objects in array (Haxe)

How would I go about sorting an new instance of an object into an array in Haxe?
For example I have a class called weapon and in the player class I gave an array inventory.
So how would I store this?
private void gun:Weapon
gun = new Weapon; //into the array
I think you are looking for this:
private var inventory:Array<Weapon>;
This is an array of type Weapon.
To add stuff to it use push(), as seen in this example:
class Test {
static function main() new Test();
// create new array
private var inventory:Array<Weapon> = [];
public function new() {
var weapon1 = new Weapon("minigun");
inventory.push(weapon1);
var weapon2 = new Weapon("rocket");
inventory.push(weapon2);
trace('inventory has ${inventory.length} weapons!');
trace('inventory:', inventory);
}
}
class Weapon {
public var name:String;
public function new(name:String) {
this.name = name;
}
}
Demo: http://try.haxe.org/#815bD
Found the answer must be writen like this
private var inventory:Array;
With Weapon being the class name.

Reference of returned object?

If I have a class as follows:
class MyClass
{
List<String> list{get;set;}
...
}
And then execute:
MyClass instance = new MyClass();
instance.add('string') ;
Will that new entry in the list be added to the member variable instance?
No. What you trying to do should be more like
class MyClass{
public List<String> list{get;set;}
}
and then execute
MyClass instance = new MyClass();
instance.list.add('string');

how to force jettison to write an array, even if there is only one element in the array?

With the simplified example below:
I get the following, as expected:
{"person":{"name":"john","tags":["tag1","tag2"]}}
However, if I only set one tag, I get this:
{"person":{"name":"john","tags":"tag1"}}
And I was expecting to get this:
{"person":{"name":"john","tags":["tag1"]}}
That is, jettison has removed the array for tags, because there is only one element in the array.
I think this is pretty unsafe.
How to force jettison to write an array, even if there is only one element?
Note: I am aware that there are other alternatives to jettison, such as StAXON.
However, here I am asking how to achieve this using Jettison.
Please do not suggest another alternative to jettison.
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.*;
import java.io.*;
import javax.xml.bind.*;
import javax.xml.stream.XMLStreamWriter;
import org.codehaus.jettison.mapped.*;
public class JettisonTest {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Person.class);
Person person = new Person();
person.name = "john";
person.tags.add("tag1");
person.tags.add("tag2");
Configuration config = new Configuration();
MappedNamespaceConvention con = new MappedNamespaceConvention(config);
Writer writer = new OutputStreamWriter(System.out);
XMLStreamWriter xmlStreamWriter = new MappedXMLStreamWriter(con, writer);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(person, xmlStreamWriter);
}
}
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
class Person {
String name;
List<String> tags = new ArrayList<String>();
}
I found this: https://blogs.oracle.com/japod/entry/missing_brackets_at_json_one
It seems that adding a line to your context resolver to explicitly state that tags is an array is the way to do this; i.e.
props.put(JSONJAXBContext.JSON_ARRAYS, "[\\"tags\\"]");
NB: I'm not familiar with Jettison, so have no personal experience to back this up; only the info on the above blog post.
#Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class[] types = {ArrayWrapper.class};
public JAXBContextResolver() throws Exception {
Map props = new HashMap<String, Object>();
props.put(JSONJAXBContext.JSON_NOTATION, "MAPPED");
props.put(JSONJAXBContext.JSON_ROOT_UNWRAPPING, Boolean.TRUE);
props.put(JSONJAXBContext.JSON_ARRAYS, "[\\"tags\\"]"); //STATE WHICH ELEMENT IS AN ARRAY
this.context = new JSONJAXBContext(types, props);
}
public JAXBContext getContext(Class<?> objectType) {
return (types[0].equals(objectType)) ? context : null;
}
}

mongo morphia howto Safely remove a string from a String array

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!

Resources