Reputation: 675
i am building a server to sends questions to clients and then receive answer from them, but when i send a question to a client i want to make it as unaviable for sending again for one hour, i mean after i send a question to client , i want for one hour that question will never sends to any other clients,
static Hashtable<Integer, List<Integer>> unavialbeQuestions =
new Hashtable<Integer, List<Integer>>();
the key is the clientID, the value is list of the IDs of questions that will never send to that client in one hour, this function i used to make question as unaivalble
public void setUnavialbeQuestion(final String cellName, final int questionID) {
List<Integer> cells = getCellsIntersectedWithCell(cellName);
int cellID = getCellID(cellName);
cells.add(cellID);
for (int i = 0; i < cells.size(); i++) {
if (unavialbeQuestions.containsKey(cellID)) {
unavialbeQuestions.get(cells.get(i)).add(questionID);
} else {
List<Integer> lll = new LinkedList<Integer>();
lll.add(questionID);
unavialbeQuestions.put(cellID, lll);
}
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
f(cellName, questionID);
}
}, 1000 * 120);
}
}
see the function f()
that will fired after one hour (in my demo just 2mins), here is the problem, i got null pointer exception when executing the f()
function:
protected void f(String cellName, int questionDI) {
// TODO Auto-generated method stub
List<Integer> cells = getCellsIntersectedWithCell(cellName);
int cellID = getCellID(cellName);
cells.add(cellID);
for(int i=0;i<cells.size();i++){
int index = unavialbeQuestions.get(cells.get(i)).indexOf(questionDI);
unavialbeQuestions.get(cells.get(i)).remove(index);
}
}
the exception on the index
parameter,
what am i doing wrong?
Upvotes: 0
Views: 1517
Reputation: 692181
You don't check that the returned list is not null here:
unavialbeQuestions.get(cells.get(i)).indexOf(questionDI);
and here:
unavialbeQuestions.get(cells.get(i)).remove(index);
And you use different keys for your map here:
if (unavialbeQuestions.containsKey(cellID)) {
and here:
unavialbeQuestions.get(cells.get(i)).add(questionID);
(and your code is not thread-safe, also)
Upvotes: 2
Reputation: 2886
unavialbeQuestions or cells list may be null. If you are trying to access it's method, it will throw NullPointerException.
Upvotes: 1