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
Related
I'm trying to finish my project about searching graphs, where one of the functions is input (vertex and edges) from user.
I already have a method for this in another class, but now I need to put it into GUI.
I've already tried many of tutorials, but nothing worked. Can somebody help me, how to put the method getInputFromCommand to gui?
I've already tried to copy the method into the GUI, but there was problem with the "return g" because of the void result type, I've tried just to call the method, (I know.. stupid) but it didn't work either.
package Process;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
public static FindIslands getInputFromCommand() {
FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return g;
}
}
Where important is the last method "getInputFromCommand()"
and... gui
package Process;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.util.Scanner;
public class Guicko extends JFrame {
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
public Guicko() {
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FindIslands.getInputFromCommand();
}
});
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String str = "asd";
FindIslands g = null;
g.connectedComponents();
textArea1.setText(str);
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
}
I'm sure there are many correct ways this code can be fixed, but in IMHO, your Guicko class needs to have a FindIslands class member, and I think you need to move some stuff from FindIslands.main() into Guicko.main() or some other method.
Then your "Action Listener" inner classes' actionPerformed methods just delegate to the methods in the FindIslands member instance, like this
....
private FindIslands fi;
public Guicko() {
....
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fi = FindIslands.getInputFromCommand();
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String comps = fi.connectedComponents();// method needs to return a string
textArea1.setText(comps);
}
});
}
The whole idea of seperating GUI from domain is to make changes easily. GUI has knowledge of the domain but domain has no knowledge about the GUI. We can use an interface to seperate them, in that case, Domain says , i don't care who implements this interface but whoever implements this interface will get response and can work with me.
So , If we create a new GUI, we can let it implements that interface and the same domain will work with that GUI.
There are many mistakes but in order to make it work and to show you an example i did few changes.
public class Guicko extends JFrame implements PropertyChangeListener{
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
private FindIslands land;
private JTextField textField;
private JButton button;
public Guicko() {
JPanel panel = new JPanel();
super.getContentPane().setLayout(new GridLayout());
//For each gui, there should be one land.
this.setLand(new FindIslands(100));
//Subscribe to the domain so that you can get update if something change in domain.
this.getLand().subscribe(this);
//Dummy buttons are fields(need too initiate first)
textField2 = new JTextField("",30);
štartButton = new JButton();
textField = new JTextField("",30);
button = new JButton();
button.setPreferredSize(new Dimension(100, 40));
button.setText("Get input from Domain");
štartButton.setPreferredSize(new Dimension(100, 40));
textField.setEditable(false);
štartButton.setText("Start");
panel.add(textField2);
panel.add(štartButton);
panel.add(textField);
panel.add(button);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
//When you type something in , then this function will send it to domain(i mean to function : getInputFromCommand();).
this.addListerToField(štartButton,this.getLand(),textField2);
//Now the second case, suppose you press a button and want something to show up in textfield. In that case , this function will do work.
this.addListerToSecondField(button,this.getLand(),textField);
}
//Here i can catch the events from the domain.
#Override
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals("String changed")) {
this.getTextField().setText((String) e.getNewValue());
}
}
private void addListerToSecondField(JButton button, FindIslands land, JTextField field) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.requireArgumentsForField();
}
});
}
private void addListerToField(JButton štartButton, FindIslands land, JTextField field) {
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.getInputFromCommand(field.getText());
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
public FindIslands getLand() {
return land;
}
public void setLand(FindIslands land) {
this.land = land;
}
public JTextField getTextField() {
return textField;
}
public void setTextField(JTextField textField) {
this.textField = textField;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
Here is the second class. Run it and try to get feeling for it how it works.
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
//initialize the list
this.setListeners(new ArrayList<>());
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
//You need only one main class, not two.----------------------------
/**
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
**/
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
//Static cases are to be avoided.This is the property of object not class.
public void getInputFromCommand(String string) {
//Here you will recieve a string from the GUI and will be printed in command prompt.You can do whatever you want to do with it.
System.out.println("Recieve string is " + string);
//No idea what you are trying to do.
/** FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return line;**/
}
//This function is triggered with second button and you can send data to gui as shown below.
public void requireArgumentsForField() {
//Suppose i want to send following string.
String name = "I don't know";
this.getListeners().stream().forEach(e -> {
// I will catch this in view.
e.propertyChange(new PropertyChangeEvent(this, "String changed", null, name));
});
}
private ArrayList<PropertyChangeListener> listeners;
//Let the objects subscibe. You need this to publish the changes in domain.
public void subscribe(PropertyChangeListener listener) {
this.getListeners().add(listener);
}
public ArrayList<PropertyChangeListener> getListeners() {
return listeners;
}
public void setListeners(ArrayList<PropertyChangeListener> listeners) {
this.listeners = listeners;
}
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 am trying to fetch facebook feed using graph api in Codename one but it only works with my own account, Whenever other user will try to fetch their feed using my app it throw an error.
Following is my code
public class Test {
private Form current;
private Resources theme;
Form facebook;
Toolbar tb;
Image user;
Label userLabel;
Label username;
Login loginfb;
String clientId = "158093724691158";
String redirectURI = "http://www.codenameone.com/";
String clientSecret = "4f5b275ae702f7b6fde9bc50bfe3b5e3";
Label proLabel;
Label fname;
Label fmail;
Label fgender;
Container container12;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature, uncomment if you have a pro subscription
// Log.bindCrashProtection(true);
}
public void start() {
if(current != null){
current.show();
return;
}
try{
Splash spl = new Splash();
spl.show();
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
facebook.show();
}
} , 4000);
}catch(IOException e){
e.printStackTrace();
}
facebook = new Form("Facebook", new BoxLayout(BoxLayout.Y_AXIS));
tb = new Toolbar();
facebook.setToolbar(tb);
user = theme.getImage("user.png");
userLabel = new Label(user);
username = new Label("Visitor");
Button facebooklogin = new Button("Login with Facebook");
Button linked = new Button("Login with LinkedIn");
//linked.setUIID("linkedButton");
linked.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Oauth2 auth2 = new Oauth2("https://www.linkedin.com/oauth/v2/authorization?response_type=code",
"81lq3qpacjvkcu",
"https://www.codenameone.com","r_fullprofile%20r_emailaddress","https://www.linkedin.com/uas/oauth2/accessToken","vzwWfamZ3IUQsJQL");
Oauth2.setBackToParent(true);
auth2.showAuthentication(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof String) {
String token = (String) evt.getSource();
String expires = Oauth2.getExpires();
System.out.println("Token=" +token + "Expires in " +expires );
} else {
Exception err = (Exception) evt.getSource();
err.printStackTrace();
Dialog.show("Error", "An error occurred while logging in: " + err, "OK", null);
}
}
});
}
});
facebooklogin.addActionListener((evt) -> {
Login fb = FacebookConnect.getInstance();
fb.setClientId(clientId);
fb.setRedirectURI(redirectURI);
fb.setClientSecret(clientSecret);
fb.setScope("user_birthday,user_religion_politics,user_relationships,user_relationship_details,user_hometown,user_location,user_likes,user_education_history,user_work_history,user_website,user_events,user_photos,user_videos,user_friends,user_about_me,user_status,user_games_activity,user_tagged_places,user_posts,rsvp_event,email,read_insights,publish_actions,read_audience_network_insights,read_custom_friendlists,user_action.books,user_action.music,user_action.video,user_action.news,user_action.fitness,user_managed_groups,manage_pages,pages_manage_cta,pages_manage_instant_articles,pages_show_list,publish_pages,read_page_mailboxes,ads_management,ads_read,business_management,pages_messaging,pages_messaging_phone_number,pages_messaging_subscriptions,pages_messaging_payments,public_profile");
loginfb = fb;
fb.setCallback(new LoginListener(LoginListener.FACEBOOK));
if(!fb.isUserLoggedIn()){
fb.doLogin();
}else{
showFacebookUser(fb.getAccessToken().getToken());
}
});
Container container1 = BoxLayout.encloseY(userLabel,username);
container1.setUIID("container1");
tb.addComponentToSideMenu(container1);
tb.addCommandToSideMenu("Home", FontImage.createMaterial(FontImage.MATERIAL_HOME, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Shop by Category", FontImage.createMaterial(FontImage.MATERIAL_ADD_SHOPPING_CART, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Todays Deals", FontImage.createMaterial(FontImage.MATERIAL_LOCAL_OFFER, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Your Orders", FontImage.createMaterial(FontImage.MATERIAL_BOOKMARK_BORDER, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Your Wish List", FontImage.createMaterial(FontImage.MATERIAL_LIST, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Your Account", FontImage.createMaterial(FontImage.MATERIAL_ACCOUNT_BOX, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Gift Cards", FontImage.createMaterial(FontImage.MATERIAL_CARD_GIFTCARD, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Setting", FontImage.createMaterial(FontImage.MATERIAL_SETTINGS, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Logout", FontImage.createMaterial(FontImage.MATERIAL_BACKSPACE, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
Tabs tab = new Tabs();
Style s = UIManager.getInstance().getComponentStyle("Tab");
FontImage icon1 = FontImage.createMaterial(FontImage.MATERIAL_VPN_KEY, s);
FontImage icon2 = FontImage.createMaterial(FontImage.MATERIAL_LIST, s);
FontImage icon3 = FontImage.createMaterial(FontImage.MATERIAL_ACCOUNT_BOX, s);
Container container11 = BoxLayout.encloseY(facebooklogin,linked);
container12 = BoxLayout.encloseY(new SpanLabel("Some text directly in the tab2"));
Image pro = theme.getImage("user.png");
proLabel = new Label(pro);
Label uname = new Label("Name: ");
fname = new Label("");
Label umail = new Label("Name: ");
fmail = new Label("");
Label ugender = new Label("Name: ");
fgender = new Label("");
Container profileContainer = TableLayout.encloseIn(2, uname,fname,umail,fmail,ugender,fgender);
Container container13 = BoxLayout.encloseY(proLabel,profileContainer);
tab.addTab("Log In",icon1,container11 );
tab.addTab("Wall",icon2, container12 );
tab.addTab("User Profile",icon3, container13);
facebook.add(tab);
}
public void showFacebookUser(String token){
ConnectionRequest conn = new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parser = new JSONParser();
Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
String email = null;
if(email == null){
email=" ";
}
email = (String) parsed.get("email");
String name = (String) parsed.get("name");
String first_name = (String) parsed.get("first_name");
String last_name = (String) parsed.get("last_name");
String gender = (String) parsed.get("gender");
String image = (String) ((Map) ((Map) parsed.get("picture")).get("data")).get("url").toString();
ArrayList<String> data_arr1= (ArrayList) ((Map) parsed.get("feed")).get("data");
JSONArray array = new JSONArray(data_arr1);
Log.p("First NAme : " + first_name);
Log.p("Last Name : " + last_name);
Log.p("Email : " + email);
Log.p("Full Name : " + name);
Log.p("Gender : " + gender);
Log.p("Picture : " +image);
username.setText(name);
userLabel.setIcon(URLImage.createToStorage((EncodedImage) user, "Small_"+image, image, URLImage.RESIZE_SCALE));
proLabel.setIcon(URLImage.createToStorage((EncodedImage) user, image, image, URLImage.RESIZE_SCALE));
fname.setText(name);
fmail.setText(email);
fgender.setText(gender);
ArrayList<String> arrayList = new ArrayList<>();
try{
JSONArray array2 = new JSONArray(array.toString());
for(int i =0; i<array2.length() ; i++){
JSONObject jsonobject = array2.getJSONObject(i);
String story = null;
if(story == null){
story=" ";
}
try {
story = jsonobject.getString("story");
} catch (Exception e) {
e.printStackTrace();
}
String msg = null;
if(msg == null){
msg=" ";
}
try {
msg = jsonobject.getString("message");
} catch (Exception e) {
e.printStackTrace();
}
String full_picture = null;
if(full_picture == null){
full_picture=" ";
}
try{
full_picture = jsonobject.getString("full_picture");
}
catch(Exception e){
e.printStackTrace();
}
Log.p(story);
Log.p(msg);
Log.p(full_picture);
Image wallimage = theme.getImage("blank.jpg");
Label wallimageLabel = new Label(wallimage);
wallimageLabel.setIcon(URLImage.createToStorage((EncodedImage) wallimage, full_picture, full_picture, URLImage.RESIZE_SCALE));
Label wallstory = new Label(story);
Label wallmessage = new Label(msg);
Container wallcontainer = BoxLayout.encloseY(wallmessage,wallstory,wallimageLabel);
container12.add(wallcontainer);
}
}catch(Exception e){
e.printStackTrace();
}
}
};
conn.setPost(false);
conn.setUrl("https://graph.facebook.com/v2.8/me");
conn.addArgumentNoEncoding("access_token", token); //this statement is used to patch access token with url
conn.addArgumentNoEncoding("fields", "email,name,first_name,last_name,gender,picture.width(512).height(512),feed{name,full_picture,message,story},posts");
//above statement is used to provide permission through url so server send data with respect ot permissions.
NetworkManager.getInstance().addToQueue(conn);
}
public void stop() {
current = Display.getInstance().getCurrent();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = Display.getInstance().getCurrent();
}
}
public void destroy() {
}
public class LoginListener extends LoginCallback {
public static final int FACEBOOK = 0;
private int loginType;
public LoginListener(int loginType) {
this.loginType = loginType;
}
public void loginSuccessful() {
try {
AccessToken token = loginfb.getAccessToken();
if (loginType == FACEBOOK) {
showFacebookUser(token.getToken());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void loginFailed(String errorMessage) {
Dialog.show("Login Failed", errorMessage, "Ok", null);
}
}
}
And throws following error:
java.lang.NullPointerException
at com.grv.test.Test$3.readResponse(Test.java:220)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:733)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.lang.NullPointerException
at com.grv.test.Test$3.readResponse(Test.java:220)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:733)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
I just want to know that why this application not able to fetch facebook feed from other user account.
I'm creating a Netbeans module. How do I pass a selected text in the java editor as a parameter to my ActionListener class and, after process it, how do I replace this old text (passed as parameter) by the new processed text in the java editor?
#ActionID(category = "Edit", id = "com.beg.regextester.RegexTesterListener")
#ActionRegistration(displayName = "Regex Tester")
#ActionReference(path = "Editors/text/x-java/Popup")
public class RegexTesterListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//the code here
}
After a long research, I got it.
#ActionID(category = "Edit", id = "com.beg.regextester.RegexTesterListener")
#ActionRegistration(displayName = "Regex Tester")
#ActionReference(path = "Editors/text/x-java/Popup")
public class RegexTesterListener implements ActionListener {
private final DataObject context;
public RegexTesterListener(DataObject context) {
this.context = context;
}
#Override
public void actionPerformed(ActionEvent e) {
//Identify java object in the context
FileObject fileObject = context.getPrimaryFile();
JavaSource javaSrc = JavaSource.forFileObject(fileObject);
if (javaSrc == null) {
StatusDisplayer.getDefault().setStatusText(fileObject.getPath() + " is not a java file");
} else {
try {
javaSrc.runUserActionTask(new org.netbeans.api.java.source.Task<CompilationController>() {
#Override
public void run(CompilationController p) throws Exception {
p.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
Document doc = p.getDocument();
if (doc == null) {
StatusDisplayer.getDefault().setStatusText("Java file is closed");
} else {
new MemberVisitor(p).scan(p.getCompilationUnit(), null);
}
}
}, true);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}//end else
}//end actionPerformed
private static class MemberVisitor extends TreePathScanner<Void, Void> {
private CompilationInfo info;
public MemberVisitor(CompilationInfo info) {
this.info = info;
}
#Override
public Void visitClass(ClassTree t, Void v) {
try {
JTextComponent editor = EditorRegistry.lastFocusedComponent();
if (editor.getDocument() == info.getDocument()) {
int dot = editor.getCaret().getDot();
TreePath tp = info.getTreeUtilities().pathFor(dot);
Element el = info.getTrees().getElement(tp);
if (el != null) {
StatusDisplayer.getDefault().setStatusText("Please, select a string");
} else {
//get the selected text
String str = editor.getSelectedText();
//process the string and pass it to the clipboard
...
//replacing the old str by the new one
editor.paste();
}
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return null;
}
}
}//end class
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;
}
}