how to solve java.lang.NullPointerException for array assignment - java

I am trying to assign a variable from SQL result to array element but it keeps showing me java.lang.NullPointerException. I tried to declare the array above but it seems not working. The exception doesn't show the line of the error but I write print statements to figure out the exception place then I found out that when I print the value of the activity[i] it equals null.
Here is the code:
package main;
import java.awt.EventQueue;
public class ACTIVITY {
private Connection con;
private Statement stm;
private String sql;
private ResultSet rs;
private static int c_id=-1;
private static int s_id=-1;
private int a_id=-1;
private String activity[]=new String[5];
private int activityID[] =new int[5];
public static JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ACTIVITY window = new ACTIVITY();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ACTIVITY() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
panel.setVisible(true);
try {
Class.forName("com.mysql.jdbc.Driver");
con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","****" , "********");
stm= con.createStatement();
sql="Select * from activity where sid="+s_id;
rs=rs=stm.executeQuery(sql);
String name=" ";int i=0;
while(rs.next()){
name=rs.getString("a_name");
a_id=rs.getInt("a_id");
activity[i]=name;//after this assignment it always equal null
activityID[i]=a_id;
i++;
}
//the rest of the code
con.close();
} catch(Exception e) {System.out.println(e); }
}
}

Personally, I'd suggest using ArrayList instead of an array for this, but that's just personal preference. Here's an article on that https://www.w3schools.com/java/java_arraylist.asp
As far as the issue as you have it, the problem is you have a declared a private string array and are trying to assign values to it in another method. The array is populating with default values of null since it's a String array. The reason you're getting the exception is because it's returning this default value rather than your assigned value.
You can still use a private array, but you'll want to declare it as static and use a static method to add a value to it. That way, when you add the value to it, it'll be returnable the way you expect. This is a much simpler example, but shows how to achieve this:
public class Test {
private static String activity[] = new String[5];
public void addValue() {
activity[0] = "Yo";
}
public static void main(String[] args) {
Test test = new Test();
test.addValue();
System.out.println(activity[0]);
}
}
As for your specific code, I would suggest declaring both activity[] and activityID[] as static arrays. Then, you will need to create an object in your main method to call your value. Your changes would look like this:
private static String activity[] = new String[5];
private int activityID[] =new int[5];
Then in your main method, add:
window.initialize(); //where window is your class object you declared
That will get you the result you want. I'd also suggest renaming your method you called the same thing as your class.

Related

is there a way in java to, while a method is running, detect an integer change and run said method, then return to the same spot

I am currently creating a text adventure game and am displaying the player stats through the Jtable. I want to use the Jtable repaint method in order to make it display the stats as they change however I don't want to have to write the repaint method after every time I change it. How could I run the repaint() method whenever a stat changes and then continue with the rest of the code.
Here is the script running the Table that the repaint listener must be added:
import javax.swing.*;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
public class mainSystem extends JFrame{
public static class Stats{
public static int x = 1;
public static int n = 0;
public static ArrayList<String> contacts = new ArrayList<>(n);
public static int karma;
public static int SPC;
public static int OPC;
public static int wisdom;
public static int billsProposed;
public static int billsPassed;
public static String party;
public static String currentBill;
}
public static JTable statsWindow;
public mainSystem() {
String[] columns = new String[] {"Stat", "Value"};
Object[][] data = new Object[][]{{"Karma", Stats.karma}, {"SPC", Stats.SPC}, {"OPC", Stats.OPC}, {"Wisdom", Stats.wisdom}, {"Bills Proposed", Stats.billsProposed}, {"Bills Passed", Stats.billsPassed}, {"Party", Stats.party}};
statsWindow = new JTable(data, columns);
this.add(new JScrollPane(statsWindow));
this.setTitle("Stat Window");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void addToContacts(String name){
Stats.n = Stats.n + 1;
Stats.contacts.add(name);
}
public static void table(){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new mainSystem();
}
});
}
public static void main(String[] args) throws InterruptedException {
while (Stats.x == 1){
int karmaChange = Stats.karma; int SPCChange = Stats.SPC; int OPCChange = Stats.OPC; int wisdomChange = Stats.wisdom; int billsProposedChanged = Stats.billsProposed; int billsPassedChanged = Stats.billsPassed;
intro.Introduction();
Section1.section1();
break;
}
if (Stats.x != 1){
End.loose();
} else{
End.win();
}
}
}
What you are looking for is the observer pattern, and it is not automatic:
You must create a listener interface (see for example ActionListener or MouseListener) with a method to be called when the int property change (hint: you may use PropertyChangeListener).
You must be able to register listener to your observable object. You may look at addXXXListener from any JComponent object (for example: addPropertyChangeListener or DefaultListModel). Registering is basically adding listener to a list of listener to "warn".
When you change the int value, you have to fire the event, cycling through the listeners bounds to your object. You can read the code of DefaultListModel for an example.
As for your question title:
Is there a way in java to, while a method is running, detect an
integer change and run said method, then return to the same spot
Unless you are running in several thread, if all you are doing is done on the same thread, then you will return to the same spot. Then again, you are using Swing, and you have the main thread and the EventDispatchThread (EDT): you may need to use SwingUtilities.invokeAndWait (if you are not on the EDT) to return to the same spot.

How to bring SQL Variable into GUI?

I would like to insert in my GUI the variable anzahl from the minor class in a text field. Counting works in the minor class, but I do not know how I now get the counted value in the GUI? In the GUI, I just want to see the value from the minor class. Can someone help me with the code examples?
Minor Class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JLabel;
import java.sql.DriverManager;
public class Count {
static Connection conn;
static Statement eintrag;
static Statement eintrag2;
static JLabel textPB1;
static String ausgabe;
public static String anzahl;
Statement abfrage;
int i;
ResultSet res;
private int num;
Count() {
try {
Class.forName("org.mariadb.jdbc.Driver");
Connection con = java.sql.DriverManager.getConnection("jdbc:mariadb://fm-s012mp.fhws.de","Java","xyc");
Statement s = con.createStatement();
ResultSet res;
res = s.executeQuery("SELECT COUNT (*) AS anzahl FROM `lagersystem_test`.`00_hauptdatenbank` WHERE Boxinhalt > '0'" );
while (res.next() ) {
System.out.print(res.getString("anzahl") );
GUI_Lager.setTextExternally(res.getString("anzahl"));
}
res.close();
s.close();
con.close();
}
catch (Exception e) { System.out.println(""+e.getMessage());}
}
}
GUI: (short Form)
public class GUI_Lager extends JFrame {
private static final long serialVersionUID = 1L;
JLabel textPB; // "Text Prozessbar
static JLabel textPB1;
(....)
public GUI_Lager() {
textPB1 = new JLabel(""); // Variable from the Class
textPB1.setBounds(200, 10, 400, 25);
textPB1.setVisible(true);
add(textPB1);
(....)
}
public static void setTextExternally(String text) {
textPB1.setText(text);
// TODO Auto-generated method stub
}
}
}
To update a JLabel, you would use:
yourLabel.setText("your text");
So in context with the code provided in your question (assuming it is working without issue), you would do this:
while (res.next() == true) {
//System.out.print(res.getString("anzahl") );
//This "anzahl" i want to have in my GUI
textPB1.setText(res.getString("anzahl")); //Now you should have the label set
}
If for some reason the JLabel does not like being changed that way in a loop, you could also just instantiate a new object reference like so:
textPB1 = new JLabel(res.getString("anzahl"));
Update 1:
If you need to set the value from a different class simply create a method in the class with textPB1, which you will call from the class you are grabbing the DB value from, like so:
public static void setTextExternally(String text){
textPB1.setText(text);
//or
textPB1 = new JLabel(text);
}
Then in your loop from before, do this:
while (res.next() == true) {
//label should be set in other class using setter method below
MainGUI.setTextExternally(res.getString("anzahl"));
}
Update 2:
This update shows a specific example of a Swing application being used with the methods I have already provided, with a few changes now that I see your base GUI code. I would suggest building off from these files if you need a direct example to work up from:
Your GUI_Lager class:
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GUI_Lager extends JFrame {
private static final long serialVersionUID = 1L;
JLabel textPB1;
public GUI_Lager() {
//no need for constructor, so it can be null
}
public void showGUI() {
//let's make the GUI here
this.setSize(300, 300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
//-----------------your code
//let's give it dummy text at first to ensure we can change it
textPB1 = new JLabel("Dummy Text");
textPB1.setBounds(200, 10, 400, 25);
textPB1.setVisible(true);
add(textPB1);
//-----------------your code
}
public void setTextExternally(String text) {
//alters the text of class variable/label textPB1
textPB1.setText(text);
}
}
And then the Count class:
import java.util.Scanner;
public class Count {
public static void main(String[] args) {
GUI_Lager gui = new GUI_Lager();
gui.showGUI(); //you must show the GUI first
//now we change the value, it will be done using your SQL selection from before
gui.setTextExternally("Awesome, it works!");
//launch Count.java and the Swing application will have a
// single label that says "Awesome, it works!"
//...change your data as needed based on your specific implementation
//but let's also show how to change it using console input
Scanner scan = new Scanner(System.in);
System.out.println("What do you want to change the text label to?");
String text = scan.nextLine().trim();
gui.setTextExternally(text);
}
}

My method to load the html from a url in a web browser does not work

I am trying to make a web browser for the fun of it, i seem to get errors when ever i put in my loadHtml method, when i comment that out everything works even the action listener.
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.applet.*;
public class browserPannel extends JFrame{
public static void main(String[] arg) {
JFrame browser = new JFrame("A Nun In A Weelchair");
browser.setSize(1000,700);
browser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
browser.setLocationRelativeTo(null);
JPanel header = new JPanel();
header.setBackground(Color.lightGray);
JTextField url = new JTextField(20);
url.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
//loadHtml(event.getActionCommand);
System.out.println("action performed");
}
}
);
url.setSize(890,30);
url.setVisible(true);
JButton send = new JButton("Send");
send.setSize(75,30);
send.setVisible(true);
JEditorPane htmlc = new JEditorPane();
htmlc.setBackground(Color.red);
htmlc.setEditable(true);
htmlc.setContentType("text/html");
header.add(url, BorderLayout.SOUTH);
header.add(send);
browser.getContentPane().add(header, BorderLayout.NORTH);
browser.getContentPane().add(new JScrollPane(htmlc));
browser.pack();
browser.setVisible(true);
}
private void loadHtml(String link)
{
try{
//htmlc.setPage(link);
//url.setText(link);
}catch(Exception e){
System.out.println("ops sorry could not fined Virgine Mobile");
}
}
}
from what i can tell it looks like it can not recognize the url and the htmlc
I have tried to comment the htmlc.setPage and the url.setText, and when i do that my program compiles.
why am i getting these errors, shouldn't it recognize that they are defined above?
Your method isn't static but you're trying to call it from a static context (main()) Also, your instances in the main() method aren't visible in the loadHtml() method. You could pass them into the method (or declare them as static fields in your class). Finally, you shouldn't swallow Exception (at least printStackTrace()). So I think you were looking for something like,
private static void loadHtml(JEditorPane htmlc, JTextField url, String link) {
try{
htmlc.setPage(link);
url.setText(link);
}catch(Exception e){
System.out.println("ops sorry could not find Virgin Mobile");
e.printStackTrace();
}
}
Also, loadHtml(event.getActionCommand); isn't correct. You'd need parenthesis to call your original method loadHtml(event.getActionCommand());, but with the above changes it would be loadHtml(htmlc, url, event.getActionCommand()); (and to use the htmlc and url references in your inner class you must declare those references as final. For example, final JTextField url = new JTextField(20);).
Alternatively, you could make the components static so they're shared across all instances (and methods - first comment them out in your main method) -
private static final JTextField url = new JTextField(20);
private static final JEditorPane htmlc = new JEditorPane();
private static void loadHtml(String link) {
try{
htmlc.setPage(link);
url.setText(link);
}catch(Exception e){
System.out.println("ops sorry could not find Virgin Mobile");
e.printStackTrace();
}
}
Then you should be able to use loadHtml(event.getActionCommand())

JComponent name cannot be resolved, when used in another method

I'm following a youtube tutorial (http://www.youtube.com/watch?v=wpbQ0DCFF0M) to populate a JCombobox called "comboAccountName" with a database table.
My database connection is setup in another class.
The code is as follows -
public class Execute extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
//---------------------------------------------------------------------------------------------------------------------
public Execute()
{
.............other code...............
JComboBox comboAccountName = new JComboBox();
comboAccountName.setBounds(313, 31, 302, 20);
getContentPane().add(comboAccountName);
.............other code...............
}
void PopulateJCB()
{
String queryString = "SELECT DISTINCT [Account Name] FROM main ORDER BY [Account Name]";
try
{
Connection statJCBaccountname = DatabaseConnection.ConnectDB();
Statement stmt = statJCBaccountname.createStatement();
ResultSet rsJCBaccountname = stmt.executeQuery(queryString);
while (rsJCBaccountname.next())
{
comboAccountName.addItem(rsJCBaccountname.getString(1));
System.out.println(rsJCBaccountname.getString(1));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Execute frame1 = new Execute();
frame1.setVisible(true);
PopulateJCB();
}
There are 2 errors where I'd like your help
comboAccountName cannot be
resolved
occurs inside the while loop, at following line
comboAccountName.addItem(rsJCBaccountname.getString(1));
AND
Cannot make a static reference to the non-static method PopulateJCB() from the type
Execute
occurs when I'm trying to call PopulateJCB(); in the main method
I know the code in the tutorial video isn't exactly the same, but I'm trying to do a similar thing here. Please help.
Scope! You declare your comboAccountName inside of the constructor and so it is visible only inside of the constructor. Try to use it elsewhere and it fails. Solution: declare it outside of the constructor on the class level.
So not:
public class Execute extends JFrame {
public Execute()
{
JComboBox comboAccountName = new JComboBox(); // this guy is visible only in here
comboAccountName.setBounds(313, 31, 302, 20); // don't do this!
getContentPane().add(comboAccountName);
}
but rather:
public class Execute extends JFrame {
private JComboBox comboAccountName = new JComboBox();
public Execute()
{
comboAccountName.setBounds(313, 31, 302, 20);
getContentPane().add(comboAccountName);
}
Next we'll talk about your use of null layouts, setBounds(...) and absolute positioning. While to a newbie this seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.
As for this error:
Cannot make a static reference to the non-static method PopulateJCB() from the type
You must create an instance of the class and call the method on the instance, not on the class itself.
So not:
public static void main(String[] args) {
// TODO Auto-generated method stub // please clean your code of this before posting here
Execute frame1 = new Execute();
frame1.setVisible(true);
PopulateJCB();
but:
public static void main(String[] args) {
Execute frame1 = new Execute();
frame1.setVisible(true);
frame1.PopulateJCB(); // call it on the Execute instance, frame1

Java: Filling a JComboBox with objects

I'm trying to fill a jComboBox with objects. I have it working in one class, but in this class it's giving a NullPointerException but the code is almost the same. What am I missing here?
The code I'm using to fill the comboboxes:
I have translated every variable to English and removed some unnescessary stuff. I hope it's more clear for you guys now:
package unive.billing.boundary.clientmanager.frames;
import unive.billing.control.ClientsManager;
import unive.billing.control.InsuranceManager;
/**
*
* #author Forza
*/
public class ClientFrame extends javax.swing.JFrame {
/**
* Creates new form AddClientGUI
*/
private ClientsManager clientmanager;
private InsuranceManager insurancemanager;
public ClientFrame() {
initComponents();
clientmanager = new ClientsManager();
clientmanager.printList();
updateComboBoxCompany();
updateComboBoxInsurance();
}
private ClientsManager clientmanager;
private InsuranceManager insurancemanager;
public ClientFrame() {
initComponents();
clientmanager = new ClientsManager();
clientmanager.printList();
updateComboBoxCompany();
updateComboBoxInsurance();
}
public void updateComboBoxCompany()
{
for (Object object : insurancemanager.getCompanyNames())
{
companyComboBox.addItem(object);
}
}
public void updateComboBoxInsurance()
{
for (Object object : insurancemanager.getPolicyNames())
{
insuranceComboBox.addItem(object);
}
}
Here are the methods used:
public Object[] getCompanyNames()
{
ArrayList<String> cnames = new ArrayList<String>();
for (InsurancesCompany company : insurancecompanyList)
{
cnames.add(company.getCompanyName());
}
return cnames.toArray();
}
public Object[] getPolicyNames()
{
ArrayList<String> vnames = new ArrayList<String>();
for (Insurance insurance : insuranceList)
{
vnames.add(insurance.getPolicyName());
}
return vnames.toArray();
}
This is how my lists are initialized:
public class InsuranceManager {
private String insurancePath;
private String insurancecompanyenPath;
private static List<InsurancesCompany> insurancecompanyList;
private static List<Insurance> insuranceList;
private Insurance currentInsurance;
public InsuranceManager() {
insurancecompanyenPath = "Files/company.txt";
insurancePath = "Files/insurance.txt";
insuranceList = new List<>();
}
public void createNewList()
{
insurancecompanyList = new List<>();
System.out.println("Creates list");
}
public Object[] getCompanyNames()
{
ArrayList<String> cnames = new ArrayList<String>();
for (InsurancesCompany company : insurancecompanyList)
{
cnames.add(company.getCompanyName());
}
return cnames.toArray();
}
public Object[] getPolicyNames()
{
ArrayList<String> vnames = new ArrayList<String>();
for (Insurance insurance : insuranceList)
{
vnames.add(insurance.getPolicyName());
}
return vnames.toArray();
}
Edit: Here's the MainGUI which calls createNewList (maakLijstAan)
private ClientsManager clientsmanager;
private BillingManager billingmanager;
private InsuranceManager insurancemanager;
public MainGUI() {
clientsmanager = new ClientsManager();
clientsmanager.CreateNewList();
insurancemanager = new InsuranceManager();
insurancemanager.CreateNewList();
insurancemanager.loadInsuranceCompanyList();
initComponents();
jMenuItem1.setText("Save clients");
jMenuItem2.setText("Load clients");
jMenuItem3.setText("Exit");
}
You never initialize verzekeringBeheer, therefore you get a NullPointerException when you try to invoke methods on that variable.
You should have somewhere in your constructor, something like this:
verzekeringbeheer = new VerzekeringBeheer();
Also, try to avoid making your code coupled with other parts of your code. For example:
public VerzekeringBeheer() {
...
//verzekeringmaatschappijLijst is never initialized!!!
}
public void maakLijstAan()
{
verzekeringmaatschappijLijst = new Lijst<>();
System.out.println("Maak lijst aan");
}
public Object[] getMaatschappijNamen()
{
ArrayList<String> mnamen = new ArrayList<String>();
// Here you use verzekeringmaatschappijLijst without checking that is not null!!!
for (VerzekeringsMaatschappij maatschappij : verzekeringmaatschappijLijst)
{
mnamen.add(maatschappij.getMaatschappijNaam());
}
return mnamen.toArray();
}
If nobody calls maakLijstAan, you will get a NullPointerException in getMaatschappijNamen. Try to avoid code that is so dependent of external code, in order to run without problems.
all data for JComboBox are stored in ComboBoxModel
set ComboBoxModel for proper Objects type (String, Integer, Icon or simple Object), Java7 implements Generics, there are significant differiences in compare with Java6
all updates (to the JComboBox or its Model) must be done on Event Dispatch Thread
I only see you useing variables but for me they are nit initialized. So they are null and you get a NPE.
So how are verzekeringmaatschappijLijst and verzekeringLijst initialized?

Categories