2D object giving a nullpointerexception? - java

I'm having a bit of a problem when running the code below. This code is used when a button on a gui screen is pressed. Basically the function of this button is to read text entered into 2 text fields, derive a third value from the 2, and save all 3 in a row in a table on the GUI screen, using a 2d array.
However, i get a NullPointerException when executing it at the 5th line inside the method addItem().
saleData is the 2D array with data which is in the table.
i have instantiated the temp[][] object with 1 row more than the saleData object because i need to add a row to the table, and then i make saleData=temp.
This code worked as it is in the Gui class before i tried using OOP to create a separate class for the GUI to work from.
The nullpointer exception refers to the temp object, i know this because i printed out the value of temp and it was a null.
Does anyone have any ideas?
thanks in advance.
public void addItem() {
int len = saleData.length + 1;
Object[][] temp = new Object[len][3];
for (int k = 0; k < saleData.length; k++) {
for (int i = 0; i < 3; i++) {
temp[k][i] = ((DefaultTableModel) table.getModel()).getValueAt(k, i);
}
}
tblContainer.removeComponent(table);
try {
int qty = Integer.parseInt(txtQty.getText());
String item = (String) items.getSelectedItem();
String sql = "Select Sell_price from stockInfo where parts like '" + item + "'";
double total = 0;
if (saleData.length != 1) {
for (int i = 0; i < saleData.length; i++) {
String sql2 = "Select sell_price from stockinfo where parts like '" + temp[i][1].toString() + "'";
try {
System.out.println("Check 0");
pst = conn.prepareStatement(sql2);
System.out.println("Check 1");
rs = pst.executeQuery();
System.out.println("Check 2");
while (rs.next()) {
System.out.println("Check 3");
String qt = temp[i][0].toString();
temp[i][2] = Double.parseDouble(rs.getString("sell_price")) * Integer.parseInt(qt);
System.out.println("Check 4");
}
} catch (Exception e) {
Dialog.show("Error", "Error 1: " + e, "OK", null);
}
}
}
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
double price = Double.parseDouble(rs.getString("Sell_Price"));
total = qty * price;
try {
for (int m = 0; m < saleData.length; m++) {
for (int n = 0; n < 3; n++) {
((DefaultTableModel) table.getModel()).setValueAt(m, n, temp[m][n]);
}
}
temp[saleData.length][0] = qty;
temp[saleData.length][1] = item;
temp[saleData.length][2] = total;
saleData = temp;
table = new Table(new DefaultTableModel(saleColumns, saleData, true));
tblContainer.addComponent(table);
((TableLayout) table.getLayout()).setGrowHorizontally(true);
saleForm.revalidate();
} catch (NullPointerException e) {
}
}
} catch (SQLException e) {
Dialog.show("Error", "SQL Error Record Sale", "OK", null);
}
} catch (NumberFormatException nfe) {
Dialog.show("Error", "Please enter a valid quantity", "OK", null);
}
}

The temp array can not be null. You just created it.
temp[k][i] can be null (and should be, by the way), but that does not matter - it is being assigned a value.
If a dimension of temp would not be big enough, you'd get an ArrayIndexOutOfBoundsException
So this leaves for two things that can get to be null (if the error stems from that line, and not for example from the inside of getValueAt(k,i) ):
table
table.getModel()
Use a debugger, and it will make your life easier...

Related

Strings can not be converted to DAO Receiver

I am trying to perform batch insertion operation with a list object but while inserting I am getting String cannot be converted to DAO.The receiver in the iterator loop.
I have tried to list the list object, at that time it is printing values from the list. but, when I use generics are normal list it is showing error and I don't find any solution to insert
From this method I am reading the excel file and storing into list
public List collect(Receiver rec)
{
//ReadFromExcel rd = new ReadFromExcel();
List<String> up = new ArrayList<String>();
//List<String> details = rd.reader();
//System.out.println(details);
try( InputStream fileToRead = new FileInputStream(new File(rec.getFilePath())))
{
XSSFWorkbook wb = new XSSFWorkbook(fileToRead);
wb.setMissingCellPolicy(Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
XSSFSheet sheet = wb.getSheetAt(0);
DataFormatter fmt = new DataFormatter();
String data ="";
for(int sn = 0;sn<wb.getNumberOfSheets()-2;sn++)
{
sheet = wb.getSheetAt(sn);
for(int rn =sheet.getFirstRowNum();rn<=sheet.getLastRowNum();rn++)
{
Row row = sheet.getRow(rn);
if(row == null)
{
System.out.println("no data in row ");
}
else
{
for(int cn=0;cn<row.getLastCellNum();cn++)
{
Cell cell = row.getCell(cn);
if(cell == null)
{
// System.out.println("no data in cell ");
// data = data + " " + "|";
}
else
{
String cellStr = fmt.formatCellValue(cell);
data = data + cellStr + "|";
}
}
}
}
}
up = Arrays.asList(data.split("\\|"));
// System.out.println(details);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
}
Iterator iter = up.iterator();
while(iter.hasNext())
{
System.out.println(iter.next());
}
String row="";
Receiver info = null;
String cid = "";
String cname = "";
String address = "";
String mid = "";
boolean b = false;
List<Receiver> res = new ArrayList<Receiver>();
int c = 0;
try
{
String str = Arrays.toString(up.toArray());
//System.out.println(str);
String s = "";
s = s + str.substring(1,str.length());
// System.out.println("S:"+s);
StringTokenizer sttoken = new StringTokenizer(s,"|");
int count = sttoken.countTokens();
while(sttoken.hasMoreTokens())
{
if(sttoken.nextToken() != null)
{
// System.out.print(sttoken.nextToken());
cid = sttoken.nextToken();
cname = sttoken.nextToken();
address = sttoken.nextToken();
mid = sttoken.nextToken();
info = new Receiver(cid,cname,address,mid);
res.add(info);
System.out.println("cid :"+cid+ " cname : "+cname +" address : "+address+" mid : "+mid);
c = res.size();
// System.out.println(c);
}
else
{
break;
}
}
System.out.println(count);
// System.out.println("s");
}
catch(NoSuchElementException ex)
{
System.out.println("No Such Element Found Exception" +ex);
}
return up;
}
with this method I'm trying to insert into database
public boolean insert(List res)
{
String sqlQuery = "insert into records(c_id) values (?)";
DBConnection connector = new DBConnection();
boolean flag = false;
// Iterator itr=res.iterator();
// while(it.hasNext())
// {
// System.out.println(it.next());
// }
try( Connection con = connector.getConnection();)
{
con.setAutoCommit(false);
PreparedStatement pstmt = con.prepareStatement(sqlQuery);
Iterator it = res.iterator();
while(it.hasNext())
{
Receiver rs =(Receiver) it.next();
pstmt.setString(1,rs.getcID());
pstmt.setString(2,rs.getcName());
pstmt.setString(3,rs.getAddress());
pstmt.setString(4,rs.getMailID());
pstmt.addBatch();
}
int [] numUpdates=pstmt.executeBatch();
for (int i=0; i < numUpdates.length; i++)
{
if (numUpdates[i] == -2)
{
System.out.println("Execution " + i +": unknown number of rows updated");
flag=false;
}
else
{
System.out.println("Execution " + i + "successful: " + numUpdates[i] + " rows updated");
flag=true;
}
}
con.commit();
} catch(BatchUpdateException b)
{
System.out.println(b);
flag=false;
}
catch (SQLException ex)
{
Logger.getLogger(BImplementation.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
flag=false;
}
return flag;
}
I want to insert list object using JDBC batch insertion to the database.
Your method collect(Receiver rec) returns the List of strings called up.
return up;
However (if you are really using the method collect to pass the List into insert(List res) method), you are expecting this list to contain Receiver objects. Which is incorrect, since it collect(..) returns the list of Strings.
And that causes an error when you try to cast Receiver rs =(Receiver) it.next();
You need to review and fix your code, so you will pass the list of Receiver objects instead of strings.
And I really recommend you to start using Generics wherever you use List class. In this case compiler will show you all data-type errors immediately.

How to count the same value occurences in arrayList

Here is the snippet of code where I want to find the multiple occurrences of animal name.
I have written the code comparing the list indexes, but unable understand how to compare the names and count the number of occurrences of each name.
List<Animals> animalList= new ArrayList<Animals>();
try {
CallableStatement stmt = conn.prepareCall(callProcedure, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
boolean results = stmt.execute();
if (results) {
ResultSet rs = stmt.getResultSet();
int count = 0;
while (rs.next()) {
Animals animal = new Animals();
animal.setAnimalName(rs.getString("animal_name"));
animal.setAge(rs.getString("age"));
animal.setHealth(rs.getString("health"));
animalList.add(animal);
count++;
}
}
int nbOccurences = 1;
for (int i = 0, length = animalList.size(); i < length; i++) {
if (i < length - 1) {
if (animalList.get(i) == animalList.get(i+1)) {
nbOccurences++;
}
} else {
System.out.println( animalList.get(i) + " occurs " + nbOccurences
+ " time(s)"); //end of array
}
if (i < length - 1 && animalList.get(i) != animalList.get(i+1)) {
System.out.println( animalList.get(i) + " occurs " + nbOccurences
+ " time(s)"); //moving to new element in array
nbOccurences = i;
}
}
} catch (SQLException sqlE) {
sqlE.printStackTrace();
}
return animalList;
The easiest solution, IMHO would be to stream the animal list, group by the name and count:
Map<String, Long> nameCount =
animalList.stream()
.collect(Collectors.groupingBy(Animal::getName,
Collectors.counting()));

JAVA SQL command not properly ended

I have this code:
buy.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent actionEvent)
{
int r;
r = table.getSelectedRow();
String num = (String) table.getValueAt(r, 0);//numele jucariei
//String cop = (String) table.getValueAt(r, 3);//nr de bucati
try
{
pq = stmt.executeQuery("SELECT *" + "FROM buyid_view");
xv = stmt.executeQuery("SELECT toyid, copies " + "FROM alldatas_view" + "WHERE toyname ='"+num+"'");
int buyid = pq.getInt("buyid");
int toyid = xv.getInt("toyid");
int copies = xv.getInt("copies");
copies = copies-1;
CallableStatement cstmt = con.prepareCall("INSERT INTO buy (buyid, toyid)" + "VALUES (?,?)");
cstmt.setInt("buyid", buyid);
cstmt.setInt("toyid", toyid);
ResultSet rs = cstmt.executeQuery();
JOptionPane.showMessageDialog(null, "You brought a toy.");
for(int i = 0; i < table.getRowCount(); i++)
for(int j = 0; j < table.getColumnCount(); j++)
table.setValueAt("", i, j);
try
{
rs = stmt.executeQuery("UPDATE toys set copies "+ copies +"WHERE toyid= '"+toyid+"'");
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
int i = 0;
try
{
rs = stmt.executeQuery("SELECT *"+
"FROM availablebooks_view");
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try {
if(rs.next())
{
table.setValueAt(rs.getString(1), i, 0);
table.setValueAt(rs.getString(2), i, 1);
table.setValueAt(rs.getString(3), i, 2);
i++;
while(rs.next())
{
table.setValueAt(rs.getString(1), i, 0);
table.setValueAt(rs.getString(2), i, 1);
table.setValueAt(rs.getString(3), i, 2);
i++;
}
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
catch (SQLException e)
{
if(e.getMessage().contains("You have to pay!"))
warning(frame, "You didn't pay all your products");
else
warning(frame, e.getMessage());
}
}
});
When I compile my program I don't have any error but when I run it and I click on the buy button it gives me an error saying "ORA-00933: SQL command not properly ended".
When building SQL statements from strings you must ensure there are spaces where spaces are needed.
rs = stmt.executeQuery("SELECT *"+
"FROM availablebooks_view");
The statement you are sending is
SELECT *FROM availablebooks_view
which is invalid syntax. You have this problem in several places in your code.
However, you have a larger issue which results from building your SQL statements piecemeal. This leaves you open to SQL Injection and you should rewrite your code to use prepared statements and parameters instead.
There are multiple errors in your code
First one is
rs = stmt.executeQuery("SELECT *"+
"FROM availablebooks_view");
There is no space between * and FROM, this will actually creates a syntax error
Second one is
rs = stmt.executeQuery("UPDATE toys set copies "+ copies +"WHERE toyid= '"+toyid+"'");
There is no = after set copies, this will also create error.
Third one is
CallableStatement cstmt = con.prepareCall("INSERT INTO buy (buyid, toyid)" + "VALUES (?,?)");
Give space before VALUES

J2ME , Quizz using choiceGroups

I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}

Resultset getmethod in If condition

I'm working on java JDK7 and Microsoft Access 2007.Basically I want to get the minimum value from the all the columns of row1. But the following code doesn't work.
import java.io.*;
import java.util.*;
import java.net.*;
import java.sql.*;
public class server
{
public void check()
{
int min = 100, row = 0, index, i = 2;
try {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn = DriverManager.getConnection("jdbc:odbc:DSN2");
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery("select *from Table1");
rs.next();
System.out.println(rs.getInt(1) + "\t" + rs.getInt(2) + "\t" + rs.getInt(3) + "\t" + rs.getInt(4) + "\t" + rs.getInt(5) + "\t" + rs.getInt(6));
for (i = 2; i < 7; i++)
{
System.out.println("hello");
if (rs.getInt(i) < min) {
index = i;
min = rs.getInt(i);
}
}
} catch (Exception e) {
e.getMessage();
}
switch (i) {
case 2:
ioConnect();
break;
case 3:
break;
case 4:
ioConnect();
break;
case 5:
ioConnect();
break;
case 6:
ioConnect();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void ioConnect() {
try {
ServerSocket ss = new ServerSocket(2000);
Socket so = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the message");
String str = br.readLine();
PrintStream ps = new PrintStream(so.getOutputStream());
ps.println(str);
} catch (Exception e) {
e.getMessage();
}
}
}
class serverm {
public static void main(String s[]) {
servern obj = new servern();
obj.check();
}
}
So here I get the output the first row each column values that's fine, but when the control enters the for loop the println statement prints the hello only once and the cursor blinks. This indicates the the program has not ended correctly.
Your first problem is that you don't know what your problem is...
To solve this problem, and get to solve the real issue, instead of this
catch(Exception e)
{
e.getMessage();
}
Use
catch(Exception e)
{
e.printStackTrace();
}
And please paste the full stack trace this produces...
EDIT
As OP stated in a comment:
there is no data found exception thrown
This means that there is no data to be read. Which is a known case for MS Access:
This typically occurs when you try to read the value of a column multiple times.
So you should only read every value once! To fix the imediate issue, comment the System.out.println() line here
...
rs.next();
// comment this:
// System.out.println(rs.getInt(1) + "\t" + rs.getInt(2) + "\t" + rs.getInt(3) + "\t" + rs.getInt(4) + "\t" + rs.getInt(5) + "\t" + rs.getInt(6));
for (i = 2; i < 7; i++)
...
And be careful, as you call getInt() for the same index two times in the loop, which has to be corrected:
for (i = 2; i < 7; i++)
{
System.out.println("hello");
if (rs.getInt(i) < min) { // getInt()
index = i;
min = rs.getInt(i); // second getInt() call for same index --- throws exception
}
}
Correct:
for (i = 2; i < 7; i++)
{
System.out.println("hello");
int value=rs.getInt(i); // getInt() call, put into local variable
if (value < min) {
index = i;
min = value; //just use local variable - OK
}
}
It is a small mistake that you have done. Irrespective of whether the result has record or not, you are calling rs.getInt(1)... . Use classical JDBC way of testing whether result set has records or not.
while(rs.next()){
rs.getInt(1);
}

Categories