java.sql.SQLException: Before start of result set - java

I don't understand why this isn't working, I keep getting this java.sql.SQLException: Before start of result set error, ive looked online but because ive been staring at a computer screen for hours my brain is frazzling so I'm not able to find any soloutions. please can you help me?! thanks
String from = "";
String subject= "";
String to= "";
String message= "";
try
{
while(retrieveMessages().next())
{
to = retrieveMessages().getString("tblEmail.to");
from = retrieveMessages().getString("tblEmail.from");
subject = retrieveMessages().getString("tblEmail.subject");
message = retrieveMessages().getString("tblEmail.message");
MailBox.add(new Email(to, from, subject, message));
}
}
catch (SQLException e)
{
e.printStackTrace();
}

You're calling retrieveMessages() multiple times. It doesn't help that you haven't shown us what that does, but I suspect you want to call it once and store the result in a local variable. At the moment, I suspect you're calling next() on one result set, then getString() on a different result set. For example:
try (ResultSet results = retrieveMessages()) {
while (results.next()) {
String to = results.getString("tblEmail.to");
String from = results.getString("tblEmail.from");
String subject = results.getString("tblEmail.subject");
String message = results.getString("tblEmail.message");
MailBox.add(new Email(to, from, subject, message));
}
}

Related

Adding a class to an ArrayList, but got NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
So, I was trying to add a class to an ArrayList, but when I do it gives me a Null Pointer Exception. I'm sure I am just overlooking a variable that I thought was initialized, but I can't figure it out.
This is the class:
enum WebType { GoogleResult, Webpage };
public class Webpage {
WebType type;
String pageName;
String content;
String url;
String MLA = "";
public Webpage(String pageName, String content, String url, WebType type){
this.type = type;
this.pageName = pageName;
this.content = content;
this.url = url;
this.MLA = ""; // Temp
}
// TODO: Make Citation Maker
}
This is where I add the class to the ArrayList:
public void Start(){
for(Integer i = 0; i < tags.size(); i++){
if(tags.get(i) == null)
return;
Webpage page = Google(tags.get(i));
parseList.add(page); // The Error is on this line!
log.append("Added " + page.url + " to parse list");
}
for(Integer i = 0; i < parseList.size(); i++){
ParsePageCode(parseList.get(i));
}
}
Here is the Google function, it googles whatever you tell it to and returns the page information:
public Webpage Google(String search){
String url = "https://www.google.com/search?q=" + search;
String content = "";
try {
URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
log.append("\n Unsupported Encoding Contacting Google");
}
try {
content = GetPageCode(url);
} catch (IOException e) {
log.append("\n Unable To Reach Google");
log.append(e.getMessage());
}
Webpage w = new Webpage("Google Result For " + search, content, url, WebType.GoogleResult);
// System.out.println(search + url + WebType.GoogleResult);
return w;
}
Any Ideas?
On the line that is throwing the exception, parseList is the only variable being dereferenced. The only other variable on that line is page, and it doesn't matter if page is null because you can add null elements to a List. So, it must be parseList causing the NPE.
Actually there is no problem adding null to a collection of Objects. Retrieving the object and invoking its members later may cause NPE.
You have told is that the problem is on the line where you do add the object. The only way there to cause NPE is calling add() upon null. So that's your collection parseList that is not initialized yet. Maybe it's a field in the class and was never initialized to an actual object of type ArrayList, but it's only declared.

Java returning null pointer exception for SQL query that gets passed to JSP

I am working on a school assignment that required us to use SQL statements in Java code as well as use the LIKE operator for a search. In order to properly search I have to get a string from the user, and split the string by any delimiter, and then run the query like so:
SELECT * FROM movies WHERE (movies.title LIKE '%userInput%');
I then return this query in the form of an ArrayList.
Now, when I was testing it out. I originally tested it with no user input, and my query became: SELECT * FROM movies WHERE (movies.title LIKE '%%');. This gave me the correct results.
However when I put a title in there, all of the sudden I get a NullPointerException on this line:
if(title.equals("")) { return "(movies.title LIKE '%%') "; from this section of my code:
public String getSearchString(String title) {
if(title.equals("")) { return "(movies.title LIKE '%%') "; }
String ret = "(";
ArrayList<String> titleArray = Util.splitSearch(title);
for(int i = 0; i < titleArray.size() - 1; ++i) {
String temp = titleArray.get(i);
String stmt = "movies.title LIKE '%" + temp + "%' OR ";
ret += stmt;
}
String temp = "movies.title LIKE '%" + titleArray.get(titleArray.size() - 1) + "%')";
ret += temp;
return ret;
}
This is then called like so:
public List<Movie> listMovies(String title) throws SQLException {
List<Movie> search = new ArrayList<Movie>();
if(null != title && title.isEmpty()) { title = ""; }
ResultSet res = queryMovies(getSearchString(title));
while(res.next()) {
Movie mov = new Movie();
mov.setTitle(res.getString("title"));
search.add(mov);
}
return search;
}
private static queryMovies(String st) throws SQLException {
ResultSet res = null;
try {
PreparedStatement ps = dbcon.prepareStatement(st);
res = ps.executeQuery();
} catch(SQLException e) {
e.printStackTrace();
}
return res;
}
I unfortunately have to do this since I won't know how much a user will enter. And I am also not allowed to use external libraries that make the formatting easier. For reference my Util.splitSearch(...) method looks like this. It should be retrieving anything that is a alphanumeric character and should be splitting on anything that is not alphanumeric:
public static ArrayList<String> splitSearch(String str) {
String[] strArray = str.split("[^a-zA-Z0-9']");
return new ArrayList(Arrays.asList(strArray));
}
What is interesting is when I pass in getSearchString(""); explicitly, I do not get a NullPointerException. It is only when I allows the variable title to be used do I get one. And I still get one when no string is entered.
Am I splitting the String wrong? Am I somehow giving SQL the wrong statement? Any help would be appreciated, as I am very new to this.
the "title" which is passed from input is null, hence you're getting nullpointerexception when you do title.equals("").
Best practices suggest you do a null check like (null != title && title.equals("")).
You can also do "".equals(title)

Java The method in the type Stub is not applicable for the arguments

I know that this is yet another topic with similar subject, but i've searched stackoverflow and i could not find answer to my problem.
The situation is as follows:
I have a webservice lets call it testservice with many methods. Recently i had to add another one so i did:
public int addPayments_p24(String sessionId, int pos_id, String amount, String currency, String title, String client, String address, String postal, String city, String country, String email, String language, String p24_sign) throws Exception {
int last_inserted_id=0;
try {
PreparedStatement statement = null;
int timestamp = (int)(System.currentTimeMillis() / 1000L);
statement = connection
.prepareStatement(
"Insert into p24_strefa(pos_id,session_id,amount,currency,title,client,address,postal,city,country,email,language,p24_sign,timestamp)" +
"values(?,?,?,?,?,?,?,?,?,?,?,?,?,?);", statement.RETURN_GENERATED_KEYS);
statement.setInt(1, pos_id);
statement.setString(2, sessionId);
statement.setString(3, amount);
statement.setString(4, currency);
statement.setString(5, title);
statement.setString(6, client);
statement.setString(7, address);
statement.setString(8, postal);
statement.setString(9, city);
statement.setString(10, country);
statement.setString(11, email);
statement.setString(12, language);
statement.setString(13, p24_sign);
statement.setInt(14, timestamp);
statement.executeUpdate();
ResultSet rs = statement.getGeneratedKeys();
if(rs.next())
{
last_inserted_id = rs.getInt(1);
}
} catch (Exception ex) {
_log.error("addpayments_p24", ex);
throw ex;
}
finally {
dispose();
}
return last_inserted_id;
}
Then i tried to call this method from jsp file like this:
String sessionId = request.getParameter( "p24_session_id" );
String amount = request.getParameter( "p24_amount" );
String currencys = request.getParameter("p24_currency");
String title = request.getParameter("p24_description");
String client = request.getParameter("p24_client");
String address = request.getParameter("p24_address");
String postal = request.getParameter("p24_zip");
String city = request.getParameter("p24_city");
String country = request.getParameter("p24_country");
String email = request.getParameter("p24_email");
String language = request.getParameter("p24_language");
String sign = get_sign_str(sessionId,amount,currencys);
int pos_id = 2414;
int testResponse;
try {
if (test== null) {
inittest();
}
testResponse = test.addPayments_p24("test",2,"test","test","test","test","test","test","test","test","test","test","test");
}
catch (testWebServicesExceptionException e)
{
e.printStackTrace();
}
The connection to webservice is done by this function:
private static testWebServicesStub test;
private synchronized void inittest() throws AxisFault {
if (test == null) {
String testWebServicesEndpoint = Settings
.gettestWebServicesEndpoint();
test= new testWebServicesStub(testWebServicesEndpoint);
}
}
As you can see i use Axis2.
And ofcourse i got the error:
The method addPayments_p24(AddPayments_p24) in the type TestWebServicesStub is not applicable for the arguments (String, int, String, String, String, String, String, String, String, String, String, String, String)
I sit at this problem for a third day now and I just can't figure it out. If anyone have any idea what's going on...
I almost forgot app is run on a apache-tomcat 7.0.34 if that changes anything but i've already tested on another version.
Ofcourse everything was compiled multiple times, after compilation I even decompiled everything to check if variable types are correct and of course they were...
I didn't use web services for a while, so I'm not sure about this, but, it seems that you are mixing between two methods just like the error suggests, it happens that you are calling the method
addPayments_p24(String, int, String, String, String, String, String, String, String, String, String, String, String)
which is not present in the client, neither it's interface (at least the visible scope of the call). the method present in the scope of the call (in the client) is addPayments_p24(AddPayments_p24), so you need to instantiate an object AddPayments_p24 probably with the arguments you wanted (String, int, String, String, String, String, String, String, String, String, String, String, String) , not sure about this but it seems to be true.
I would try to remove "throw ex;" and "throws Exception" from addPayments_p24.

GAE Query with Collection Parameter

I have verified that the entity I am looking for is in the datastore. I have verified that the list I pass as a method parameter contains this entity. I am trying to find all objects that have their 'userGmail' contained in the list of strings I pass.
Here is my code
#SuppressWarnings("unchecked")
#ApiMethod(name = "findFriendsByEmailList")
public CollectionResponse<ZeppaUser> findFriendsByEmailList(
#Named("emailsList") List<String> emailsList, User user)
throws OAuthRequestException {
if (user == null) {
throw new OAuthRequestException(
"Null User Authorization Exception, findFriendsByEmailList");
}
PersistenceManager mgr = null;
List<ZeppaUser> execute = null;
Query query = null;
try {
mgr = getPersistenceManager();
query = mgr.newQuery(ZeppaUser.class);
query.declareParameters("java.util.List emailListParam");
query.setFilter("emailListParam.contains( userGmail )");
execute = (List<ZeppaUser>) query.execute(emailsList);
query.closeAll();
} finally {
mgr.close();
}
return CollectionResponse.<ZeppaUser> builder().setItems(execute)
.build();
}
This is the stack trace I receive from it:
Something worth noting: I do not receive this error on lists I pass in that to not contain an element found in the datastore. Just when it does exist which leads me to believe that the Query has located the element but has not been closed or executed into a return parameter correctly. If it is preferable to return List that is more than ok. I have tried multiple variations of this with no success thus far. It is getting quite frustrating.
Ok so I found a way around it.
Lists cannot be passed into ApiEndpoints. That or I didn't figure out the correct way to do it and would LOVE an update on the proper way to do this.
Instead, in my client, I construct a String of emails seperated by a comma and send a string into the parameter as an 'encoded' string list then 'decode' it upon execution. Works well but seems hacky.
here are the methods I used. This is convenient though because it works with iOS as well.
public static String encodeListString(ArrayList<String> stringList){
StringBuilder stringbuilder = new StringBuilder();
stringbuilder.append(stringList.get(0));
if(stringList.size() > 1){
for( int i = 0; i < stringList.size(); i++){
stringbuilder.append(",");
stringbuilder.append(stringList.get(i));
}
}
return stringbuilder.toString();
}
public static List<String> decodeListString(String encodedString){
char[] characters = encodedString.toCharArray();
StringBuilder stringbuilder = new StringBuilder();
int position = 0;
ArrayList<String> stringList = new ArrayList<String>();
while(true){
try {
char character = characters[position];
if(character == ','){
String resultString = stringbuilder.toString();
stringList.add(resultString);
stringbuilder = new StringBuilder(); // clear it
} else {
stringbuilder.append(character);
}
position++;
} catch (ArrayIndexOutOfBoundsException aiex){
// List ended
String resultString = stringbuilder.toString();
if(!resultString.isEmpty())
stringList.add(resultString);
break;
}
}
return stringList;
}

How to overcome this java syntax so that double become string?

I am stuck in a situation whereby my Bean class - CartItemBean is in double.
public double getTotalCost() {
return dblTotalCost;
And the SetExpressCheckOutService class requires me to put the amount in String.
String amount = "";
CartItemBean details = new CartItemBean();
amount = details.getTotalCost();
try {
//calling the service, setting up the checkoutpage
String token = setExpressCheckoutService.setExpressCheckout(userId, amount,
currencyCode, returnURL, cancelURL, paymentAction);
log.info("Url to redirect to: https://www.sandbox.paypal.com
/webscr?cmd=_express-checkout&useraction=commit&token=" + token);
} catch (PayPalException e) {
// Log the exception
log.log(Level.WARNING, "Paypal exception", e);
}
}
I hope someone can advise me how to overcome a problem like this.
Thanks.
Use the toString method of the Double object:
String string = Double.toString(double);
So in your code do this:
String token = setExpressCheckoutService.setExpressCheckout(userId, Double.toString(amount), currencyCode, returnURL, cancelURL, paymentAction);
I have found the solution:
amount = Double.toString(details.getTotalCost());

Categories