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.
Related
how do I clear my memory after the fifth action?
to be able to create a new basket again and fill it with new balls.
Because now, when you re-create the basket and fill it with balls,
the error appears on the second action (filling the basket)
how to clear the cache with the first bucket so that you can enter the second one?
//main
public class Dialogue {
private static Scanner scanner = new Scanner(System.in);
private static boolean buildBasket = false;
private static boolean completedBasket = false;
private Basket basket;
private static int volumeOfBasket = 0;
public static void main(String[] args) {
boolean buildBasket = false;
boolean completedBasket = false;
Basket basket =null;
int volumeOfBasket = 0;
try {
while (true) {
System.out.println("1 - build а basket");
System.out.println("2 - add balls to basket");
System.out.println("3 - output information about basket");
System.out.println("4 - weight of balls in the basket");
System.out.println("5 - quantity red balls");
int i = ScunnerInformation.checkInformatio();
if (i == 1) {
System.out.println("what max count of ball will into basket?");
volumeOfBasket = ScunnerInformation.getVolumeBasket();
Basket newBasket = new Basket("<Basketballs>", volumeOfBasket);
System.out.println("Basket was build with name: " + newBasket.getNameBasket() +
" and with the size " + newBasket.getVolume());
buildBasket = true;
basket = newBasket;
} else if (i == 2) {
if (buildBasket) {
basket = WorkWithBasket.fillBasket(basket);
completedBasket = true;
System.out.println("you have successfully added balls to the basket");
}else {
System.out.println("error");
}
} else if (i == 3) {
if (completedBasket) {
WorkWithBasket.InfoOut(basket);
} else {
System.out.println("error");
}
}else if (i == 4) {
if (completedBasket) {
System.out.println("weight basket: " + WorkWithBasket.countWeight(basket));
} else {
System.out.println("error");
}
}else if (i==5) {
if (completedBasket) {
System.out.println(WorkWithBasket.countRedBalls(basket) + " it it number of red balls");
} else {
System.out.println("error");
}
} else if (i == 6) {
break;
}
}
}finally {
if (scanner!=null){
scanner.close();
}
}
}
//fillBasket
public class WorkWithBasket {
public static Basket fillBasket(Basket basket){
for(int i =0; i < basket.getVolume(); i++){
Ball temp = new Ball(Color.getRandomColor(), WorkWithBall.CostBall(),WorkWithBall.WeightBall());
basket.addBall(temp);
}
return basket;
}
//addBall
public void addBall(Ball ball){
if (ball !=null){
basket[ball.getId() -1] = ball;
}
}
//basket initialization
public class Basket {
private Ball[] basket;
public Basket(){
this.basket = new Ball[this.volume];
}
public Basket (String nameBasket, int volume){
this.basket = new Ball[volume];
}
public Ball[] getBasket(){
return basket.clone();
}
public void addBall(Ball ball){
if (ball !=null){
basket[ball.getId() -1] = ball;
}
}
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;
}
}
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
Follow-up on a previous question I posted about a combat simulator.
The problem here: 'Creature' objects do not enter the stack on the 'Combat' class.
The whole thing is several classes larger but I've managed to narrow the problem to the following code.
public class Combat implements Runnable {
int Turn = 0;
HashMap<Integer, Faction> Factions = new HashMap<Integer, Faction>();
Stack<Creature> stack;
public int getFactionsStanding() {
int Result = 0;
Iterator<Faction> F = Factions.values().iterator();
while(F.hasNext()) {
if (F.next().getMemberCount() > 0)
Result = Result + 1;
}
return Result;
}
public HashMap<Integer, Creature> getEnemies(int factionID) throws NoFactionsException {
HashMap<Integer, Creature> targetPool = new HashMap<Integer, Creature>();
Iterator<Faction> F = Factions.values().iterator();
if (!(F.hasNext()))
throw new NoFactionsException();
Faction tempFaction;
while (F.hasNext()){
tempFaction = F.next();
if (tempFaction.getfactionID() != factionID)
targetPool.putAll(tempFaction.getMembers());
}
return targetPool;
}
private int getMaxInit(){
int Max = 0, temp = 0;
Iterator<Faction> I = Factions.values().iterator();
while(I.hasNext()){
temp = I.next().getMaxInit();
if (temp > Max)
Max = temp;
}
return Max;
}
public int getTurn() {
return Turn;
}
public void setTurn(int turn) {
Turn = turn;
}
// TODO I can't get creatures to enter the stack! :#
synchronized public void push(Creature C){
stack.push(C);
System.out.println("Creature " + C.getName() + " is now on the stack");
if (C.getInit() == this.getMaxInit())
this.emptyStack();
notify();
}
// TODO The stack must be processed now: everyone does what they intended to do
public void emptyStack(){
Creature C;
while (!(stack.isEmpty())){
C = stack.pop();
C.takeAction();
}
Turn = 0;
}
synchronized public void increaseTurn(){
this.Turn = Turn + 1;
System.out.println("Current initiative score is " + this.getTurn());
notifyAll();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return;
}
}
public void run(){
while(this.getFactionsStanding() > 1){
increaseTurn();
}
}
}
public class Creature extends Observable implements Runnable {
synchronized public void declareAction(){
try{
if (Combat.getTurn() != this.getInit())
wait();
Combat.push(this);
}
catch (InterruptedException e){
return;
}
}
public void takeAction(){
Attack(this.Target, this.leftHandWeapon);
if (this.Target.getCurrentHP() < 0)
this.Target = null;
}
public void setTarget() {
Integer targetID = -1;
HashMap<Integer, Creature> targetPool;
Object[] targetKeys;
try{
targetPool = Combat.getEnemies(FID);
if (targetPool.isEmpty())
throw new EmptyTargetPoolException();
targetKeys = targetPool.keySet().toArray();
if (targetKeys.length == 0)
throw new EmptyTargetKeysArrayException();
if (this.Target == null) {
do{
targetID = (Integer) this.getRandom(targetKeys); //(Integer)targetKeys[(Integer) this.getRandom(targetKeys)];
} while (!(targetPool.keySet().contains((Integer)targetID)));
this.Target = targetPool.get(targetID);
}
}
catch (EmptyTargetPoolException e) {
System.out.println(e.getMessage());
}
catch (EmptyTargetKeysArrayException e) {
System.out.println(e.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void run() {
// This will go on and on as long as this creature is alive
while (this.currentHP > 0) {
try {
this.setInit();
this.setTarget();
this.declareAction();
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
System.out.println(this.Name + " was killed!");
}
}
Does the creatures name get printed out? If so there may be a problem with:
if (C.getInit() == this.getMaxInit())
this.emptyStack();
I'm not sure what the method getInit() does but if getMaxInit() also returns the same value then it could just empty the stack each time push() is called. Its the only problem I can see right now that could happen.