For example: If I create a list people and that list contains Name, Age, Height as the elements, then a Table of Name People will be created, having the columns Name, Age, Height  I tried this code...  static final String DATABASE_NAME="MyDatabase";     static final int DATABASE_VERSION = 1;     static String TABLE_NAME=null;     static String CREATE_TABLE = null;     static List&lt;String&gt; COLUMNS = null;     static String DROP_TABLE = null;      private Context context;      public DBHandler(Context context,String Table_Name,List&lt;String&gt; columns,){         super(context,DATABASE_NAME,null,DATABASE_VERSION);         this.context = context;         this.TABLE_NAME=Table_Name;         this.COLUMNS = columns;         CREATE_TABLE ="CREATE TABLE "+TABLE_NAME+"("+COLUMNS.get(0)+" INTEGER PRIMARY KEY, "+COLUMNS.get(1)+" TEXT,"+COLUMNS.get(2)+" TEXT,"+COLUMNS.get(3)+" TEXT,"+COLUMNS.get(4)+" TEXT)";         DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;     }     public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {         super(context, DATABASE_NAME, factory, DATABASE_VERSION);         this.context=context;     }      @Override     public void onCreate(SQLiteDatabase sqLiteDatabase) {         sqLiteDatabase.execSQL(CREATE_TABLE);     }
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?
79268
Here is my code `  global with sharing class ReportsListController {     public String dcarr { get; set; }    public static ReportsColumnMap__c repcols { get; set; }    public ReportsListController() { } // empty constructor    @RemoteAction   global static List&lt;ReportsColumnMap__c&gt; getRepCols(String dcarr) {             List&lt;ReportsColumnMap__c&gt; repcols =          [SELECT ColumnName__c,SObject__c ,COUNT(ID) FROM ReportsColumnMap__c WHERE ColumnName__c IN ('OWNER','FIRST_NAME','LAST_NAME','TITLE','COMPANY','LEAD_SOURCE','RATING','STREET','EMAIL') AND SObject__c !='null' GROUP BY SObject__c ,ColumnName__c];     return repcols;   } }   `
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.
19673
I am getting FATAL_ERROR|System.QueryException: List has no rows for assignment to SObject. I know that it is because it is not returning any rows in the SOQL query but what I want is that if it returns any row, it should update ALO field on contact object, if it is null then ALO field should be set to null.  Here is my code:  ziptoLOD = [SELECT Id, Name, LOD__c             FROM Zip_3_to_LOD__c             WHERE Name =: contact.Extract_Zipcode__c ];  Zip_3_to_LOD__c ziptoLOD2 = (ziptoLOD != null) ? ziptoLOD : null;  if (ziptoLOD2 == null) {     contact.ALO__c = ' ';    } else {     System.debug(System.LoggingLevel.ERROR, 'Zip to LOD' + ziptoLOD2);     contact.ALO__c = ziptoLOD2.LOD__c; }   My code gets stuck at the SOQL query and gives me the list has no rows error.
11719
I want to do something like this:  List&lt;Animal&gt; animals = new ArrayList&lt;Animal&gt;();  for( Class c: list_of_all_classes_available_to_my_app() )    if (c is Animal)       animals.add( new c() );   So, I want to look at all of the classes in my application's universe, and when I find one that descends from Animal, I want to create a new object of that type and add it to the list.  This allows me to add functionality without having to update a list of things.  I can avoid the following:  List&lt;Animal&gt; animals = new ArrayList&lt;Animal&gt;(); animals.add( new Dog() ); animals.add( new Cat() ); animals.add( new Donkey() ); ...   With the above approach, I can simply create a new class that extends Animal and it'll get picked up automatically.  UPDATE: 10/16/2008 9:00 a.m. Pacific Standard Time:  This question has generated a lot of great responses -- thank you.  From the responses and my research, I've found that what I really want to do is just not possible under Java.  There are approaches, such as ddimitrov's ServiceLoader mechanism that can work -- but they are very heavy for what I want, and I believe I simply move the problem from Java code to an external configuration file. Update 5/10/19 (11 years later!) There are now several libraries that can help with this according to @IvanNik's   looks good. Also  from @Luke Hutchison's  looks interesting. There are several more possibilities in the answers as well.  Another way to state what I want: a static function in my Animal class finds and instantiates all classes that inherit from Animal -- without any further configuration/coding.  If I have to configure, I might as well just instantiate them in the Animal class anyway.  I understand that because a Java program is just a loose federation of .class files that that's just the way it is.  Interestingly, it seems this is  in C#.
75001
As the topic suggests I wish to be able to pass table names as parameters using .NET (doesn't matter which language really) and SQL Server.  I know how to do this for values, e.g. command.Parameters.AddWithValue("whatever", whatever) using @whatever in the query to denote the parameter. The thing is I am in a situation where I wish to be able to do this with other parts of the query such as column and table names.  This is not an ideal situation but it's one I have to use, it's not really prone to SQL injection as only someone using the code can set these table names and not the end-user. It is messy however.  So, is what I am asking possible?   EDIT: To make the point about SQL injection clear, the table names are only passed in by source code, depending on the situation. It is the developer who specifies this. The developer will have access to the database layer anyway, so the reason I am asking is not so much for security but just to make the code cleaner.
4991
Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.  I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:  for item in self.inventory_names:     self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", item)     self.cursor.close()   I get the error:     sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied.   I believe this is somehow caused by the initial creation of the database; the module I made that actually creates the DB does have 8 bindings.  cursor.execute("""CREATE TABLE Equipment      (id INTEGER PRIMARY KEY,      name TEXT,     price INTEGER,      weight REAL,      info TEXT,      ammo_cap INTEGER,      availability_west TEXT,     availability_east TEXT)""")   However, when I use the less-secure "%s" substitution for each item name, it works just fine. Like so:  for item in self.inventory_names:     self.cursor.execute("SELECT weight FROM Equipment WHERE name = '%s'" % item)     self.cursor.close()   I can't figure out why it thinks I have 8 bindins when I'm only calling one. How can I fix it?
58028
I want to do something like this :  myYear = record.GetValueOrNull&lt;int?&gt;("myYear"),   Notice the nullable type as the generic parameter.   Since the GetValueOrNull function could return null my first attempt was this:   public static T GetValueOrNull&lt;T&gt;(this DbDataRecord reader, string columnName)   where T : class {     object columnValue = reader[columnName];      if (!(columnValue is DBNull))     {         return (T)columnValue;     }     return null; }   But the error I'm getting now is:     The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method   Right! Nullable&lt;int&gt; is a struct! So I tried changing the class constraint to a struct constraint (and as a side effect can't return null any more):  public static T GetValueOrNull&lt;T&gt;(this DbDataRecord reader, string columnName)   where T : struct   Now the assignment:  myYear = record.GetValueOrNull&lt;int?&gt;("myYear");   Gives the following error:     The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method   Is specifying a nullable type as a generic parameter at all possible?
48923
When using JDBC, I often come across constructs like    ResultSet rs = ps.executeQuery(); while (rs.next()) {     int id = rs.getInt(1);     // Some other actions }   I asked myself (and authors of code too) why not to use labels for retrieving column values:    int id = rs.getInt("CUSTOMER_ID");   The best explanation I've heard is something concerning performance. But actually, does it make processing extremely fast? I don't believe so, though I have never performed measurements. Even if retrieving by label would be a bit slower, nevertheless, it provide better readability and flexibility, in my opinion. So could someone give me good explanation of avoiding to retrieve column values by column index instead of column label? What are pros and cons of both approaches (maybe, concerning certain DBMS)?
122018
I am trying to add a list into an another nested list before adding values of a list to nested list it is getting the correct value but after adding i am getting (already output) in debug log when i checked.    public List&lt;String&gt; fieldName {get;set;}  public List&lt;List&lt;String&gt;&gt; fileValuesXML; // To get the field values of xml  for(Dom.XMLNode child : SalesforceObjecet.getChildElements()) {                        objecetName = child.getText();             system.debug('Object Name in XML field  ' + objecetName );              for(Dom.XMLNode subchild : child.getChildElements())              {                 system.debug('Sub child ' + subchild.getText() );                 for(Dom.XMLNode subchildfield : subchild.getChildElements())                 {                     system.debug('Sub child Field ' + subchildfield );                     fName  = subchildfield.getText();                     fieldName.add(fName);                     //fileValuesXML.add(fieldName);                     //system.debug('Filed Name in XML field  ' + fieldName);                 }                  system.debug('Filed Name before affing to filevalueXML  ' + fieldName);                                     fileValuesXML.add(fieldName);                 fieldName.clear();                 system.debug('Filed Name after affing to filevalueXML  ' + fileValuesXML);             }    }    I am getting values in debug log as:     Filed Name before affing to filevalueXML  (AccountSource, field3)   Filed Name after affing to filevalueXML  ((), (already output),   (already output))
98518
Using extension syntax I'm trying to create a left-join using LINQ on two lists that I have. The following is from the Microsoft help but I've modified it to show that the pets list has no elements. What I'm ending up with is a list of 0 elements. I assume that this is because an inner-join is taking place. What I want to end up with is a list of 3 elements (the 3 Person objects) with null data filled in for the missing elements. i.e. a Left-Join. Is this possible?  Person magnus = new Person { Name = "Hedlund, Magnus" }; Person terry = new Person { Name = "Adams, Terry" }; Person charlotte = new Person { Name = "Weiss, Charlotte" };  //Pet barley = new Pet { Name = "Barley", Owner = terry }; //Pet boots = new Pet { Name = "Boots", Owner = terry }; //Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; //Pet daisy = new Pet { Name = "Daisy", Owner = magnus };  List&lt;Person&gt; people = new List&lt;Person&gt; { magnus, terry, charlotte }; //List&lt;Pet&gt; pets = new List&lt;Pet&gt; { barley, boots, whiskers, daisy }; List&lt;Pet&gt; pets = new List&lt;Pet&gt;();  // Create a list of Person-Pet pairs where  // each element is an anonymous type that contains a // Pet's name and the name of the Person that owns the Pet. var query =     people.Join(pets,                 person =&gt; person,                 pet =&gt; pet.Owner,                 (person, pet) =&gt;                     new { OwnerName = person.Name, Pet = pet.Name }).ToList();
56570
I have a database table that looks like:   create table answers(    id int not null,    question_id int not null,    answer text null )   This table was originally build by Hibernate using the @Lob attribute for the "answer" column.  I did not realize it at the time, but when setup that way, Hibernate stores an OID in the column instead of the actual text.  Everything works fine when I use Hibernate to retrieve the values since it automatically converts the OID to the CLOB string, however it is becoming a performance problem and I'd like to get rid of the OID.   select * from answers ID     QUESTION_ID     ANSWER =============================== 1       123             55123 2       234             51614 3       345             56127 should be ID     QUESTION_ID     ANSWER =============================== 1       123             Male 2       234             203-555-1212 3       345             555 Main St. New York, NY    My desire is to add an extra column to the table "ANSWER_VALUE TEXT" and do something like below to get the actual value into the table, then change Hibernate around to not use the @Lob designator   update answers set ANSWER_VALUE= getValueFromOID(ANSWER)   Does that "getValueFromOID" function exist?  If not, could I get some pointers on how to create one or at least how to fetch the actual value of an OID?  Thanks
98355
With java.sql.ResultSet is there a way to get a column's name as a String by using the column's index? I had a look through the API doc but I can't find anything.
8920
What SQL can be used to list the tables, and the rows within those tables in an SQLite database file - once I have attached it with the ATTACH command on the SQLite 3 command line tool?
122930
I'm comparing two list given in the list to see if the item.name exists in both for loop. If not then add into a list to show the error for the missing names.  set&lt;id&gt; setAssetIds = new set&lt;id&gt;(); list&lt;Asset_Store__c&gt;  assets = [select id,name......]; for(Asset_Store__c item : assets ) {     setAssetIds.add(item.id);  }   list&lt;Meter__c&gt;  meters = [select id,name......where id in : setAssetIds];  //now comparing the two lists for(Asset_Store__c a : assets) {    for(Meter__c m : meters)    {      if(a.Name != m.Name)      {        //not matched...        break;      }     } }   the problem with the above approach is that, its not finding the correct name.
91805
Short prestory. Typical problem: you have a lot of small string and you want to concatenate them all in one big string. The code like for(Integer i = 0; i &lt; smallStringsSize; i++){     bigString += smallStrings[i]; }  will solve this problem, but it has to produce a lot of unnecessary string objects that consume your heap. That is why Java has classes like StringBuilder and StringBuffer that allow you to solve this problem wihtout consuming too many memory. Thus, I decided to try to do my own StringBuilder in apex. String class has two methods that looked suitable for it:   and  . Here is the code that i used to test these methods against &quot;+=&quot; concatenantion (ready to execute in anonymous): List&lt;String&gt; chars = new List&lt;String&gt;(); List&lt;Integer&gt; charsCode = new List&lt;Integer&gt;(); Integer size = 10000; String chartToAdd = 'Ω'; for(Integer i = 0; i &lt; size; i++){     chars.add(chartToAdd);     charsCode.add(String.valueOf(chartToAdd).charAt(0)); } String joinS = '', forS = '', fromS = ''; Integer initialHeapSize = Limits.getHeapSize(); Integer initialCPUtime = Limits.getCpuTime(); System.debug('initialHeapSize ' + initialHeapSize); System.debug('initialCPUtime ' + initialCPUtime); joinS = String.join(chars, ''); Integer joinHeapSize = Limits.getHeapSize() - initialHeapSize; Integer joinCPUtime = Limits.getCpuTime() - initialCPUtime; System.debug('-------- String.join ---------'); System.debug('joinHeapSize ' + joinHeapSize); System.debug('joinCPUtime ' + joinCPUtime); for(Integer i = 0; i &lt; size; i++){     forS += chars[i]; } Integer forHeapSize = Limits.getHeapSize() - joinHeapSize - initialHeapSize; Integer forCPUtime = Limits.getCpuTime() - joinCPUtime - initialCPUtime; System.debug('-------- for each += ---------'); System.debug('forHeapSize ' + forHeapSize); System.debug('forCPUtime ' + forCPUtime); fromS = String.fromCharArray(charsCode); Integer fromHeapSize = Limits.getHeapSize() - forHeapSize - joinHeapSize - initialHeapSize; Integer fromCPUtime = Limits.getCpuTime() - forCPUtime - joinCPUtime - initialCPUtime; System.debug('-------- String.fromCharArray ---------'); System.debug('fromHeapSize ' + fromHeapSize); System.debug('fromCPUtime ' + fromCPUtime); System.debug(''); System.debug('-------- strings ----------'); System.debug('joins ' + joins); System.debug('fors ' + fors); System.debug('fromS ' + fromS);  The result of this code execution:  initialHeapSize 161166 initialCPUtime 242 -------- String.join --------- joinHeapSize 10016 joinCPUtime 17 -------- for each += --------- forHeapSize 10024 forCPUtime 48 -------- String.fromCharArray --------- fromHeapSize 10016 fromCPUtime 5  As you can see, the heap size for each approach is so close to 10 kilobytes, what is a size of the string of 10 000 characters (size) if each character takes only one byte. In case of creating 10 000 additional string objects, the heap size would be a bit more than 50 megabytes (10 000 * (1 + 10 000)/2). Taking into consideration the above,  Does not the '+=' concatenation create any additional string objects that devour your heap? Did not I miss anything? I am so amazed.  As you see, I use Omega 'Ω' as a chartToAdd. It has  the high-surrogate code point equals to 937, that needs at least 2 bytes to be encoded. How can 10 000 Omegas consume only 10 000 bytes of the heap size?  What weightful reasons Salesforce has that they do not to add the character data type? Any ideas?
69888
I have a custom object, with a Text Name (ID) field. When I upsert two records with identical Name/ID, but otherwise different values, in two separate upsert statement, one record results, as expected.  When I create a list, add these records to the list, and then upsert the list, I get a DUPLICATE_VALUE error. What gives? By definition, upsert should not do this, should it? Even worse: it doesn't matter whether a record with the identical Name already exists or not, the upsert will fail in both scenarios.  By the way: by default upsert a does not use the Name/ID field as identifying/unique field, as you might expect. You need to do upsert a Name  Complete code:  List&lt;Flight__c&gt; flights = new List&lt;Flight__c&gt;(); Flight__c f1 = new Flight__c(); f1.Name = 'ABC123'; f1.Flight_Number__c = 'ABC'; flights.add(f1);  Flight__c f2 = new Flight__c(); f2.Name = 'ABC123'; f2.Flight_Number__c = '123'; flights.add(f2);  upsert flights Name;      Error message: Line: 12, Column: 1 System.DmlException: Upsert failed.   First exception on row 0; first error: DUPLICATE_VALUE, Duplicate   external id specified: ABC123: [Name]   Name being the standard identifying field of a custom object. You cannot edit the properties of this field, e.g. making it unique or not unique.