I am a beginner in Java Programming. I try to practice with working on a Java application and i need to create a different database each time i register a new client.  (Please see attached, the picture of my client window)   Thank you in advance for any review or valuable answer !   Connecter.java   import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement;    public class Connecter { Connection con;  public Connecter(String db) {     try {         Class.forName("com.mysql.jdbc.Driver");      } catch (ClassNotFoundException e) {         System.err.println(e);         // pour afficher 1 ere erreur     }     try {          con = DriverManager.getConnection("jdbc:mysql://localhost:8889/", "root", "root");      } catch (SQLException e) {         System.err.println(e);     }  }  Connection obtenirconnexion() {     return con;  }  public Connection getCon() {     return con; }  public void setCon(Connection con) {     this.con = con; }  }   Client.java   import java.awt.BorderLayout;  public class Client extends JFrame {  Connection conn; protected String Cl; private JPanel contentPane; private JTextField txtCl; Connecter Cot = new Connecter(Cl); java.sql.Statement stm; int Rs;  /**  * Launch the application.  */ public static void main(String[] args) {     EventQueue.invokeLater(new Runnable() {          public void run() {             try {                 Client frame = new Client();                 frame.setVisible(true);             } catch (Exception e) {                 e.printStackTrace();             }         }     }); }  /**  * Create the frame.  */ public Client() {     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     setBounds(100, 100, 450, 300);     contentPane = new JPanel();     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));     setContentPane(contentPane);     contentPane.setLayout(null);      JLabel lblClient = new JLabel("Client ");     lblClient.setBounds(46, 99, 61, 16);     contentPane.add(lblClient);      txtCl = new JTextField();     txtCl.setBounds(157, 93, 134, 28);     contentPane.add(txtCl);     txtCl.setColumns(10);      JButton btnCreate = new JButton("Create");     btnCreate.addActionListener(new ActionListener() {         public void actionPerformed(ActionEvent e) {             String Client = txtCl.getText();             String requete = "Create database " + Client + "";             Cot.obtenirconnexion();             conn = Cot.obtenirconnexion();             try {                 stm.execute(requete);               System.out.println("" + Client + " is created");             } catch (SQLException e1) {                 // TODO Auto-generated catch block                 e1.printStackTrace();             }          }     });     btnCreate.setBounds(21, 180, 117, 29);     contentPane.add(btnCreate);  }  }
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
108487
I have the code below (I've included what I believe are all relevant sections):  private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ? AND VAL_@ = ?;"; public bool read(string id) {     level = -1;     MySqlCommand m = new MySqlCommand(readCommand);     m.Parameters.Add(new MySqlParameter("", val1));     m.Parameters.Add(new MySqlParameter("", val2));     MySqlDataReader r = m.ExecuteReader();     if (r.HasRows)         level = Convert.ToInt32(r.GetValue(0).ToString());     r.Close();     return true; }   When I run this, I get an IndexOutOfBoundsException on adding the first parameter. What have I done wrong?
58461
Consider the code:  PreparedStatement ps = null; ResultSet rs = null; try {   ps = conn.createStatement(myQueryString);   rs = ps.executeQuery();   // process the results... } catch (java.sql.SQLException e) {   log.error("an error!", e);   throw new MyAppException("I'm sorry. Your query did not work."); } finally {   ps.close();   rs.close(); }   The above does not compile, because both PreparedStatement.close() and ResultSet.close() throw a java.sql.SQLException.  So do I add a try/catch block to the finally clause?  Or move the close statements into the try clause?  Or just not bother calling close?
96022
I had the following exception thrown at me when trying to process more than one selected records via a custom button in the list view.    Class Code  global class MerchandiseInventoryClass {      webservice static void ConverttoInventory(String[] merchandise_id)    {        //Convert Merchandise collection into Inventory Collection...         Merchandise__c[] merchandise_collection = [SELECT ID,Author__c,Book_Title__c,Edition__c,Publisher__c,Total_Merchandise_QtyTotal_Qty__c,Status__c FROM Merchandise__c WHERE ID = :merchandise_id];          Inventory__c i = new Inventory__c(); //Line 1        List&lt;Inventory__c&gt; newInventory = new List&lt;Inventory__c&gt;();        for(Merchandise__c m : merchandise_collection )        {            if(m.Status__c !='Fully Converted')            {            i.Author__c = m.Author__c ;            i.Book_Title__c = m.Book_Title__c;            i.Edition__c = m.Edition__c;            i.Publisher__c = m.Publisher__c;            i.Qty_Available__c = m.Total_Merchandise_QtyTotal_Qty__c;            i.Merchandise__c = m.Id;            m.Uninventoried_Qty__c = 0;            m.Status__c = 'Fully Converted';            newInventory.add(i);            }        }        insert newInventory;        update merchandise_collection;    }  }   By moving the Line 1 to within the for loop solved the issue for me.  Thanks to this post (refer the Best Answer in that post)    What puzzles me is that WHY i have to instantiate "i" for every iteration within the loop.  Why the list collection ("newInventory") is complaining that are duplicate elements and why should it even confuse in the first place when I am performing an "insert" even ?
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
84342
I have a JFrame. This JFrame contains a JButton. I click the JButton and 10 JTextFields are created.  the problem: I cannot see them until "I force a repaint()" by resizing the window. Only then do I see the JTextFields created.  CODE:  JPanel points = new JPanel();  //Creating the JTextFields: for (int i=0; i&lt;10; i++) {     JTextField textField = new JTextField();     points.add(textField); }  repaint(); this.repaint(); super.repaint(); points.repaint();     THANK YOU - after the for loop, I just called points.validate() and it worked...
29674
Why do we need an init() method in servlet? Can't we use the constructor to initialization?
68403
I have this controller but I am getting this error      System.QueryException: List has no rows for assignment to SObject   public class MyController {     private final Account account;      public MyController() {         account = [SELECT Id, Name, Site FROM Account                     WHERE Id = :ApexPages.currentPage().getParameters().get('id')];             }      public Account getAccount() {         return account;     }      public PageReference save() {         update account;         return null;     } }
99002
I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:  conn = sqlite3.connect("mydatabase.db")    If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it. If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.   Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?
18034
when i try to save the following code, i got the error below. Following same instructions given in this link, but still errors. Am i doing anything wrong here? please suggest.    @isTest private class WebSvcCalloutTest {     @isTest static void testEchoString() {         Account a = new Account(name='Tester',SAP_KUNNR__c='1172');         insert a;                       // This causes a fake response to be generated         Test.setMock(WebServiceMock.class, new WebServiceMockImpl());      } }   Error:  Save error: Method does not exist or incorrect signature: Test.setMock(Type, WebServiceMockImpl)    WebSvcCalloutTest.cls         @isTest global class WebServiceMockImpl implements WebServiceMock {    global void doInvoke(            Object stub,            Object request,            Map&lt;String, Object&gt; response,            String endpoint,            String soapAction,            String requestName,            String responseNS,            String responseName,            String responseType) {          sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00 sap1 = new sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00();                Map&lt;String,String&gt; mapSAP = new Map&lt;String,String&gt; {};         sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01 req = new sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01();               sapComDocumentSapSoapFunctionsMcS.ZGssmwfmHndlEvntrqst00Response_element ret =  sap1.ZGssmwfmHndlEvntrqst00('',req);         response.put('response_x', ret);     } }
57295
I have a Trigger that is referencing a class. It works in Dev, but now I am trying to create the test class in order to push it to production. I am trying to test that a new user is created. I keep getting the same error System.QueryException: List has no rows for assignment to SObject. The error seems to point to the class on line 9 where the Account is added. The goal of the code is when a new user is inserted, then a contact for that new user is created as well. Does someone have any ideas why this is happening? I've used the Query Editor to make sure that the record does exist, and it does, so I'm stumped. Thanks in advance for the help.   Trigger      trigger UserInsertContactInsert1 on User (after insert, after update) {      if(Trigger.isAfter &amp;&amp; Trigger.isInsert){         Set&lt;ID&gt; usrIds = new Set&lt;ID&gt;();          for(User u : Trigger.new){             usrIds.add(u.id);         }          UserContactSyncClass1.syncContact(usrIds);       }      if(Trigger.isAfter &amp;&amp; Trigger.isUpdate){          Set&lt;ID&gt; idSet = new Set&lt;ID&gt;();         Set&lt;ID&gt; idSet2 = new Set&lt;ID&gt;();          for(User u : trigger.new){             for(User r : trigger.old){                 if(u.ID == r.ID &amp;&amp; u.isActive==false &amp;&amp; r.isActive==true){                     idSet.add(u.ID);                 }                  if (u.ID == r.ID &amp;&amp; u.isActive==true &amp;&amp; r.isActive==false) {                     idSet2.add(u.ID);                 }              }         }          UserContactSyncClass1.InactiveContact(idSet);         UserContactSyncClass1.ActivateContact(idSet2);     } }   Class  public class UserContactSyncClass1 {      @future     public static void syncContact(Set&lt;Id&gt; userSet){         List&lt;Contact&gt; cList = new List&lt;Contact&gt;();         List&lt;User&gt; userList = [Select ID, FirstName, LastName, Email, Phone, True_Market_Unit__c, True_Market_Name__c FROM User WHERE ID IN :userSet];         List&lt;String&gt; mList = new List&lt;String&gt;();         List&lt;String&gt; mktList = new List&lt;String&gt;();         **Account acc = [SELECT Id, Name FROM Account WHERE Name = 'Company Users' Limit 1];**          // Loop through Users, to get List of True Market Number         for(User usr : userList){             mList.add(usr.True_Market_Unit__c);                 }          // Use the True Market Number and Match to the True Market Number in Markets         for(Market__c mkt : [SELECT Name, Unit_Number__c FROM Market__c WHERE Unit_Number__c IN :mList]){             mktList.add(mkt.Name);           }          for(User usr : userList){             for(String mk : mktList){                 usr.True_Market_Name__c = mk;             }             System.debug(usr.True_Market_Name__c);         }          for(User u : userList){             cList.add(new Contact(FirstName=u.FirstName, LastName=u.LastName, User_True_Market_Name__c=u.True_Market_Name__c, Email=u.Email, Phone=u.Phone, OwnerID=u.ID, Related_User__c=u.Id, AccountId = acc.Id));         }          upsert cList;     }   Test Class Method with the Error  public static testMethod void validateNewUser(){          Profile p = [SELECT id FROM Profile WHERE Name='System Administrator'];          User u = new User(             FirstName = 'test',              LastName= 'last_test',              Email='test323232@test.com',              Phone='111-111-1111',              True_Market_Unit__c='1111',              alias = 'test',              EmailEncodingKey='UTF-8',             ProfileId = p.Id,             LanguageLocaleKey='en_US',             LocaleSidKey='en_US',              TimeZoneSidKey='America/Los_Angeles',             UserName = 'test323232@test.com'          );          System.runAs(u){             System.assertEquals('111-111-1111', u.Phone);         }      }   Updated Solution  Turns out even though my User never referenced the account, I still needed to insert it into my test class, with the Name='Company Users' from my SOQL query. Thanks everyone for all the help.
36484
I'm trying to implement a KeyListener for my JFrame. On the constructor, I'm using this code:  System.out.println("test"); addKeyListener(new KeyListener() {     public void keyPressed(KeyEvent e) { System.out.println( "tester"); }      public void keyReleased(KeyEvent e) { System.out.println("2test2"); }      public void keyTyped(KeyEvent e) { System.out.println("3test3"); } });   When I run it, the test message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the KeyListener was not even there.  I was thinking that it could be because the focus is not on the JFrame and so they KeyListener doesn't receive any events.  But, I'm pretty sure it is.  Is there something that I am missing?
105631
Please consider the below scenario:   I have an Application__c object. I have a trigger on that (for simplicity, coded directly in trigger) which does one thing if the record name is Error then throws exception.     trigger ApplicationTrigger on Application__c (before insert, after update){          if(trigger.new[0].Name == 'Error'){             Application__c application;             System.debug(application.Name);         } }    Now I am running below code:     Now notice the catch statement is not executing, means system was not able to catch the exception. It came as the Fatal Error.   This is kind of a big issue where if there is null pointer or any other exception in trigger and exception handling code will not be able to do anything. Not even logging since it never reaches to catch block.   Let me know if you guys ever faced such situation and if yes what you did to make sure that it is properly caught.
5609
I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.    The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.    What is the best "drop in" solution to switch this over to using connection pooling in python?  I am imagining something like the commons DBCP solution for Java.    The process is long running and has many threads that need to make requests, but not all at the same time... specifically they do quite a lot of work before brief bursts of writing out a chunk of their results.  Edited to add: After some more searching I found  which looks decent, but as I'm relatively new to python I guess I just want to make sure I'm not missing a more obvious/more idiomatic/better solution.
104558
I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs. So, I'm trying to see if instead of doing something like this:  ProcessDirector = ProcessDirector() ID12345 = ID12345() ID01234 = ID01234()  ProcessDirector.construct(ID12345) ProcessDirector.construct(ID01234)  ID12345.run() ID01234.run()   Can I do something like this (I know this doesn't work):  IDS = ["ID12345", "ID01234"]  ProcessDirector = ProcessDirector() for id in IDS:   builder = id() #some how instantiate class from string   ProcessDirector.construct(builder)   builder.run()   That way, when I need to add a new one in the future, all I have to do is add the id to the IDS list, rather than peppering the new ID throughout the code.   EDIT  Looks like there are some different opinions based on where the data is coming from. These IDs are entered in a file that no one else has access to. I'm not reading the strings from the command line, and I'd like to be able to do as little alteration when adding a new ID in the future.
112290
This code throws a NullReferenceException when it calls ExecuteScalar:  selectedPassengerID = 0;  //SqlCommand command = GenericDataAccess.CreateCommand();   // 2nd test string connectionString = ""; SqlConnection conn;  connectionString = ConfigurationManager.     ConnectionStrings["ConnST-MHM"].ConnectionString; conn = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(); command.CommandType = CommandType.StoredProcedure ; command.Connection = conn; command.CommandText = "SearchForPassenger";  SqlParameter param;  param = command.CreateParameter(); param.ParameterName = "@name"; param.Value = pName; // Session[""]; param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@flightDate"; param.Value = date;  param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@ticketNo"; param.Value = ticketNumber;  param.DbType = DbType.Int32; command.Parameters.Add(param);  int item;  command.Connection.Open(); item = (int)command.ExecuteScalar();
92671
public class ExampleClass {       public static void publishCaseUpdateNotifications(List&lt;Case&gt; cases) {     List&lt;Case_Updated__e&gt; notifications = new List&lt;Case_Updated__e&gt;();     for (Case c: cases) {         notifications.add(new Case_Updated__e(             Case__c = (String)c.Id,             CreatedByName__c = UserInfo.getName(),             CaseNumber__c = c.CaseNumber         ));     }       List&lt;Database.SaveResult&gt; results = EventBus.publish(notifications);      for (Database.SaveResult result : results) {         if (!result.isSuccess()) {             for (Database.Error error : result.getErrors()) {                 System.debug('Error returned: ' +                     error.getStatusCode() +' - '+                     error.getMessage());             }         }       }      }    }   My Test Class: getting error   @isTest   public class ExampleTestClass {    @isTest   static void testClassforExample(){         Case testcase = new Case(Subject ='Test',);      list&lt;Case_Updated__e&gt; caseUpdate =      ExampleClass.publishCaseUpdateNotifications(testcase );       }      }   My Error is Method does not exist or incorrect signature: void publishCaseUpdateNotifications(Case) from the type ExampleTestClass   Please suggest me how to resolve this error.     trigger Cases on Case (after insert) { if(Trigger.isAfter) {     System.debug('I will be replaced shortly!'); }  }   Do we need test class for above trigger. Please suggest me too