Why is HashMap resetting after it exits method? - java

I am having some trouble with the HashMaps in my program. I have several declared at the top class like so:
public HashMap<String, Object> hmClass = new HashMap<String ,Object>();
public HashMap<String, Object> hmIns = new HashMap<String, Object>();
public HashMap<String, Object> hmCon = new HashMap<String, Object>();
public HashMap<String, Object> hmParam = new HashMap<String, Object>();
public HashMap<String, Object> hmResult = new HashMap<String, Object>();
In a separate method, I am putting values into them like this:
public String newInstanceCreate(Class c3, String classInstance)//void ??
{
Class c = c3;
String cI = classInstance;
Object instance = null;
Object con = null;
String instanceName = null;
try{
instanceName = JOptionPane.showInputDialog(null, "Under what name would you like to store this Instance?",
"Create an Instance of a Class", JOptionPane.QUESTION_MESSAGE);
}catch(NullPointerException e)
{
newInstanceCreate(c,cI);
}
hmClass.put(instanceName, c); //add the name of the instance as key and class as value to the hashmap
System.out.println(hmClass);
con = JOptionPane.showInputDialog(null,"Choose Constructor for " + c, "Create an Instance of a Class", 3, null, getConstructors(c), JOptionPane.QUESTION_MESSAGE);
System.out.println("worked + " + con);
hmCon.put(instanceName, con); //add the name of the instance as key and constructor as value to the hashmap
System.out.println(hmCon);
try {
instance = c3.getDeclaredConstructor().newInstance(); //create the instance --KEY
hmIns.put(instanceName, instance);
System.out.println("23" + instance);
hmParam.put(instanceName, getParams(c3, con)); //ask the user for the parameters (doubles) that they want in the instance constructor
// add the name of the instance as key and parameters(array) as value
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e){
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.print("hmClass: \n" + hmClass + "hmIns: \n" + hmIns + "hmCon: \n" + hmCon + "hmParam: \n" + hmParam);
return classInstance;
}
But when I try access them from a another method, it seems that they have all been reset.
public void option4()
{
System.out.println("hmIns: " + hmIns);
String stringInstance = JOptionPane.showInputDialog(null, "Which Instance would you like to stringify? " ,
"Stringify an Instance of a Class", JOptionPane.QUESTION_MESSAGE);
//get all the required info for making the instance
/*
* needed: name of stored instance
* name of correct and stored constructor
* name of parameters that were created by user (doubles?)
*/
System.out.println(stringInstance);
if(hmIns.isEmpty())
System.out.println("EMPTY");
Object ins = hmIns.get(stringInstance);
System.out.println("ins before: " + ins);
Object cons = hmCon.get(stringInstance);
System.out.println("cons before: " + cons);
Object par = hmParam.get(stringInstance);
System.out.println("par before: " + par);
//construct an instance and run toString() here
try {
ins = ((Constructor)cons).newInstance(par);
System.out.println(" ins: " + ins);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//result from toString
/*
* stored: name of result
* result itself (stored as string for now)
*/
JOptionPane.showMessageDialog(null, "result here??--how to get result to double??", "Stringified Instance of: ", 0);
mainWindow();
}
In the last method listed, I tested to see if the HashMap had null values instead of actually being empty, but it returns as having no values at all. Why is the HashMap resetting after I exit the first method?
Thank you so much for any insight.
Fran

It doesn't reset. I suggest you look at your code in a debugger and check if they are looking at the same object/map. I suspect you have two objects which contain maps.

Related

ResultSet only returns one row when more exist in the database

I created a java class called Executar_Query_Bd_Multiplos_Resultados in this class as the parameter for the Conectar method 2 values (int Integer1, int Integer2) of integer type.
These values are received by the query:
"SELECT DS_ESTRATEGY, STRID_ID" +
"FROM TB_BKOFFICE_ESTRATEGY" +
"WHERE IN_STRATEGY_ID IN (" + Istrategy1 + "," + Istrategy2 + ")";
The result of the above query is stored in the variable ls_command.
In the Executar_Query_Bd_Multiplos_Resultados_Test class I make the method call (Connect) and step 2 parameters (179, 319) and command to print on the screen the variable of type String codEstrategies.
But Eclipse only displays 1 result on the console. The query should bring 2 results and not 1. Here is the code for the Java classes and the result of the query executed in Oracle SQL Developer.
public class Executar_Query_Bd_Multiplos_Resultados_Test {
#Before
public void setUp() throws Exception {
Executar_Query_Bd_Multiplos_Resultados qr_2 = new Executar_Query_Bd_Multiplos_Resultados();
String codEstrategias = qr_2.Conectar(179, 319);
System.out.println("Estratégias: " + codEstrategias);
}
#After
public void tearDown() throws Exception {
}
#Test
public void test() {
}
}
public class Executar_Query_Bd_Multiplos_Resultados {
//Variáveis de BD
Connection conOracle = null;
Statement stmtOracle = null;
ResultSet rsetOracle = null;
public String Conectar(int Id_Estrategia1, int Id_Estrategia2) {
String retorno = "#;-1;#";
Boolean lb_continuar = true;
//StringBuilder ls_comando = new StringBuilder();
String ls_comando = new String();
try {
System.out.println("Conectando ao banco de dados Oracle...");
String url = "";
try {
//conectando aos bancos de dados
Class.forName("oracle.jdbc.driver.OracleDriver");
url = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
DriverManager.setLoginTimeout(10);
conOracle = (Connection) DriverManager.getConnection(url, "bkofficeadm", "bkofficeadmdesenv01");
} catch (SQLException e) {
System.out.println("falha SQL >> " + e.getMessage());
} catch (Exception e) {
//System.out.println("falha geral >> " + e.getMessage());
e.printStackTrace();
lb_continuar = false;
}
//String teste = "'BKO - Rep Conectividade'";
if (lb_continuar) {
System.err.println("Preparando comando...");
System.out.println("");
ls_comando = "SELECT DS_ESTRATEGIA, ID_ESTRATEGIA"+
" FROM TB_BKOFFICE_ESTRATEGIA"+
" WHERE ID_ESTRATEGIA IN (" + Id_Estrategia1 + ", " + Id_Estrategia2 + ")";
System.out.println(ls_comando);
stmtOracle = conOracle.createStatement();
stmtOracle.setQueryTimeout(10);
rsetOracle = stmtOracle.executeQuery(ls_comando.replaceAll("\n", " ").trim());
if(rsetOracle.next()) {
retorno = rsetOracle.getString(1);
}
rsetOracle.close();
stmtOracle.close();
/*
Para comandos de Insert, Delete, ou Update
--------------------------------------------------------
stmtOracle = conOracle.createStatement();
stmtOracle.setQueryTimeout(10);
stmtOracle.execute(variavel_comando.toString());
conOracle.commit();
stmtOracle.close();
*/
}
} catch (Exception ex) {
System.out.println("Erro - " + ex.getMessage());
} finally {
try {
if (rsetOracle != null) {
rsetOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar rset - " + e.getMessage());
}
try {
if (stmtOracle != null) {
stmtOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar stmt - " + e.getMessage());
}
try {
if (conOracle != null && !conOracle.isClosed()) {
conOracle.close();
}
if (conOracle != null && !conOracle.isClosed()) {
conOracle.close();
}
} catch (Exception e) {
System.out.println("Erro ao fechar con - " + e.getMessage());
}
}
return retorno;
}
}
Output from SQL Devleoper query:
Output from Eclipse console:
You're doing this
if(rsetOracle.next()) {
retorno = rsetOracle.getString(1);
}
This runs once
Consider while instead:
List<String> retornos = new ArrayList<>();
while(rsetOracle.next()) {
retornos.add(rsetOracle.getString(1));
}
This will run until you're out of rows.
If something like this happens in the future, you'll want to modify your query to select count(*) ... and verify you get the same result in both the database workbench and your javacode. Then you'll at least know you've got the right query, and it's your presentation that's failing.
Note:
I understand this question is indeed a duplicate of other questions. However, those are difficult to search. I would propose this be a canonical answer.

JAVA / SqLite memory behaves not as expected, rows are lost

I have the following code using sqlite3 and java which runs without errors:
public class SqLiteDB {
public static void main(final String[] args) {
final SqLiteDB theDatabase = SqLiteDB.initSqLiteDB();
theDatabase.addParametersRow("test", "beam process");
theDatabase.addParametersRow("test", "beam process 1");
theDatabase.addParametersRow("test", "beam process 2");
theDatabase.addParametersRow("test1", "beam process 1");
theDatabase.addParametersRow("test1", "beam process 2");
theDatabase.addParametersRow("test2", "beam process");
theDatabase.addParametersRow("test2", "beam process 1");
theDatabase.addParametersRow("test3", "beam process");
theDatabase.addGroupStatements();
for (final Entry<String, String> result : theDatabase.getParametersAll().entrySet()) {
System.out.print(result.getKey() + ", " + result.getValue() + "\n");
}
}
private static final Logger LOGGER = LoggerFactory.getLogger(SqLiteDB.class);
private Connection dbConnection = null;
private static SqLiteDB myInstance = null;
// *****************************************************************************************************************
// Public methods
// *****************************************************************************************************************
public static SqLiteDB initSqLiteDB() {
if (myInstance == null) {
myInstance = new SqLiteDB();
}
return myInstance;
}
public void addParametersRow(final String parameterName, final String beamProcessName) {
final String sqlInsert = "INSERT INTO PARAMETERS (PARAMETER_NAME, BEAM_PROCESS) VALUES ('" + parameterName
+ "', '" + beamProcessName + "');";
try (Statement insertStatement = dbConnection.createStatement()) {
insertStatement.execute(sqlInsert);
} catch (final SQLException ex) {
ErrorLogger.logError(ex.getStackTrace(), ex);
}
}
public Map<String, String> getParametersAll() {
final String sqlGetParameterCount = "SELECT * FROM PARAMETERS";
final Map<String, String> queryResults = new TreeMap<>();
try (Statement queryParameterCount = dbConnection.createStatement()) {
final ResultSet resultSet = queryParameterCount.executeQuery(sqlGetParameterCount);
getClass();
while (resultSet.next()) {
queryResults.put(resultSet.getString(1), resultSet.getString(2));
}
resultSet.close();
} catch (final SQLException ex) {
ErrorLogger.logError(ex.getStackTrace(), ex);
}
return queryResults;
}
// *****************************************************************************************************************
// Private methods
// *****************************************************************************************************************
private SqLiteDB() {
try {
dbConnection = DriverManager.getConnection("jdbc:sqlite::memory:");
} catch (final SQLException ex) {
ErrorLogger.logError(ex.getStackTrace(), ex);
}
createTableAvailableParameters();
}
private void createTableAvailableParameters() {
if (dbConnection != null) {
final String sqlCreateTable = "CREATE TABLE IF NOT EXISTS PARAMETERS (\n"
+ " PARAMETER_NAME text NOT NULL, BEAM_PROCESS text NOT NULL, PRIMARY KEY (PARAMETER_NAME, BEAM_PROCESS));";
try (final Statement statement = dbConnection.createStatement()) {
statement.execute(sqlCreateTable);
} catch (final SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void addGroupStatements() {
final String sqlGetParameterCount = "SELECT PARAMETER_NAME, COUNT(PARAMETER_NAME) FROM PARAMETERS GROUP BY PARAMETER_NAME HAVING COUNT(PARAMETER_NAME) > 1";
final Map<String, Integer> queryResults = new HashMap<>();
try (Statement queryParameterCount = dbConnection.createStatement()) {
final ResultSet resultSet = queryParameterCount.executeQuery(sqlGetParameterCount);
getClass();
while (resultSet.next()) {
queryResults.put(resultSet.getString(1), resultSet.getInt(2));
}
resultSet.close();
} catch (final SQLException ex) {
ErrorLogger.logError(ex.getStackTrace(), ex);
}
for (final Entry<String, Integer> resultRow : queryResults.entrySet()) {
if (resultRow.getValue() > 1) {
addParametersRow(resultRow.getKey(), "*");
}
}
}
}
When I run the code it produces the following output:
test, *
test1, *
test2, *
test3, beam process
I do not understand where my rows with "test(1,2), beam process(1,2)" are? Why / where are they lost?
Stackoverflow does not accept post with a lot of code. I wouldn't know how to truncate the code without omitting details which might be necessary. That's why I have to put in some more useless text. I hope it helps to make the question postable.
The loss happens in the function getParametersAll(). In this function, you iterate over the available results and add them to a Map. However, if duplicate values occur, you override the already read results in the map. Thus, you only get the last created beam process for each of the parameters.
One way to solve this would be to create a Map<String, List<String>> and return this map instead.
Map<String, List<String>> queryResults = new TreeMap<>();
while (resultSet.next()) {
if (!queryResults.contains(resultSet.getString(1)) {
queryResults.put(resultSet.getString(1), new ArrayList<>());
}
queryResults.get(resultSet.getString(1)).add(resultSet.getString(2));
}
I hope, this answers your question, otherwise I have probably misunderstood your problem.
Based on Illedhar's answer - thanks to that - I implemented the method getParametersAll using the Guava Multimap interface. Here the working code:
public Multimap<String, String> getParametersAll() {
final String sqlGetParameterCount = "SELECT * FROM PARAMETERS";
final Multimap<String, String> queryResults = ArrayListMultimap.create();
try (Statement queryParameterCount = dbConnection.createStatement()) {
final ResultSet resultSet = queryParameterCount.executeQuery(sqlGetParameterCount);
getClass();
while (resultSet.next()) {
queryResults.put(resultSet.getString(1), resultSet.getString(2));
}
resultSet.close();
} catch (final SQLException ex) {
ErrorLogger.logError(ex.getStackTrace(), ex);
}
return queryResults;
}
The output in the main method needs to be changed sightly too:
for (final Entry<String, String> result : theDatabase.getParametersAll().entries()) {
System.out.print(result.getKey() + ", " + result.getValue() + "\n");
}
For cudos please vote 1+ for Illedhar.

How to use Map as dataset element in JasperReports?

I'm passing a parameter to Jasper which is a collection of Maps. I would like to use this collection as dataset for a table.
If I had a collection of normal Java objects I would do:
$F{description}
to get the field. I would like to do something like:
get(description)
or
values().get(1)
Is it possible to retrieve a map value in a table like this?
As I really wanted to keep the service generic I decided for dynamic class creation with Javassist. It's an ugly solution but at least it works.
HashMap<String, Object> element = (HashMap<String, Object>) ((ArrayCollection) v).get(0);
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.makeClass("Dynamic"+System.currentTimeMillis());
element.keySet().forEach(s -> {
try {
//need only Strings
ctClass.addField(CtField.make("public String "+s+";", ctClass));
ctClass.addMethod(CtMethod.make("public String get" + StringUtils.capitalize(s) + "() { return " + s + "; }", ctClass));
} catch (Exception e) {
e.printStackTrace();
}
});
Class clazz = ctClass.toClass();
ArrayList<Object> objects = new ArrayList<>();
((Collection) v).forEach(m -> {
HashMap<String, Object> hm = (HashMap<String, Object>) m;
try {
Object obj = clazz.newInstance();
element.keySet().forEach(s -> {
try {
obj.getClass().getDeclaredField(s).set(obj, hm.get(s));
} catch (Exception e) {
e.printStackTrace();
}
});
objects.add(obj);
} catch (Exception e) {
e.printStackTrace();
}
});
parameters.put(k, new JRBeanCollectionDataSource(objects));

Im rusty, can't figure out how to do exception handling right in Java swing

So, i have this program, and it works okey. But i have a problem. You aren't suppose to be able to add an ID that's already in the ID table in my array.
This is the code for my listener on my add button (laggTill)
I don't know how to make the exception stop the data from being added. So when i for example put letters in my ID box im not suppose to be able to add it. But it still does. By JOptionPane comes upp and says the error message but still add it to the array. How do i stop this from happening?
I though an exception stopped everything, but apparently it doesn't.
And i also need the exception for ID checking to work.. i don't know how to do it.. i haven't been doing this for a while so i can't figure it out.
So, Basicly, My questions are: how do you make an exception hinder the data from being added. And how do i make my class check if the ID is unique?
Main class:
private class Listener implements ActionListener {
String getId;
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == laggTill) {
DTODjur dto = new DTODjur();
dto.djurNamn = textFieldNamn.getText();
dto.djurKategori = (String) comboBox.getSelectedItem();
try {
dto.djurID = Integer.parseInt(textFieldId.getText());
dao.laggTill(dto);
} catch (WrongDjurID ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
textArea.setText("Lade till: \nID: " + textFieldId.getText() + "\nNamn: " + textFieldNamn.getText() + "\nKategori: "+ comboBox.getSelectedItem());
}
DAO class:
public void laggTill(DTODjur dto) throws WrongDjurID {
boolean found = false;
openDB();
try {
int djurid = dto.djurID;
String djurnamn = dto.djurNamn;
String djurkategori = dto.djurKategori;
String SQL = "INSERT INTO h12mjont_djur(djurID,djurNamn,djurKategori) VALUES('" + djurid + "','" + djurnamn + "','" + djurkategori + "')";
System.out.println(SQL);
st.executeUpdate(SQL);
found=true;
} catch (SQLException ex) {
}
if (!found) {
throw new WrongDjurID("Id ska inte innehålla bokstäver");
}else {
dtodjur = getAll();
}
closeDB();
dtodjur = getAll();
}
Your problem is you are catching exceptions then proceeding as if nothing had happened by writing code after the catches. I'd suggest moving all catch logic to the very end of each method. In your first block change it to this:
String getId;
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == laggTill) {
DTODjur dto = new DTODjur();
dto.djurNamn = textFieldNamn.getText();
dto.djurKategori = (String) comboBox.getSelectedItem();
try {
dto.djurID = Integer.parseInt(textFieldId.getText());
dao.laggTill(dto);
textArea.setText("Lade till: \nID: " + textFieldId.getText() + "\nNamn: " + textFieldNamn.getText() + "\nKategori: "+ comboBox.getSelectedItem());
} catch (WrongDjurID ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
2nd block of code:
public void laggTill(DTODjur dto) throws WrongDjurID {
openDB();
try {
int djurid = dto.djurID;
String djurnamn = dto.djurNamn;
String djurkategori = dto.djurKategori;
String SQL = "INSERT INTO h12mjont_djur(djurID,djurNamn,djurKategori) VALUES('" + djurid + "','" + djurnamn + "','" + djurkategori + "')";
System.out.println(SQL);
st.executeUpdate(SQL);
dtodjur = getAll();
} catch (SQLException ex) {
throw new WrongDjurID("Id ska inte innehålla bokstäver");
} finally {
closeDB();
}
}
Now the getAll() call will not be run if an exception is thrown. Previously you were running getAll() even if an exception was thrown which would re-read the list. Remember to use finally clause to clean up after you read the DB regardless of if it was successful or an exception was thrown.

listen to incoming mails - JavaMail

I'm trying to write a class that is suppose to listen for incoming messages.
I had added a listener to my inbox.
I parse the messages in the inbox to look for a specific email, when that email is found I want my listener to stop listen to the inbox.
How can this be done?
This is my code:
public Map<String, Object> read(String id, Risk risk) {
setID(id);
try {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", email, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
inbox.addMessageCountListener(new MessageCountAdapter() {
public void messagesAdded(MessageCountEvent ev) {
setListenerExists(true);
boolean emailFound = false;
Message[] msgs = ev.getMessages();
System.out.println("Got " + msgs.length + " new messages");
if (msgs.length >= 1){
for (Message msg: msgs){
try {
Object o = msg.getContent();
if (o instanceof String){
hm = parser.parseMessage(adr, msg.getSubject(), msg.getContent(), getID());
System.out.println("FROM : " + adr);
System.out.println("SUBJECT : " + msg.getSubject());
System.out.println("HTML : " + msg.getContent());
}
else if (o instanceof Multipart){
Multipart mp = (Multipart) o;
BodyPart bp = mp.getBodyPart(0);
hm = parser.parseMessage(adr, msg.getSubject(), bp.getContent(), getID());
/*
System.out.println("FROM : " + adr);
System.out.println("SUBJECT : " + msg.getSubject());
System.out.println("HTML : " + bp.getContent());
*/
}
Iterator<Integer> it = hm.keySet().iterator();
while (it.hasNext()){
if (it.next() == 1){
map = extractValues(hm.get(1));
setMap(map);
//emailReceived = true;
//setEmailReceived(true);
//extractValues(hm.get(1));
}else{
/*
* TODO : remove listener
* setLisetn
*/
System.out.println("HM is Null!");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
while (emailFound == false){
for (Message msg : msgs){
try {
Object o = msg.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
*/
}
});
// Check mail once in "freq" MILLIseconds
boolean supportsIdle = false;
try {
if (inbox instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder)inbox;
f.idle();
supportsIdle = true;
}
} catch (FolderClosedException fex) {
throw fex;
} catch (MessagingException mex) {
supportsIdle = false;
}
for (;;) {
if (supportsIdle && inbox instanceof IMAPFolder) {
IMAPFolder f = (IMAPFolder)inbox;
f.idle();
System.out.println("IDLE done");
} else {
Thread.sleep(20000); // sleep for freq milliseconds
// This is to force the IMAP server to send us
// EXISTS notifications.
inbox.getMessageCount();
}
}
}catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return getMap();
}
public void setID(String id){
this.riskId = id;
}
public String getID(){
return riskId;
}
public void setMap(Map<String, Object> m){
this.map = m;
}
public Map<String, Object> getMap(){
return map;
}
public void setListenerExists(boolean exists){
this.listener = exists;
}
public boolean getListenerExists(){
return listener;
}
/** extracts values from hashmap received from the parser **/
public Map<String, Object> extractValues(HashMap<String, EmailData> h){
System.out.println("I'M Called");
Risk risk = new Risk();
String id = "";
String sender = "";
String answer = "";
HashMap<String, String> data;
Iterator<String> it = h.keySet().iterator();
while (it.hasNext()){
id = it.next();
EmailData ed = h.get(id);
sender = ed.getEmail();
answer = ed.getAnswer();
}
Map<String, Object> map = createVariablesToInsert(id, sender, answer);
return map;
}
public Map<String, Object> createVariablesToInsert(String id, String sender, String answer){
Map<String, Object> map = new HashMap<String, Object>();
System.out.println("I'M Called");
System.out.println("UUID : " + id);
System.out.println("USER : " + sender);
System.out.println("ANSWE : " + answer);
map.put("uuid", id);
map.put("user", sender);
map.put("ans", answer);
System.out.println("ID : " + map.get("uuid"));
System.out.println("USER : " + map.get("user"));
System.out.println("ANS : " + map.get("ans"));
System.out.println("ID in insert");
return map;
}
}
pay attention that you must declare two variables as final. it allow to access to those variables inside the implementation of MessageCountAdapter
final Folder inbox = store.getFolder("INBOX");
final MessageCountAdapter listener = new MessageCountAdapter() {
boolean emailFound = false;
// do something
if (emailFound) {
inbox.removeMessageCountListener(listener);
}
}
inbox.addMessageCountListener(listener);

Categories