Incorrect page number in List of Listings

The problem I'm having is that page numbers, in a List of Listings, are frequently off by one page.

I'm using the listings package and I have a List of Listings in the beginning of the document, generated by the command \listoflistings.

I'm using the following environment for writing the listings.

\lstnewenvironment{javacode}[2]
{
\refstepcounter{listings}%
\label{lst:#2}%
\addcontentsline{lst}{listings}{\protect\numberline{\thelistings}#1}%
\lstset{language=Java,caption=#1,breaklines=true,breakatwhitespace=false,float=phtb}
}
{
}


The issue appears when there isn't enough space for the listing in a page and it is moved to the next one. In those cases, the page number that appears in the list of listing is off by one page, because the anchor remained in its place in the text, but the actual listing got moved to the next page.

Do you know how can I fix it? I guess a solution should exist since I just want to replicate the behavior of figures and tables, and List of Figures and List of Tables.

-
Why the \refstepcounter and \addcontentsline commands? \lstnewenvironment{javacode}[2]{\lstset{language=Java,label=lst:#2,caption=#1,b‌​reaklines=true,breakatwhitespace=false,float=phtb}}{} appears to work fine as-is, and may remove your problem. – Mike Renfro Feb 6 '12 at 4:10
Would you be able to provide a (small) minimal working example (MWE) that duplicates your problem? – Werner Feb 6 '12 at 5:22
@MikeRenfro I was using the variable "listings" for keeping track of the number of listings. \addcontentsline was for adding it automatically to the list. I was using a \listoflistings, based on the toclof package, instead of the \lstlistoflistings' that package listingsp provides. Right now I'm incapable of remembering why I was doing that. Thanks for your help. – nozebacle Feb 6 '12 at 11:36
Since you have some responses below that seem to answer your question, please consider marking one of them as ‘Accepted’ by clicking on the tickmark below their vote count (see How do you accept an answer?). This shows which answer helped you most, and it assigns reputation points to the author of the answer (and to you!). It's part of this site's idea to identify good questions and answers through upvotes and acceptance of answers. – Jubobs Mar 2 '14 at 12:02

1 Answer

Not sure why the \refstepcounter and \addcontentsline commands are present. The following appears to work fine on its own:

\documentclass{article}
\usepackage{listings}
\lstnewenvironment{javacode}[2]{\lstset{language=Java,label=lst:#2,caption=#1,breaklines=true,breakatwhitespace=false,float=phtb}}{}
\begin{document}
\lstlistoflistings
\begin{javacode}{Java code caption}{code}
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
\end{javacode}
Listing~\ref{lst:code} is a Hello, world!'' program.
\end{document}

-