I'm not sure why the albums aren't being serialized when the users are.
In the admin class, when I login, the userlist is populated in the JCombobox<String> userlist everytime I restart the program.
But the JComboBox<Album> comboBoxAlbumSelect isn't populated every time I restart the program.
Not sure why. Thanks.
Relevant code:
public class Admin extends JFrame implements ActionListener {
Backend backend = new Backend();
GuiCtrl ctrl = new GuiCtrl(backend);
private JComboBox<String> userlist = new JComboBox<String>();
public Admin() {
//same as login
userlist = new JComboBox<String>(getUserList());
}
public String[] getUserList() {
String[] ret = new String[backend.getUserList().size()];
int i = 0;
for (String s : backend.getUserList()) {
System.out.println(s);
ret[i++] = s;
}
return ret;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == logout) {
this.dispose();
new Login();
}
else if (e.getSource() == add) {
try {
if (ctrl.adduser(idNumberTF.getText(), fullNameTF.getText())) {
userlist.addItem(idNumberTF.getText());
backend.storeData();
} catch (IOException|ClassNotFoundException i) {}
}
}
}
public class MainAlbumPanelv2 extends JFrame implements ActionListener {
JButton btnCreateAlbum = new JButton("Create");
JComboBox<Album> comboBoxAlbumSelect = new JComboBox<Album>();
Backend backend = new Backend();
GuiCtrl ctrl = new GuiCtrl(backend);
User loggedInUser;
public MainAlbumPanelv2(User id) {
loggedInUser = id;
comboBoxAlbumSelect = new JComboBox<Album>(getAlbumList());
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCreateAlbum) {
if (ctrl.createAlbum(loggedInUser, textFieldCreateAlbum.getText())) {
Album newAlbum = new Album(textFieldCreateAlbum.getText());
comboBoxAlbumSelect.addItem(newAlbum);
}
try {
backend.storeData();
} catch (IOException i) {}
}
}
public Album[] getAlbumList() {
Album[] ret = new Album[loggedInUser.getAlbums().size()];
int i = 0;
for (Album a : loggedInUser.getAlbums()) {
System.out.println(a);
ret[i++] = a;
}
return ret;
}
}
-
public class GuiCtrl {
User loggedInUser;
Backend backend;
public GuiCtrl(Backend backend) {
this.backend = backend;
}
public boolean adduser(String user_id, String user_name) throws IOException, ClassNotFoundException {
if (backend.addUser(new User(user_id, user_name))) {
return true;
} else {
return false;
}
}
public boolean createAlbum(User user_id, String name) {
if (user_id.getAlbum(name) != null) {
return false;
} else {
user_id.addAlbum(name);
return true;
}
}
}
-
public class Backend {
private HashMap<String, User> userList = new HashMap<>();
StringTokenizer tokenizer;
public Backend() {
try {
populateList();
} catch (ClassNotFoundException | IOException e) {
throw new RuntimeException("Cannot read file");
}
}
public boolean addUser(User newUser)
{
String userId = newUser.getID();
if (userList.containsKey(userId)) {
return false;
}
userList.put(userId, newUser);
return true;
}
public void storeData() throws IOException
{
try
{
FileOutputStream file = new FileOutputStream("users.ser");
ObjectOutputStream out = new ObjectOutputStream(file);
out.writeObject(userList);
out.close();
file.close();
}
catch (IOException i)
{
i.printStackTrace();
}
}
public void populateList() throws IOException, ClassNotFoundException
{
try
{
FileInputStream file = new FileInputStream ("users.ser");
ObjectInputStream in = new ObjectInputStream(file);
userList = (HashMap<String, User>) in.readObject();
in.close();
file.close();
}
catch (IOException i)
{
i.printStackTrace();
userList = new HashMap();
}
}
}
public class Album implements Serializable{
private String name;
private ArrayList<Photo> photoList;
public Album(String name)
{
this.name = name;
photoList = new ArrayList<Photo>();
}
}
public class User implements Serializable{
private String id;
private String fullName;
private ArrayList<Album> albumList;
public User(String id, String fullName)
{
this.id = id;
this.fullName = fullName;
albumList = new ArrayList<Album>();
}
public int addAlbum(Album newAlbum)
{
Album currAlbum;
if (newAlbum == null)
{
return 0;
}
for (int x = 0; x < albumList.size(); x++)
{
currAlbum = albumList.get(x);
if (currAlbum.getName().equals(newAlbum.getName()))
{
return 0;
}
}
albumList.add(newAlbum);
return 1;
}
public ArrayList<Album> getAlbums()
{
return albumList;
}
}
Related
I find out a library of JavaWsDiscovery-0.2.jar. It is find out the ONVIF camera on same network, when I simply run the jar file in android studio, it runs successfully.
But when I want to use it in our project, it does not run just because of Private method.
In this library two methods are private those are not accessible to another class.
When i editing in jar file. so, it shows the compilation Error.
So, I need help in this regard, thank you.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btn;
ListView values;
List<String> value;
String[] args;
public static int WS_DISCOVERY_TIMEOUT = 4000;
public static int WS_DISCOVERY_PORT = 3702;
public static String WS_DISCOVERY_ADDRESS_IPv4 = "239.255.255.250";
public static String WS_DISCOVERY_ADDRESS_IPv6 = "[FF02::C]";
public static String WS_DISCOVERY_PROBE_MESSAGE = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:tns=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\"><soap:Header><wsa:Action>http://schemas.xmlsoap.org/ws/2005/04/discovery/Probe</wsa:Action><wsa:MessageID>urn:uuid:c032cfdd-c3ca-49dc-820e-ee6696ad63e2</wsa:MessageID><wsa:To>urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To></soap:Header><soap:Body><tns:Probe/></soap:Body></soap:Envelope>";
private static final Random random = new SecureRandom();
String filepath = "/mnt/sdcard/Android/data/com.onvif.camera/com.onvif.javaWsDiscovery-0.2.jar";
static DeviceDiscovery deviceDiscovery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
deviceDiscovery = new DeviceDiscovery();
btn = (Button) findViewById(R.id.button);
values = (ListView) findViewById(R.id.values);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
main(args);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) throws InterruptedException {
Iterator i$ = discoverWsDevicesAsUrls().iterator();
while(i$.hasNext()) {
URL url = (URL)i$.next();
System.out.println("Device discovered: " + url.toString());
}
}
public static Collection<URL> discoverWsDevicesAsUrls() {
return discoverWsDevicesAsUrls("", "");
}
public static Collection<URL> discoverWsDevicesAsUrls(String regexpProtocol, String regexpPath) {
TreeSet urls = new TreeSet(new Comparator() {
#Override
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
});
Iterator i$ = discoverWsDevices().iterator();
while(i$.hasNext()) {
String key = (String)i$.next();
try {
URL e = new URL(key);
boolean ok = true;
if(regexpProtocol.length() > 0 && !e.getProtocol().matches(regexpProtocol)) {
ok = false;
}
if(regexpPath.length() > 0 && !e.getPath().matches(regexpPath)) {
ok = false;
}
if(ok) {
urls.add(e);
}
} catch (MalformedURLException var7) {
var7.printStackTrace();
}
}
return urls;
}
public static Collection<String> discoverWsDevices() {
final ConcurrentSkipListSet addresses = new ConcurrentSkipListSet();
final CountDownLatch serverStarted = new CountDownLatch(1);
final CountDownLatch serverFinished = new CountDownLatch(1);
ArrayList addressList = new ArrayList();
try {
Enumeration executorService = NetworkInterface.getNetworkInterfaces();
if(executorService != null) {
label45:
while(true) {
NetworkInterface ignored;
do {
if(!executorService.hasMoreElements()) {
break label45;
}
ignored = (NetworkInterface)executorService.nextElement();
} while(ignored.isLoopback());
List address = ignored.getInterfaceAddresses();
Iterator runnable = address.iterator();
while(runnable.hasNext()) {
InterfaceAddress address1 = (InterfaceAddress)runnable.next();
addressList.add(address1.getAddress());
}
}
}
} catch (SocketException var10) {
var10.printStackTrace();
}
ExecutorService executorService1 = Executors.newCachedThreadPool();
Iterator ignored1 = addressList.iterator();
while(ignored1.hasNext()) {
final InetAddress address2 = (InetAddress)ignored1.next();
Runnable runnable1 = new Runnable() {
public void run() {
try {
String e = UUID.randomUUID().toString();
String probe = WS_DISCOVERY_PROBE_MESSAGE.replaceAll("<wsa:MessageID>urn:uuid:.*</wsa:MessageID>", "<wsa:MessageID>urn:uuid:" + e + "</wsa:MessageID>");
int port = random.nextInt(20000) + '鱀';
final DatagramSocket server = new DatagramSocket(port, address2);
(new Thread() {
public void run() {
try {
DatagramPacket e = new DatagramPacket(new byte[4096], 4096);
server.setSoTimeout(WS_DISCOVERY_TIMEOUT);
long timerStarted = System.currentTimeMillis();
while(System.currentTimeMillis() - timerStarted < (long)WS_DISCOVERY_TIMEOUT) {
serverStarted.countDown();
server.receive(e);
Collection collection = deviceDiscovery.parseSoapResponseForUrls(Arrays.copyOf(e.getData(), e.getLength()));
Iterator i$ = collection.iterator();
while(i$.hasNext()) {
String key = (String)i$.next();
addresses.add(key);
}
}
} catch (SocketTimeoutException var11) {
;
} catch (Exception var12) {
var12.printStackTrace();
} finally {
serverFinished.countDown();
server.close();
}
}
}).start();
try {
serverStarted.await(1000L, TimeUnit.MILLISECONDS);
} catch (InterruptedException var7) {
var7.printStackTrace();
}
if(address2 instanceof Inet4Address) {
server.send(new DatagramPacket(probe.getBytes(), probe.length(), InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv4), WS_DISCOVERY_PORT));
} else {
server.send(new DatagramPacket(probe.getBytes(), probe.length(), InetAddress.getByName(WS_DISCOVERY_ADDRESS_IPv6), WS_DISCOVERY_PORT));
}
} catch (Exception var8) {
var8.printStackTrace();
}
try {
serverFinished.await((long)WS_DISCOVERY_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (InterruptedException var6) {
var6.printStackTrace();
}
}
};
executorService1.submit(runnable1);
}
try {
executorService1.shutdown();
executorService1.awaitTermination((long)(WS_DISCOVERY_TIMEOUT + 2000), TimeUnit.MILLISECONDS);
} catch (InterruptedException var9) {
;
}
return addresses;
}
}
DeviceDiscovery.class
private static Collection<Node> getNodeMatching(Node body, String regexp) {
ArrayList nodes = new ArrayList();
if(body.getNodeName().matches(regexp)) {
nodes.add(body);
}
if(body.getChildNodes().getLength() == 0) {
return nodes;
} else {
NodeList returnList = body.getChildNodes();
for(int k = 0; k < returnList.getLength(); ++k) {
Node node = returnList.item(k);
nodes.addAll(getNodeMatching(node, regexp));
}
return nodes;
}
}
private static Collection<String> parseSoapResponseForUrls(byte[] data) throws SOAPException, IOException {
ArrayList urls = new ArrayList();
MessageFactory factory = MessageFactory.newInstance(WS_DISCOVERY_SOAP_VERSION);
MimeHeaders headers = new MimeHeaders();
headers.addHeader("Content-type", WS_DISCOVERY_CONTENT_TYPE);
SOAPMessage message = factory.createMessage(headers, new ByteArrayInputStream(data));
SOAPBody body = message.getSOAPBody();
Iterator i$ = getNodeMatching(body, ".*:XAddrs").iterator();
while(i$.hasNext()) {
Node node = (Node)i$.next();
if(node.getTextContent().length() > 0) {
urls.addAll(Arrays.asList(node.getTextContent().split(" ")));
}
}
return urls;
}
I want to use both method of DeviceDiscovery.class. But it's not accessible because it's a private method.
I am not able to editing in DeviceDiscovery.class because it's a part of jar file and it's only readable form.
This is the error I have:
(216, 80) error: parseSoapResponseForUrls(byte[]) has private access in DeviceDiscovery
For some obscene reason this works when reward = "DIAMOND" and amount = 10
public ItemStack giveReward() {
return new ItemStack(Material.matchMaterial(reward), amount);
}
p.getInventory().addItem(o.giveReward()); //gives the player 10 DIAMONDS
but when reward = "ACACIA_DOOR" and amount = 1 the same method gives the player NOTHING and no error is thrown. I have no clue why. Also
System.out.println(Material.getMaterial("ACACIA_DOOR"))
prints ACACIA_DOOR so shouldn't my above code work?
here's the rest of the code:
//imports omitted
public class ObjectivesRPG extends JavaPlugin implements Listener {
//TODO
//add view command
//implement rewards and requirements
//test for completeness
//future - allow ops to modify player data
public static void main(String args[]) {
Objective o = new Objective("Spider", 1, 3, "DIAMOND", 1);
Material m = Material.getMaterial("ACACIA_DOOR");
System.out.println(m);
//meta.setDisplayName(ChatColor.GOLD + "Excaliber");
//meta.setLore(Arrays.asList(ChatColor.AQUA + "The legendary sword", ChatColor.GREEN + "Wow"));
//sword.setItemMeta(meta);
//System.out.println(o.getName());
/*
System.out.println(Material.DIAMOND_SWORD);
ItemStack stack = new ItemStack(Material.DIAMOND_SWORD, 1);
ItemMeta meta = stack.getItemMeta();
stack.setItemMeta(meta);*/
}
private ArrayList<Objective> objectives = null;
private HashMap<String, ArrayList<Objective>> loadedPlayerData = null;
#SuppressWarnings("unchecked")
#Override
public void onEnable() {
System.out.println("ObjectivesRPG loaded");
loadedPlayerData = new HashMap<>();
File dir = getDataFolder();
if (!dir.exists()) {
Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[ObjectivesRPG] Could not find data directory, creating it");
if (!dir.mkdir()) {
System.out.println("Error: Could not create data directory");
}
}
objectives = (ArrayList<Objective>) load(new File(getDataFolder(), "objectives.dat"));
if (objectives == null) {
objectives = new ArrayList<>();
}
getServer().getPluginManager().registerEvents(this, this); // ParamListener,
// ParamPlugin
}
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String args[]) {
if (label.equalsIgnoreCase("objectives")) {
if (sender instanceof Player) {
Player p = (Player) sender;
if(args.length == 0) {
for(Objective o: loadedPlayerData.get(p.getName())) {
p.sendMessage(o.getName() + " " + o.getTillComplete() + " ");
}
}
if (args.length > 0) {
if (args[0].equals("create")) {
if (!p.isOp()) {
p.sendMessage(ChatColor.RED + "You must be op to use this command");
} else if (args.length == 6) {
Objective objective = new Objective(args[1] ,Integer.parseInt(args[2]), Integer.parseInt(args[3]), args[4], Integer.parseInt(args[5]));
objectives.add(objective);
save(objectives, new File(getDataFolder(), "objectives.dat"));
} else {
p.sendMessage(ChatColor.RED + "Error: Bad arguments.");
}
}
}
}
}
return true;
}
public void onDisable() {
save(objectives, new File(getDataFolder(), "objectives.dat"));
}
public void save(Object o, File f) {
try {
if (!f.exists()) {
f.createNewFile();
}
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f));
os.writeObject(o);
Bukkit.getConsoleSender().sendMessage("[ObjectivesRPG] Saved objective");
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Object load(File f) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Object result = ois.readObject();
ois.close();
return result;
} catch (Exception e) {
return null;
}
}
#EventHandler
private void checkKills(EntityDeathEvent e) {
Entity killed = e.getEntity();
Entity killer = e.getEntity().getKiller();
if(killer instanceof Player) {
Player p = (Player) killer;
for(Objective o: loadedPlayerData.get(p.getName())) {
if(o.isComplete()) {
continue;
}
if(!o.isComplete() && (o.getRequirement() == Requirement.kill_Spiders && killed instanceof Spider ||
o.getRequirement() == Requirement.kill_Zombies && killed instanceof Zombie) ||
o.getRequirement() == Requirement.kill_Skeletons && killed instanceof Skeleton
) {
o.setTillComplete(o.getTillComplete() - 1);
if(o.getTillComplete() == 0) {
p.sendMessage(ChatColor.GREEN + "Congragulations! You completed objective " + o.getName() + "! Here is your reward!");
p.getInventory().addItem(o.giveReward());
o.setComplete(true);
}
}
}
}
}
#EventHandler
private void onQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
File f = new File(getDataFolder(), player.getName());
save(loadedPlayerData.get(player.getName()), f);
loadedPlayerData.remove(player.getName());
}
#EventHandler
private void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
File f = new File(getDataFolder(), player.getName());
ArrayList<Objective> playerObjectives = null;
try {
if(!f.exists()) {
f.createNewFile();
Bukkit.getConsoleSender().sendMessage("[ObjectivesRPG] Could not find " + player.getName() + "'s objective data, creating it");
playerObjectives = new ArrayList<>();
for(Objective objective: objectives) {
playerObjectives.add(objective);
}
player.sendMessage(ChatColor.GREEN + "You have new objective(s) to complete! Type /objectives to view them.");
save(playerObjectives, f);
} else {
playerObjectives = (ArrayList<Objective>) load(f);
System.out.println(objectives.size() + " " + playerObjectives.size());
//If server objective list is larger than playerObjectives new objectives must be added to player list
if(objectives.size() > playerObjectives.size()) {
player.sendMessage(ChatColor.GREEN + "You have new objective(s) to complete! Type /objectives to view them.");
for(int i = 0; i < objectives.size(); i++) {
boolean objectiveAdded = false;
for(int j = 0; j < playerObjectives.size(); j++) {
if(objectives.get(i).getName().equals(playerObjectives.get(j).getName())) {
objectiveAdded = true;
//break;
}
}
if(!objectiveAdded) {
playerObjectives.add(objectives.get(i));
}
}
save(playerObjectives, f);
}
}
loadedPlayerData.put(player.getName(), playerObjectives);
} catch(Exception e) {
e.printStackTrace();
}
}
}
public class Objective implements Serializable {
private static final long serialVersionUID = -2018456670240873538L;
private static ArrayList<Requirement> requirements = new ArrayList<>();
private String name;
private Requirement requirement;
private String reward;
private int amount;
private int tillComplete;
private boolean complete;
public Objective(String name, int requirementIndex, int tillComplete, String reward, int amount) {
if(requirements.isEmpty()) {
requirements.add(Requirement.kill_Skeletons);
requirements.add(Requirement.kill_Spiders);
requirements.add(Requirement.kill_Zombies);
}
this.name = name;
this.requirement = requirements.get(requirementIndex);
this.tillComplete = tillComplete;
this.reward = reward;
this.amount = amount;
complete = false;
}
public ItemStack giveReward() {
return new ItemStack(Material.matchMaterial(reward), amount);
}
public String getName() {
return name;
}
public Object getRequirement() {
return requirement;
}
public static ArrayList<Requirement> getRequirements() {
return requirements;
}
public static void setRequirements(ArrayList<Requirement> requirements) {
Objective.requirements = requirements;
}
public int getTillComplete() {
return tillComplete;
}
public void setTillComplete(int tillComplete) {
this.tillComplete = tillComplete;
}
public void setName(String name) {
this.name = name;
}
public void setRequirement(Requirement requirement) {
this.requirement = requirement;
}
public void setReward(String reward) {
this.reward = reward;
}
public void setComplete(boolean complete) {
this.complete = complete;
}
public String getReward() {
return reward;
}
public boolean isComplete() {
return complete;
}
}
This has tripped people up more than once. Doors are two-component items. ACACIA_DOOR represents the top-part of the door, while ACACIA_DOOR_ITEM represents the bottom-part and also the item id. Use ACACIA_DOOR_ITEM when creating an ItemStack.
Tip: If you are unsure about an item id, launch Minecraft in creative mode and enable Advanced Tooltips by pressing F3+H. The real item id will be displayed in the tool tip as you hover over items in the creative inventory. For example, hovering over an Acacia Door would display
Acacia Door (#0430)
Use this information to lookup the appropriate Material enum in org.bukkit.Material, which in this case would be ACACIA_DOOR_ITEM.
I have edited the question as your suggestions but null pointer exception is caught.I used connectionRequest instead of multipartRequest since i dont need to upload(just need to read the value frm json). All my codes below, please have a look.
Edited: exception
java.lang.NullPointerException
at userclasses.StateMachine$16.readResponse(StateMachine.java:1834)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:438)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:263)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
Code:
#Override
protected void beforeImgGallery(Form f) {
int iter = 0;
GridLayout gr = new GridLayout(1, 1);
Container grid = new Container(gr);
gr.setAutoFit(true);
grid.setScrollableY(true);
grid.addComponent(new InfiniteProgress());
f.addComponent(BorderLayout.CENTER, grid);
f.removeAllCommands();
f.setBackCommand(null);
createPictureCommand(grid);
}
private static boolean animating;
private Vector<Map<String, Object>> responsesgallery;
String galleryPhotoUrl;
private void createPictureCommand(final Container grid) {
ConnectionRequest mp = new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser p = new JSONParser();
results = p.parse(new InputStreamReader(input));
responsesgallery = (Vector<Map<String, Object>>) results.get("data");
//i've kept this for loop in postResponse but same error
for (int i = 0; i < responsesgallery.size(); i++) {
//null pointer exception in this line
final Button btn = createImageButton(i, grid, imageList.getSize());
//if i simply create a btn like below, it works
// final Button btn = new Button((URLImage.createToStorage(placeholder, token, galleryPhotoUrl, URLImage.RESIZE_SCALE_TO_FILL)));
imageList.addImageId(i);
grid.addComponent(i, btn);
Hashtable hm = (Hashtable) responsesgallery.get(i);
String galleryImgId = (String) hm.get("news_id");
galleryPhotoUrl = (String) hm.get("photo");
}
}
};
mp.setUrl("http://capitaleyedevelopment.com/~admin/traffic/api/news/getLatestNews");
NetworkManager.getInstance().addToQueueAndWait(mp);
}
ImageList imageList;
Button createImageButton(final int imageId, final Container grid, final int offset) {
final Button btn = new Button(URLImage.createToStorage(placeholder, token, galleryPhotoUrl, URLImage.RESIZE_SCALE_TO_FILL));
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
imageList.setSelectedIndex(offset);
final Container viewerParent = new Container(new LayeredLayout());
ImageViewer viewer = new ImageViewer(imageList.getItemAt(offset));
viewerParent.addComponent(viewer);
Container parent = new Container(new BorderLayout());
viewerParent.addComponent(parent);
viewer.setImageList(imageList);
grid.getParent().replace(grid, viewerParent, CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, false, 300));
Display.getInstance().getCurrent().setBackCommand(createBackCommand(viewerParent, grid));
}
});
return btn;
}
public static final String SERVER_URL = "http://capitaleyedevelopment.com/~admin/traffic/api/news/getLatestNews";
class ImageList implements ListModel<Image> {
private int selection;
private long[] imageIds;
private EncodedImage[] images;
private EventDispatcher listeners = new EventDispatcher();
public void addImageId(int id) {
long[] n = new long[imageIds.length + 1];
EncodedImage[] nImages = new EncodedImage[n.length];
System.arraycopy(imageIds, 0, n, 0, imageIds.length);
System.arraycopy(images, 0, nImages, 0, images.length);
n[imageIds.length] = id;
imageIds = n;
images = nImages;
listeners.fireDataChangeEvent(-1, DataChangedListener.ADDED);
}
public long getSelectedImageId() {
return imageIds[selection];
}
public ImageList(long[] images) {
this.imageIds = images;
this.images = new EncodedImage[images.length];
}
public Image getItemAt(final int index) {
if (images[index] == null) {
images[index] = placeholder;
Util.downloadUrlToStorageInBackground(IMAGE_URL_PREFIX + imageIds[index], "FullImage_" + imageIds[index], new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("FullImage_" + imageIds[index]));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch (IOException err) {
err.printStackTrace();
}
}
});
}
return images[index];
}
public int getSize() {
return imageIds.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
WebServiceProxy.getPhotoLikesAsync(imageIds[selection], new Callback<Integer>() {
public void onSucess(Integer value) {
}
public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
}
});
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeListener(l);
}
public void addSelectionListener(SelectionListener l) {
}
public void removeSelectionListener(SelectionListener l) {
}
public void addItem(Image item) {
}
public void removeItem(int index) {
}
}
In the Photo Share demo (that's on github) I demonstrate something pretty similar. I used a custom list model that fetches the images to the ImageViewer dynamically.
The interesting bit is this list model where the images are downloaded dynamically as needed:
class ImageList implements ListModel<Image> {
private int selection;
private long[] imageIds;
private EncodedImage[] images;
private EventDispatcher listeners = new EventDispatcher();
public void addImageId(long id) {
long[] n = new long[imageIds.length + 1];
EncodedImage[] nImages = new EncodedImage[n.length];
System.arraycopy(imageIds, 0, n, 0, imageIds.length);
System.arraycopy(images, 0, nImages, 0, images.length);
n[imageIds.length] = id;
imageIds = n;
images = nImages;
listeners.fireDataChangeEvent(-1, DataChangedListener.ADDED);
}
public long getSelectedImageId() {
return imageIds[selection];
}
public ImageList(long[] images) {
this.imageIds = images;
this.images = new EncodedImage[images.length];
}
public Image getItemAt(final int index) {
if(images[index] == null) {
images[index] = placeholder;
Util.downloadUrlToStorageInBackground(IMAGE_URL_PREFIX + imageIds[index], "FullImage_" + imageIds[index], new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("FullImage_" + imageIds[index]));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch(IOException err) {
err.printStackTrace();
}
}
});
}
return images[index];
}
public int getSize() {
return imageIds.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
WebServiceProxy.getPhotoLikesAsync(imageIds[selection], new Callback<Integer>() {
public void onSucess(Integer value) {
if(likeCount != null) {
likeCount.setText("" + value);
likeCount.getParent().revalidate();
}
}
public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
}
});
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeListener(l);
}
public void addSelectionListener(SelectionListener l) {
}
public void removeSelectionListener(SelectionListener l) {
}
public void addItem(Image item) {
}
public void removeItem(int index) {
}
}
Well I have this class for a game I'm making, and I'm trying to save the ArrayList notes. When I logout, it properly print the size, for example if I have 5 notes, when I log out notes.getSize() would be 5, but when I log in, it gets reset back to nothing. Why isn't notes saving?
public class Notes implements Serializable {
private static final long serialVersionUID = -4947870743226160329L;
private ArrayList<Note> notes = new ArrayList<Note>(30);
public class Note implements Serializable {
private static final long serialVersionUID = -4589885080580317958L;
private int color = 0;
private String text = "";
public Note(int color, String text) {
this.setColor(color);
this.setText(text);
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public void setColor(int color) {
this.color = color;
}
public int getColor() {
return color;
}
}
private transient Player player;
public Notes(Player p) {
this.player = p;
}
public void addNote(String text) {
System.out.println("Note Text: "+text);
if (text.length() > 50) {
player.getPackets().sendGameMessage("You can only enter notes up to 50 characters!");
return;
}
if (notes.size() < 30) {
notes.add(new Note(0, text));
} else {
player.getPackets().sendGameMessage("You cannot add more then 30 notes!");
return;
}
int NoteId = notes.size() - 1;
player.getPackets().sendConfig(1439, NoteId);
player.getTemporaryAttributtes().put("selectedNote", NoteId);
refreshNotes(false);
}
public void addNote(String text, int color) {
notes.add(new Note(color, text));
}
public void loadNotes() {
player.getPackets().sendIComponentSettings(34, 9, 0, 30, 2621470);
player.getPackets().sendHideIComponent(34, 3, false);
player.getPackets().sendHideIComponent(34, 44, false);
player.getPackets().sendIComponentText(34, 13, "Loading notes<br>Please wait...");
player.getPackets().sendConfig(1439, -1);
refreshNotes(true);
}
public void refreshNotes(boolean sendStartConfigs) {
for (int i = 0; i < 30; i++) {
player.getPackets().sendGlobalString(149 + i, i < notes.size() ? notes.get(i).getText() : "");
}
if (sendStartConfigs) {
for (int i = 1430; i < 1450; i++)
player.getPackets().sendConfig(i, i);
}
player.getPackets().sendConfig(1440, getFirstTotalColorValue());
player.getPackets().sendConfig(1441, getSecondTotalColorValue());
}
public int intColorValue(int color, int noteId) {
return (int) (Math.pow(4, noteId) * color);
}
public int getFirstTotalColorValue() {
int Color = 0;
for (int i = 0; i < 15; i++) {
if (notes.size() > i)
Color += intColorValue(notes.get(i).getColor(), i);
}
return Color;
}
public int getSecondTotalColorValue() {
int color = 0;
for (int i = 0; i < 15; i++) {
if (notes.size() > (i + 16))
color += intColorValue(notes.get(i + 16).getColor(), i);
}
return color;
}
public void deleteSelectedNote() {
if ((int)player.getTemporaryAttributtes().get("selectedNote") > -1) {
int slot = (int) player.getTemporaryAttributtes().get("selectedNote");
notes.remove(slot);
player.getTemporaryAttributtes().put("selectedNote", -1);
player.getPackets().sendConfig(1439, -1);
refreshNotes(false);
}
}
public void clear() {
notes.clear();
refreshNotes(false);
}
public void editNote(String string, int index) {
notes.get(index).setText(string);
refreshNotes(false);
}
public void setColor(int color, int index) {
notes.get(index).setColor(color);
refreshNotes(false);
}
public void deleteNote(int slot) {
notes.remove(slot);
refreshNotes(false);
}
public void setNotes(ArrayList<Note> setNotes) {
notes = setNotes;
refreshNotes(false);
}
}
And here is the class I manage saving/loading in
public class SerializableFilesManager {
private static final String PATH = "data/characters/";
private static final String BACKUP_PATH = "data/charactersBackup/";
public synchronized static final boolean containsPlayer(String username) {
return new File(PATH + username + ".p").exists();
}
public synchronized static Player loadPlayer(String username) {
try {
return (Player) loadSerializedFile(new File(PATH + username + ".p"));
} catch (Throwable e) {
Logger.handle(e);
}
try {
Logger.log("SerializableFilesManager", "Recovering account: "
+ username);
return (Player) loadSerializedFile(new File(BACKUP_PATH + username
+ ".p"));
} catch (Throwable e) {
Logger.handle(e);
}
return null;
}
public static boolean createBackup(String username) {
try {
Utils.copyFile(new File(PATH + username + ".p"), new File(
BACKUP_PATH + username + ".p"));
return true;
} catch (Throwable e) {
Logger.handle(e);
return false;
}
}
public synchronized static void savePlayer(Player player) {
try {
storeSerializableClass(player, new File(PATH + player.getUsername()
+ ".p"));
} catch (ConcurrentModificationException e) {
//happens because saving and logging out same time
} catch (Throwable e) {
Logger.handle(e);
}
}
public static final Object loadSerializedFile(File f) throws IOException,
ClassNotFoundException {
if (!f.exists())
return null;
ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
Object object = in.readObject();
in.close();
return object;
}
public static final void storeSerializableClass(Serializable o, File f)
throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
out.writeObject(o);
out.close();
}
private SerializableFilesManager() {
}
}
Do NOT mark Player as transient, cause you are saving it, transient will prevent if from
getting saved, and will bring player to the default value of null, when deserialized.
Have you made the player class serializable ?
Its the Entire object graph that gets serialized or none... the purpose of transient is to make a particular member to be left off during serialization so that, the process of serialization goes smoothly.
For example, Suppose in a game we want to keep the progress of the player and hours of play for that session, but not the starting and ending times. So the starting and ending time can be made transient.
you should save your ArrayList with:
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream("filename",false);
out = new ObjectOutputStream(fos);
out.writeObject(notes);
out.close();
System.out.println("Object Persisted");
} catch (IOException ex) {
ex.printStackTrace();
}
and when you open your project, import you Arraylist with:
FileInputStream fos;
try {
fos = new FileInputStream("filename");
ObjectInputStream oos = new ObjectInputStream(fos);
notes=(ArrayList) oos.readObject();
fos.close();
{
catch {
}
Thats because your Player is transient...I've tried to demonstrate your logic on other example...when Player was set to private, serialization has been successful and all data has been loaded back. Otherwise, when transient, Player reference was null, it loads only other serialized fields like int. When theres only a transient Player as field in class, the NullPointerException occurs, but ArrayList has size > 0.
I have code to stored the value using RMS in J2ME. It's working fine on emulator. So, my first problem is
When i restart the emulator all the stored values are deleted.
Stored values are showing in the emulator, but not in the Mobile, in which i am testing my application.
I am using NetBeans for developing my J2ME application.
===UPDATED===
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class TryNew extends MIDlet implements CommandListener, ItemCommandListener {
private RecordStore record;
private StringItem registered;
static final String REC_STORE = "SORT";
//Button existUser;
Display display = null;
private Ticker ticker;
Form form = null;
Form form1 = null;
TextField tb, tb1, tb2, tb3;
ChoiceGroup operator = null;
String str = null;
Command backCommand = new Command("Back", Command.BACK, 0);
Command loginCommand = new Command("Login", Command.OK, 2);
Command saveCommand = new Command("Save New", Command.OK, 1);
Command sendCommand = new Command("Send", Command.OK, 2);
Command selectCommand = new Command("Select", Command.OK, 0);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private ValidateLogin ValidateLogin;
public TryNew() {
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Login");
registered = new StringItem("", "Registered ?", StringItem.BUTTON);
form1 = new Form("Home");
tb = new TextField("Login Id: ", "", 10, TextField.PHONENUMBER);//TextField.PHONENUMBER
tb1 = new TextField("Password: ", "", 30, TextField.PASSWORD);
operator = new ChoiceGroup("Select Website", Choice.POPUP, new String[]{"Game", "Joke", "SMS"}, null);
form.append(tb);
form.append(tb1);
form.append(operator);
form.append(registered);
registered.setDefaultCommand(selectCommand);
registered.setItemCommandListener(this);
form.addCommand(saveCommand);
ticker = new Ticker("Welcome Screen");
form.addCommand(loginCommand);
form.addCommand(selectCommand);
form.addCommand(exitCommand);
// existUser = new StringItem(null, "Registered ?");
// form.append(existUser);
form.setCommandListener(this);
form1.addCommand(exitCommand);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
form.setTicker(ticker);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
void showMessage(String message, Displayable displayable) {
Alert alert = new Alert("");
alert.setTitle("Error");
alert.setString(message);
alert.setType(AlertType.ERROR);
alert.setTimeout(5000);
display.setCurrent(alert, displayable);
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == loginCommand) {
ValidateLogin = new ValidateLogin(this);
ValidateLogin.start();
ValidateLogin.validateLogin(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
} else if (c == saveCommand) {
openRecord();
writeRecord(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
closeRecord();
showAlert("Login Credential Saved Successfully !!");
}
}
////==============================================================================/////
/// Record Management
public void openRecord() {
try {
record = RecordStore.openRecordStore(REC_STORE, true);
} catch (Exception e) {
db(e.toString());
}
}
public void closeRecord() {
try {
record.closeRecordStore();
} catch (Exception e) {
db(e.toString());
}
}
public void deleteRecord() {
if (RecordStore.listRecordStores() != null) {
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString());
}
}
}
public void writeRecord(String login_id, String pwd, String operator_name) {
String credential = login_id + "," + pwd + "," + operator_name;
byte[] rec = credential.getBytes();
try {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
record.addRecord(rec, 0, rec.length);
}
} catch (Exception e) {
db(e.toString());
}
}
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
public void readRecord() {
try {
if (record.getNumRecords() > 0) {
Comparator comp = new Comparator();
RecordEnumeration re = record.enumerateRecords(null, comp, false);
while (re.hasNextElement()) {
String str = new String(re.nextRecord());
showAlert(str);
}
}
} catch (Exception e) {
db(e.toString());
}
}
private void db(String error) {
System.err.println("Exception: " + error);
}
public void commandAction(Command c, Item item) {
if (c == selectCommand && item == registered) {
openRecord();
readRecord();
closeRecord();
}
}
class Comparator implements RecordComparator {
public int compare(byte[] rec1, byte[] rec2) {
String str1 = new String(rec1);
String str2 = new String(rec2);
int result = str1.compareTo(str2);
if (result == 0) {
return RecordComparator.EQUIVALENT;
} else if (result < 0) {
return RecordComparator.PRECEDES;
} else {
return RecordComparator.FOLLOWS;
}
}
}
class ValidateLogin implements Runnable {
TryNew midlet;
private Display display;
String login_id;
String pwd;
String operator_name;
public ValidateLogin(TryNew midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
showHome();
}
}
/* This method takes input from user like text and pass
to servlet */
public void validateLogin(String login_id, String pwd, String operator_name) {
this.login_id = login_id;
this.pwd = pwd;
this.operator_name = operator_name;
}
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
private void showHome() {
tb2 = new TextField("To: ", "", 30, TextField.PHONENUMBER);
tb3 = new TextField("Message: ", "", 300, TextField.ANY);
form1.append(tb2);
form1.append(tb3);
form1.addCommand(loginCommand);
//display.setCurrent(tb3);
display.setCurrent(form1);
}
};
}
This is what i got, when i click the Manage Emulator
You need to fix the storage_root of your app in WTK,
Whenever you start your enulator it would refer to same storage_root, by default it creates different data files for each session