I am getting error 500 and null pointer exception - java

I am making project on online examination in java.
I am facing a problem.
On starting base I have 15 questions in my database and I am fetching those sequentially.
The problem is that if I attempt all the answers I get the results otherwise I get error 500 and NullPointerException. The questions are multiple choice. Every question has four options. If I don't attempt all the questions then I get the above error.
<%#page import="java.sql.*"%>
<%
String st[] = new String[20];
String ans[] = new String[20];
int k=0;
//int length = Integer.parseInt(request.getAttribute("length").toString());
for (int i = 0; i < 15; i++)
{
int j = i + 1;
st[i] = request.getParameter("radio" + j);
System.out.println(st[i]);
}
Class.forName("oracle.jdbc.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "root", "root");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("Select ANS from ANSWERS order by ID");
//String ans = "";
int t;
while (rs.next()) {
ans[k] = rs.getString("ans");
k++;
System.out.println(ans[k]);
}
int count = 0;
//String answers[] = ans.split(" ");
for (int i = 0; i < 15; i++) {
if (st[i].equals(ans[i])) {
count++;
}
}
out.println("Your " + count + " answers are correct");
%>

At the start of your code you're initializing your st[] with request.getParameter("radio" + j); This might come as null. As per the javadoc for getParameter():
Returns the value of a request parameter as a String, or null if the
parameter does not exist.
So when you try to execute this following piece of code:
for (int i = 0; i < 15; i++) {
if (st[i].equals(ans[i])) {
count++;
}
}
There is a chance that st[i] is in fact null. This might possibly be a reason for the NullPointerException in your code

You should be enclosing your logic in try catch and in finally handle the SQL exception for connection, rs (in separate try catch blocks)
Also, try lloking at the stack trace, as to which line gives the null pointer exception

I would say that your answers are simply not submitted back with your request. If the radio group for a question does not have a selected value, that radio group is not going to be part of the POST request that you are processing after the form submission.
That is why you get the Null pointer exception in the first place.
I cannot runt your example above, but i assume that the error is happening in the comparison line at the end of your example:
if (st[i].equals(ans[i])) {
Update
For a quick fix, just switch the evaluated values: st[i].equals(ans[i]) to ans[i].equals(st[i]). That way you can always do a equals against null and get the correct count.

Related

How to resolve IndexOutOfBoundsException: Invalid index 1, size is 1? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
i've just recived java.lang.IndexOutOfBoundsException: but can't understand what its caused from. Basically, i am integrating records of sqlite table into listview.
Here is my sql query to fetch records from the table.
public ArrayList<Integer> getRecordsCount(int no) {
ArrayList<Integer> count = new ArrayList<>();
Cursor c = database.rawQuery(
"select count(*) as TotalCount, tDate, " +
"strftime('%d', tDate) as DayPart, " +
"strftime('%m', tDate) as MonthPart, " +
"strftime('%Y', tDate) as YearPart " +
"from library " +
"where type = '" + no + "' " +
"group by MonthPart, YearPart", null);
while (c.moveToNext()) {
count.add(c.getInt(0));
}
return count;
}
This is my method to retrieve that data :-
public void setDataInList(int no) {
if (no == 0) {
ArrayList<Integer> count = helper.getRecordsCount(1);
mainGetLibraryModels.clear();
MainLibraryModelWS modelWS = helper.getAllRecordsMonthWise2(no);
for (int i = 0; i < modelWS.getRecords().size(); i++) {
WSLibraryModel model = new WSLibraryModel();
model.setAmount(modelWS.getRecords().get(i).getAmount());
model.setTotalCount("" + count.get(i));
model.setYearPart(modelWS.getRecords().get(i).getYearPart());
model.setMonthPart(modelWS.getRecords().get(i).getMonthPart());
mainGetLibraryModels.add(model);
}
adapter.notifyDataSetChanged();
} else if (no == 1) {
ArrayList<Integer> count = helper.getRecordsCount(2);
mainGetLibraryModels.clear();
MainLibraryModelWS modelWS = helper.getAllRecordsMonthWise2(no);
for (int i = 0; i < modelWS.getRecords().size(); i++) {
WSLibraryModel model = new WSLibraryModel();
model.setAmount(modelWS.getRecords().get(i).getAmount());
model.setTotalCount("" + count.get(i));
model.setYearPart(modelWS.getRecords().get(i).getYearPart());
model.setMonthPart(modelWS.getRecords().get(i).getMonthPart());
mainGetLibraryModels.add(model);
}
adapter.notifyDataSetChanged();
} else {
mainGetLibraryModels.clear();
MainLibraryModelWS modelWS = helper.getAllRecordsMonthWise2(no);
for (int i = 0; i < modelWS.getRecords().size(); i++) {
WSLibraryModel model = new WSLibraryModel();
model.setAmount(modelWS.getRecords().get(i).getAmount());
model.setTotalCount(" - ");
model.setYearPart(modelWS.getRecords().get(i).getYearPart());
model.setMonthPart(modelWS.getRecords().get(i).getMonthPart());
mainGetLibraryModels.add(model);
}
adapter.notifyDataSetChanged();
}
}
But, when i run this code, it gives me this error?
FATAL EXCEPTION: main Process: com.teezom, PID: 14168
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
first of all use switch instead of if-else branching , because what i see your Result from query will give the fix number of result as an array (switch is more efficient and improve readability) .
public void setDataInList(int no) { //just a suggestion not a answer
switch (no){
case 0 :
//Your Code as you specified in your code context.
break;
case 1 :
//Your Code as you specified in your code context.
break;
case 2 :
//Your Code as you specified in your code context.
break;
default :
break;
}
Now Coming to your problem if you see your Exception StackTrace and debug the application once you will get your solution easily.
this is what your stacktrace says--
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
Hope you know this popular exception IndexOutOfBoundsException only came while you try to access the any array index which is not present in array.
Now your error message clearly said that your Array size is one. It means your array will only accessible to index zero (0).
So, Please debug your code and try to find out which line of code is generating exception in-fact
Instead of this :
ArrayList<Integer> count = helper.getRecordsCount(1);
Try this :
ArrayList<Integer> count = helper.getRecordsCount(0);
First, you need to avoid calling getRecords() so many times. It costs performance and might not be returning the same result - the possible reason for your error. Instead, introduce a local parameter as a cache output of this function and play with it.

Selenium NoSuchElementException

I am getting the following error.
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element
(Session info: chrome=39.0.2171.95)
From the looks of the error message it says that it couldnt find such element.
So i added a wait until the element appears.
The funny thing is that the error occurs on the line driver.findElement which means that the wait was able to find the element.
The question is obviously why is selenium not able to find the element.
At first i thought it was because of using a variable in the string
driver.findElement(By.id("_ctl0_ContentPlaceHolder1_eoiSectionSummary_individualRepeater__ctl0_sectionRepeater__ct" + i + "_isCompleteLabel")).getText();
So i tried to store the string somewhere and then findElement with it.
As you see in the code below i have tried using print to verify that the string is the same as the one in the web. And they do match.
Im currently out of ideas now. Please help. Please let me know if you need any other information
public int verifyCompletion() {
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("_ctl0_ContentPlaceHolder1_eoiSectionSummary_individualRepeater__ctl0_sectionRepeater__ctl0_isCompleteLabel")));
int uncompletedCounter = 0;
for (int i = 10; i < 20; i++) {
String text = "_ctl0_ContentPlaceHolder1_eoiSectionSummary_individualRepeater__ctl0_sectionRepeater__ct" + i + "_isCompleteLabel";
driver.findElement(By.id(text)).getText();
System.out.println(text);
boolean sectionCompleted =text.equalsIgnoreCase("Yes");
if (!sectionCompleted) {
uncompletedCounter++;
}
}
return uncompletedCounter;
}
I see a small bug in your selector. You are not parameterizing the selector correctly. I am not sure if it a very efficient way to handle this scenario though.
String selector = "_ctl" + i + "_ContentPlaceHolder1_eoiSectionSummary_individualRepeater__ctl" + i + "_sectionRepeater__ctl" + i + "_isCompleteLabel";
Edit: more precise code should look like this:
public int verifyCompletion() {
int uncompletedCounter = 0;
for (int i = 0; i < 10; i++) {
String selector = "_ctl" + i + "_ContentPlaceHolder1_eoiSectionSummary_individualRepeater__ctl" + i + "_sectionRepeater__ctl" + i + "_isCompleteLabel";
(new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id(selector)));
String elementText = driver.findElement(By.id(selector)).getText();
System.out.println(selector);
System.out.println(elementText);
boolean sectionCompleted =text.equalsIgnoreCase("Yes");
if (!sectionCompleted) {
uncompletedCounter++;
}
}
return uncompletedCounter;
}

why is there a null pointer exception in the for loop, when I can have access the array element?

I am using temboo to get all the events for a calendar. However, i am trying to create a hashtable of the events and the days. but the for loop says its a null pointer exception even though the program is actually able to access that ith element. I have even printed it and the i is less than the size of the array. Here is the snippet code: Error is in the second line of the for loop.Errr occurs when i = 23, but items.size is 41.
GetAllEvents getAllEventsChoreo = new GetAllEvents(session);
// Get an InputSet object for the choreo
GetAllEventsInputSet getAllEventsInputs = getAllEventsChoreo.newInputSet();
// Set inputs
getAllEventsInputs.set_AccessToken(accessToken);
getAllEventsInputs.set_ClientID(clientID);
getAllEventsInputs.set_ClientSecret(clientSecret);
getAllEventsInputs.set_CalendarID(callIDs[0]);
// Execute Choreo
GetAllEventsResultSet getAllEventsResults = getAllEventsChoreo.execute(getAllEventsInputs);
results = getAllEventsResults.get_Response();
System.out.println(results);
root = jp.parse(results);
rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("items").getAsJsonArray();
System.out.println("Abour to enter the for loop\nItems:\n"+items.toString());
System.out.println("****************************\nEnter the for loop");
System.out.println("iems Size: "+items.size());
System.out.println(items.get(23).toString());
for(int i = 0;i < items.size();i++)
{
System.out.println("i: "+i);
String startTime = items.get(i).getAsJsonObject().get("start").getAsJsonObject().get("dateTime").getAsString();
System.out.println("startTime: "+startTime);
String dayKey = startTime.split("T")[0];
if(dayKey.equals(beginDate)==false | dayKey.equals(endDate)==false)
{
System.out.println(startTime + " not the one interested so skipping");
continue;
}
System.out.println("passed the first if in for loop");
String endTime = items.get(i).getAsJsonObject().get("end").getAsJsonObject().get("dateTime").getAsString();
String name = items.get(i).getAsJsonObject().get("summary").getAsJsonPrimitive().getAsString();
calendarEvent eventTemp = new calendarEvent(name,startTime,endTime);
if(table.containsKey(dayKey))
table.get(dayKey).add(eventTemp);
else
{
ArrayList<calendarEvent> schedule = new ArrayList<calendarEvent>();
schedule.add(eventTemp);
table.put(dayKey,schedule);
}
}
Set<String> key = table.keySet();
Iterator<String> it = key.iterator();
while(it.hasNext())
{
String keyValue = it.next();
System.out.println("Events on "+keyValue);
ArrayList<calendarEvent> temp = table.get(keyValue);
for(int j =0;j<temp.size();j++)
{
System.out.println(temp.get(j));
}
}
After breaking down the exception line, the exception occurs when I try to get the dateTime as string, the last part creates an exception.
Just because the ith element of an array exists, it does not mean that the element is not null.
Referencing a property or method of such an element will yield a NullPointerException.
If i went beyond the bounds of the array, you would get an ArrayIndexOutOfBoundsException instead.
Check indexed array elements for null before using them.
Sorry to be brief and not reference your code or other sources. I am on my phone. The likely source of your problem is pretty clear, though.

Java Bean not working as expected

OK, I have a JSP running the following script section.
<% irCollection mgrq = new irCollection();
mgrq.setMgrid("Chris Novish");
mgrq.populateCollection();
int pagenum;
if (request.getParameter("p") != null) {
String pagedatum=request.getParameter("p");
pagenum = Integer.parseInt(pagedatum);
} else { pagenum = 0; }
for (int i=0;i<10;i++) {
int rownum = pagenum * 10 + i;
InquireRecord currec = mgrq.getCurRecords(rownum);
out.println(currec.getID()); %>
irCollection has an ArrayList property that stores a several InquireRecord objects. It gets this data from a database using the mgrid as (set in line 2 there) as the matching term.
But I'm getting an IndexOutOfBounds exception on what appears here as line 11.
I've done some tests, and I'm pretty sure that it's because populateCollection() isn't getting things done. I have a getSize method that gives me a size of 0.
I made a test class in Eclipse to make sure all my methods were working:
package com.serco.inquire;
public class test {
public static void main (String[] args) {
String mgr = "Chris Novish";
irCollection bob = new irCollection();
bob.setMgrid(mgr);
bob.populateCollection();
InquireRecord fred = bob.getCurRecords(1);
System.out.println(fred.getID());
}
}
That test class produces exactly what I'd expect.
Other than the names of some of the local variables, I can't see what I'm doign different in the JSP.
So... tell me, what noobish mistake did I make?
for the sake of being thorough, here's the populateCollection() method:
public void populateCollection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename = "inquire.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection( database ,"","");
Statement s = con.createStatement();
s.execute ("SELECT * FROM inquiries WHERE manager = '" + mgrid + "'");
ResultSet rs = s.getResultSet();
int cur;
if (rs != null) {
while (rs.next()) {
cur = rs.getRow();
cur -- ;
int curID = rs.getInt("ID");
this.newIR.setID(curID);
String cursub = rs.getString("submitter");
this.newIR.setSubmitter(cursub);
this.iRecords.add(cur, this.newIR);
}
this.size = iRecords.size();
this.pages = this.size / 10;
int remain = this.size % 10;
if (remain > 0) { this.pages++; }
} else { System.out.println("no records."); }
}
catch (Throwable e) {
System.out.println(e);
}
}
Your IndexOutOfBounds exception is probably being caused by the value of rownum being passed to mgrq.getCurRecords().
Your test code proves nothing because there you're calling getCurRecords() with a constant which is probably always valid for your system and will never cause the exception.
My suggestion is to step through the code in your JSP with a debugger, or even simply to print out the value of your variables (especially pagedatum, pagenum and rownum) in your JSP code.
Is your JSP Snippet correct? It looks like you started the braces for the
for (int i=0;i<10;i++) {
but I dont see a end braces for that at all. Can you check if that is the case and if so, fix the code appropriately?

how to generate RSS for news sites programmatically in java/j2ee?

how to generate RSS for news sites programmatically? I dont know how to start..
I learned how to write RSS from this article:
http://www.petefreitag.com/item/465.cfm
You can also just go to an RSS feed you like and press "View Source". Then you should simply use your java application to reproduce an XML similar to the XML you see (Only with your data).
When you finish, use one of many RSS Validators to validate your RSS.
It's easier than it first looks...
This code shows how to query a database to generate arbitrary XML from a JSP, manually.
It's not RSS, but the idea might be helpful to you.
private String ExecQueryGetXml(java.sql.PreparedStatement stmt, String rowEltName) {
String result= "<none/>";
String item;
java.sql.ResultSet resultSet;
java.sql.ResultSetMetaData metaData ;
StringBuffer buf = new StringBuffer();
int i;
try {
resultSet = stmt.executeQuery();
metaData= resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
String[] columnNames = new String[numberOfColumns];
for( i = 0; i < numberOfColumns; i++)
columnNames[i] = metaData.getColumnLabel(i+1);
try {
// if ((root!=null) && (!root.equals("")))
// buf.append('<').append(root).append('>').append('\n');
// each row is an element, each field a sub-element
while ( resultSet.next() ) {
// open the row elt
buf.append(' ').append('<').append(rowEltName).append(">\n");
for( i= 0; i < numberOfColumns; i++) {
item = resultSet.getString(i+1);
if(item==null) continue;
buf.append(" <").append(columnNames[i]).append('>');
// check for CDATA required here?
buf.append(item);
buf.append("</").append(columnNames[i]).append(">\n");
}
buf.append("\n </").append(rowEltName).append(">\n");
}
// conditionally close the row elt
// if ((root!=null) && (!root.equals("")))
// buf.append("</").append(root).append(">\n");
result= buf.toString();
}
catch(Exception e1) {
System.err.print("\n\n----Exception (2): failed converting ResultSet to xml.\n");
System.err.print(e1);
result= "<error><message>Exception (2): " + e1.toString() + ". Failed converting ResultSet to xml.</message></error>\n";
}
}
catch(Exception e2) {
System.err.print("\n\n----Exception (3).\n");
System.err.print("\n\n----query failed, or getMetaData failed.\n");
System.err.print("\n\n---- Exc as string: \n" + e2);
System.err.print("\n\n---- Exc via helper: \n" +
dinoch.demo.ExceptionHelper.getStackTraceAsString(e2));
result= "<error><message>Exception (3): " + e2 + ". query failed, or getMetaData() failed.</message></error>\n";
}
return result;
}
How about using a framework like Rome or jrss

Categories

Resources