This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
my problem is easy normally but i just don't see where is the problem.
-i am declaring an array of a class as a global variable that i reuse in multiple functions inside this other class.
the class instantiated is:
public class Service {
int numticketsin;
String name="mi";
int[] perhour={0,0,0,0,0,0,0,0,0,0};
int moyenneticketperday;
int[] moyenneticketperdayperhour={0,0,0,0,0,0,0,0,0,0};
public Service(){}
}
global var:
Service[] services=new Service[10];
the function where i use try to fill the array:
public void getnamesofservices(){
int x=0;
Connection conn=db.java_db();
try {
Statement stmt = conn.createStatement();
String qry = "SELECT service_name from service ";
ResultSet rs = stmt.executeQuery(qry);
int i=0;
while (rs.next()) {
String namee=rs.getString("service_name");
System.out.println(namee);
services[i].name = namee;
i++;
}
conn.close();
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex);
}
}
the error:
''' Exception in thread "main" java.lang.NullPointerException: Cannot assign field "name" because "this.services[i]" is null
at com.mycompany.stats.NewJFrame.getnamesofservices(NewJFrame.java:195)
at com.mycompany.stats.NewJFrame.<init>(NewJFrame.java:122)
at com.mycompany.stats.Main.main(Main.java:16)'''
thank you in advance!!
Service[] services=new Service[10];
This means you created and array with 10 positions, but all those positions are empty (meaning they have null inside each and every position of the array).
So, when trying services[i].name you get the NullPointerException because services[i] is null.
There are plenty of ways to do the initialization, that depends on your business cases. But just to name two possibilities:
Initialize it at the declaration:
Service services[] = new Service[] {
new Service(),new Service(), new Service(), new Service(),new Service(),
new Service(),new Service(), new Service(), new Service(),new Service()
};
Or just before using it, in case you are not overriding it:
services[i] = new Service();
services[i].name = namee;
Related
I'm trying to use ResultSet.getArray() to grab an int[] array from my database. I'm using postgreSQL, DBeaver, and Java.
ResultSet rs = s.executeQuery(sql);
ArrayList<Theater> theaterList = new ArrayList<>();
while(rs.next()) {
Theater t = new Theater(
rs.getInt("theater_id"),
rs.getArray("theater_numbers"),
rs.getString("theater_loc")
);
theaterList.add(t);
return theaterList;
}
Error message: "The constructor Theater(int, Array, String) is undefined"
I keep getting flagged for not having a constructor of the appropriate type:
import java.sql.Array;
public Theater(int theater_id, Array theater_numbers, String theater_loc) {
super();
this.theater_id = theater_id;
this.theater_numbers = theater_numbers;
this.theater_loc = theater_loc;
Here's the beginning of the class:
public class Theater {
private int theater_id;
private Array theater_numbers;
private String theater_loc;
Not sure how to make the types agree with one another.
How do I make the types agree?
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have the below script where I get the id correctly but when I append it to the url I am getting as
java null pointer Exception.
Below is the method I used to store the ids:
public static HashMap<String, String> createdValue;
public static void getid(WebDriver driver) throws InterruptedException
{
String pendingconfirm = buttonXpath_Replace.replace("XXXX", "Pending confirm");
clickOnButton(driver, pendingconfirm);
createdValue = new HashMap<String, String>();
List<WebElement> tableValues = driver.findElements(By.xpath("//table//tr//td[contains(#class,'mat-column-demandId')]//span"));
int tableValueSize = tableValues.size();
System.out.println("Get the no of rows:"+tableValueSize);
WebElement latestId = driver.findElement(By.xpath("(//table//tr//td[contains(#class,'mat-column-demandId')]//span)["+tableValueSize +"]"));
System.out.println("Latest DemandIds: "+ latestId .getText());
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//table//tr//td[contains(#class,'mat-column-demandId')]//span)["+tableValueSize +"]")));
createdValue.put("latestDataId", latestId.getText());
System.out.println(createdValue.put("latestDataId", latestId.getText()));
}
Then I call the above method in order to append the latestId to the url:
String confirmationURL = "https://test-webapp.net/#/type=confirm";
List<String> newurls = new ArrayList<String>();
newurls.add(confirmationURL + "&id=" + createdValue.get("latestDataId"));
so in this case I fetch the id from the previous method by appending as above but when I do this it is not fetching the id and causes a null pointer Exception.
Any inputs on what I can do to get this resolved.
basically createdValue and getid both are static, so when you are calling it like this :
newurls.add(confirmationURL + "&id=" + createdValue.get("latestDataId"));
this is getting called :
public static HashMap<String, String> createdValue;
and since it does not have anything, you are getting the null pointer exception.
Also, I think if you call this :
getid first and then calling like this :
String confirmationURL = "https://test-webapp.net/#/type=confirm";
List<String> newurls = new ArrayList<String>();
getid(driver);
newurls.add(confirmationURL + "&id=" + createdValue.get("latestDataId"));
should help you by past this issue.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
So I have an issue. My RPC calls will fail due to "NullpointExeption". Meaning that one column contains null in value. This is done on purpose, as I am gonna fill this column with value at some time. How can I allow the Java code to ignore/ or allow this error to happen thru error handling??
#Override
public List <BreakRegistered> getAllRegisteredBreaks() throws IllegalArgumentException {
List<BreakRegistered> resultsfromquery = null;
ResultSet resultSet = null;
try {
//Execute query kaldes på resultsetter, fordi der kun nedhentes data
resultSet = getAllEmployeesBreaks.executeQuery();
resultsfromquery = new ArrayList<BreakRegistered>();
while (resultSet.next()) {
resultsfromquery.add(new BreakRegistered(
resultSet.getTimestamp("time").toString(),
resultSet.getTimestamp("checkedOut").toString(), //Error occurs HERE!
resultSet.getString("navn"),
resultSet.getInt("medarbejderID")));
}
} catch (SQLException sqlException) {
throw new IllegalArgumentException(" \"getBreaks\" fejlede");
} finally {
try {
resultSet.close();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
close();
}
}
return resultsfromquery;
}
The implication is that resultSet.getTimestamp("checkedOut") is returning null. You need to check for that before you try to deference the object to call toString().
A typical construct for this might be:
Object time = resultSet.getTimestamp("checkedOut"); //Or use a more specific type
String timeAsString;
if ( time != null)
timeAsString = time.toString();
else
timeAsString = null; // or empty string, or any other placeholder value you want
P.S. It looks like you are executing SQL queries. I would not call those "RPC calls".
You just need to check whether it is null. If you will use this query result later, It would be nice to put the logic into Object. Moreover, In this case, you just need to change the constructor if there will be some changes to your DB in the future.
public BreakRegistered(ResultSet resultSet) {
this.time = resultSet.getTimestamp("time") != null ? resultSet.getTimestamp("time").toString() : null;
this.checkedOut = resultSet.getTimestamp("checkedOut") != null ? resultSet.getTimestamp("checkedOut").toString() : null;
this.navn = resultSet.getString("navn");
this.medarbejderID = resultSet.getInt("medarbejderID")
}
i'm working with java in eclipse.I am trying to take 2 variables from my database and write it to an excel.My only problem is returning 2 different values(an integer and a string) from db reader method and send it to excel writer method which are in different classes.
Here is my db reader class:
public class DbConnection {
public void createConnection(String choice) {
try {
String myDriver = "com.mysql.jdbc.Driver";
String db = "jdbc:mysql://localhost/digiturkschema";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(db, "root",
"*****");
Statement st = conn.createStatement();
switch (choice) {
case "write":
ResultSet rs = st.executeQuery("SELECT * FROM channelstable");
while (rs.next()) {
int channelId = rs.getInt("channelNo");
String channelName = rs.getString("channelName");
}
}
} catch (Exception exception) {
System.out.print(exception.getStackTrace());
}
}
}
I need to return "channelId" and "channelName" from this method to this method:
public class WritingToExcel {
public void Write() throws IOException {
try {
JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showSaveDialog(null);
System.out.println(f.getCurrentDirectory());
System.out.println(f.getSelectedFile());
String direction = f.getSelectedFile().toString() + "\\DigiTurkKanalListesi.xls";
WritableWorkbook workbook = Workbook.createWorkbook(new File(direction));
WritableSheet sheet = workbook.createSheet("Kanal Listesi", 0);
Label label = new Label(0, 0, "A label record");
sheet.addCell(label);
Number number = new Number(2, 1, 3.1459);
sheet.addCell(number);
workbook.write();
workbook.close();
} catch (WriteException e) {
e.getStackTrace();
}
}}
I know that writingToExcel class is not completed and it's ok,i can finish it if i can take these two variables to this class.By the way i am using MVC pattern so i have a controller class between them.I can write it too if it's necessary.
As #Ascalonian said, you can use Map or HashMap.
for example:
Map<Integer, String> channelInfo = new HashMap<Integer, String>();
You can also (but should not):
Create a new class with the values you need and return that class. (You will be doing extra work which you don't really need to.)
Create setter methods for those variables and use it before calling the method to write to excel. (requires caution as you can end up with undesired values if you mess the code)
There are multiple options
ArrayList<Objects> : During Iterating the resultSet prepare temporary List say tempList insert items into tempList and then after each iteration add tempList to Main List , Since ArrayList is a sequential list. So, insertion and retrieval order is the same. So you can return this from your dbReader() method .Then use them wherever you want
Your Arraylist will look like this
[ [1,Channel 1] , [2,Channel 2] , [3,Channel 3] ]
Map if order is important prefer LinkedHashMap if order is not your primary concern then opt for HashMap
I'm working in a project with DB. There are a method that collect info from the DB and set the info in ArrayList:
public ArrayList<Director> listAll(){
ArrayList<Director>list = new ArrayList<Director>();
Director direc = new Director();
int cont=0;
String sql = "select * from director;";
try{
ResultSet res = objBBDD.sentencia.executeQuery(sql);
while(res.next()){
direc.setCode(res.getInt("CODE"));
direc.setName(res.getString("NAME"));
direc.setNationality(res.getString("NATIONALITY"));
direc.setOscar(res.getInt("OSCAR"));
list.add(direc);
// THIS IS USE TO CONFIRM IF IT WORKS ///////////////////////////////////////
// JOptionPane.showMessageDialog(null,"Code:"+list.get(cont).getCode()+"Nombre"+list.get(cont).getName());
// cont++;
}
}catch (SQLException e) {
e.printStackTrace();
}
return list;
}
I use JOptionPane.showMessageDialog to see if I get info from DB and is added correctly to de ArrayList, and it's works.
Now the ArrayList back the invoker class, this is the method:
private void stackArray(){
ArrayList<Director>arrayDir = new ArrayList<Director> ();
ArrayList<Director>arrayDir = conexion.listAll();
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(0).getCode()+"Name"+arrayDir.get(0).getName());
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(1).getCode()+"Name"+arrayDir.get(1).getName());
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(2).getCode()+"Name"+arrayDir.get(2).getName());
}
Again I use the JOptionPane.showMesageDialog to show the first three positions, but it's not work, the problem, as far as I've seen, is all the positions have the same object saved (exactly the last).
Summarizing the ArrayList have the same object (last in DB), there are no problems at run or compile.
I don't know if I write something bad, or just a noob fail.
the problem, as far as I've seen, is all the positions have the same
object saved (exactly the last).
You are changing value of same instance Director. Thats why, you seen the last value of Director object. You should create new instance of Director with iteration of while loop.
ResultSet res = objBBDD.sentencia.executeQuery(sql);
while(res.next){
Director direc = new Director();// Declare Director instance here.
.....
list.add(direc);
}