java.lang.RuntimeException: Unable to start activity   ComponentInfo{com.exampledinLoginActivity}:   java.lang.NullPointerException   protected void onCreate(Bundle savedInstanceState) {         Log.d(TAG, "login activity OnCreate************");          super.onCreate(savedInstanceState);         dbHandler = new DatabaseHandler(this);           wasDbExisted = dbHandler.ifDatabaseExists();         Log.d(TAG, "login activity wasdbexister="+wasDbExisted);         if (wasDbExisted &amp;&amp;//if db exists, this becomes true to send to mainactivity. mainactivity needs to know if db existed or not                  !dbHandler.isLoginRemember().equals(null)) {//isloginremember returns string, username if loginremember checked, if not only returns null Intent i = new Intent(LoginActivity.this, MainActivity.class);             i.putExtra("username", dbHandler.isLoginRemember());             i.putExtra("wasDbExisted", wasDbExisted);              startActivity(i);             finish();         }   This is first activity of my applicaiton. Login activity. It checks if db exists, if db exists and in database, loginremember is true, it goes to mainactivirt directlry without setcontent (this worked).  But if db doesnot exist , it setscontent and gets username password. or if loginremember false.  Caused by: java.lang.NullPointerException                                                                                          at com.example.caneraydin.androidwithlogin.LoginActivity.onCreate(LoginActivity.java:167)  error is that for that line:   if (wasDbExisted &amp;&amp;   but logs say  login activity wasdbexister=true   to sum up  Log.d(TAG, "login activity wasdbexister="+wasDbExisted);//log output is true for this         if (wasDbExisted &amp;&amp;//it gives nullexception for this   this is my manifest  &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.caneraydin.androidwithlogin"&gt;      &lt;uses-permission android:name="android.permission.INTERNET" /&gt;     &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"&gt;&lt;/uses-permission&gt;     &lt;uses-permission android:name="android.permission.READ_PHONE_STATE"&gt;&lt;/uses-permission&gt;     &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;      &lt;application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:supportsRtl="true"         android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"&gt;         &lt;activity android:name=".LoginActivity"             android:screenOrientation="landscape" &gt;             &lt;intent-filter&gt;                 &lt;action android:name="android.intent.action.MAIN" /&gt;                   &lt;category android:name="android.intent.category.LAUNCHER" /&gt;             &lt;/intent-filter&gt;         &lt;/activity&gt;          &lt;activity android:name=".MainActivity"             android:screenOrientation="landscape"&gt;         &lt;/activity&gt;       &lt;/application&gt;  &lt;/manifest&gt;   this is dbexists method of dbhandler class  public boolean ifDatabaseExists() {          Log.d(TAG,"dbhandlerifdbexists");          SQLiteDatabase db = this.getWritableDatabase();          Cursor mCursor = db.rawQuery("SELECT * FROM " + TABLE_OBJECT, null);//it is looking for object tble to check if db is null or not         Boolean dbExists;      if(mCursor.moveToFirst())     {         Log.d(TAG,"dbhandlerifdbexists true");         dbExists = true;     }      else     {         Log.d(TAG,"dbhandlerifdbexists false");         dbExists = false;     }          return dbExists; }   in my activity, the code is like that  if (wasDbExisted &amp;&amp;                 !dbHandler.isLoginRemember().equals(null)) {   it shows first line.
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?
112781
This is the error I get when I run my web application in an instance of the Tomcat servlet container started by NetBeans. To fix this I even changed the heap size in netbeans.conf, but still it shows the same error. How can I keep this from happening?   HTTP Status 500 -   --------------------------------------------------------------------------------  type Exception report  message   description The server encountered an internal error () that prevented it from fulfilling this request.  exception   javax.servlet.ServletException: Servlet execution threw an exception     org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)   root cause   java.lang.OutOfMemoryError: Java heap space  note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs.
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
96142
I am working on a requirement to create an opportunity and opportunity products , when there is an update on the asset object.  The asset object has a filed called Refresh_Asset_To__c, this is a lookup to the product object.   Basically each time I change the product on the Refresh_Asset_To__c, a new opportunity should be generated with the Refresh_Asset_To__c being the opportunity product.  I have tested , and its generating the opportunity , but each time i try to insert the opportunity product I get the error :      Update failed. First exception on row 0 with id 02i3B000003TAk7QAG; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AssetRefreshOpp: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry currency code does not match opportunity currency code): [PricebookEntryId] Trigger.AssetRefreshOpp: line 56, column 1: []   This is my code:  trigger AssetRefreshOpp on Asset (after update) {      Pricebook2 ikmBook    = [SELECT Id,CurrencyIsoCode FROM Pricebook2 WHERE Id = '01s46000003K1zXAAS'];  List&lt;OpportunityLineItem&gt; oppLiList = new List&lt;OpportunityLineItem&gt;(); Opportunity opp; OpportunityLineItem oli; string refeshed;     List&lt;asset&gt; refreshedAss = [select Id,Contract__r.EndDate,OwnerId,quantity,Name,Refresh_Asset_To__c,Refresh_Asset_To__r.Id,AccountId,account.name from asset                                      where Id IN : Trigger.new                                      And Refresh_Asset__c = True];          for(asset myAss:refreshedAss){             // Create New Opportunity              Opportunity newopp =new Opportunity();   newopp.Name=myAss.account.name + ' ' + 'refreshed'; newOpp.AccountId = myAss.AccountId; newOpp.CloseDate = myAss.Contract__r.EndDate; newOpp.StageName = 'Create'; newOpp.RecordTypeID = '01246000000TfMZAA0'; newOpp.OwnerId = myAss.OwnerId; newOpp.Amount = 0; newOpp.Type= 'Existing Business'; newOpp.OM_Order_Type__c = 'Regular'; newOpp.CurrencyIsoCode = ikmBook.CurrencyIsoCode; newOpp.Pricebook2Id = ikmBook.Id;  insert newOpp;          List&lt;PriceBookEntry&gt; priceBookList = [SELECT Id, Product2Id,CurrencyIsoCode, Product2.Id, Product2.Name FROM PriceBookEntry WHERE  PriceBook2.isStandard=true LIMIT 1];               for(asset myAssets:refreshedAss){               OpportunityLineItem oli = new OpportunityLineItem();                oli.OpportunityId = newOpp.Id;                oli.Product2Id = myAssets.Refresh_Asset_To__r.Id;                oli.PriceBookEntryId = priceBookList[0].Id;                oli.UnitPrice = 0;               oli.Quantity = myAssets.Quantity;               oppLiList.add(oli);           }           insert oppLiList;               } }
113159
I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized?   public static void Main(String[] args) {     Byte maxSize;     Queue queue;      if(args.Length != 0)     {         if(Byte.TryParse(args[0], out maxSize))             queue = new Queue(){MaxSize = maxSize};         else             Environment.Exit(0);     }     else     {         Environment.Exit(0);     }      for(Byte j = 0; j &lt; queue.MaxSize; j++)         queue.Insert(j);     for(Byte j = 0; j &lt; queue.MaxSize; j++)         Console.WriteLine(queue.Remove()); }   So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?  Hope ya'll can give me some pointers :)  Thanks.
8224
Since many users are facing the NullReferenceException: Object reference not set to an instance of an object error in Unity, I thought that it would be a good idea to gather from multiple source some explanation and ways to fix this error.  Symptoms I am getting the error below appearing in my console, what does it mean and how do I fix it?  NullReferenceException: Object reference not set to an instance of an object
105367
I'm trying to develop my first test class in our sandbox instance. When running the below test, I am getting no records return from the first query to build accountsList. The test succeeds, but I have 0% code coverage. The trigger works as expected when ran.  My Test Class:  @isTest private class test_deleteAccountSharesOnUpdate {  static testMethod void updateAccounts()  {     Set&lt;String&gt; accountIds = new Set&lt;String&gt;();      List&lt;Account&gt; accountsList =      [         SELECT Id, Is_Script_Update__c, Description FROM Account     ];      Integer i = 0;     for (Account acct : accountsList)     {         if(i &gt; 199)         {             break;         }          acct.Is_Script_Update__c = True;         acct.Description = 'Testing at ' + System.now();          accountIds.add(acct.Id);          i++;     }      test.startTest();      update accountsList;      test.stopTest();      List&lt;Account&gt; updatedAccts =      [         SELECT Id, Is_Script_Update__c, Description         FROM Account          WHERE Id IN : accountIds     ];      for(Account acct : updatedAccts)     {         System.assertEquals         (             'Testing at',             acct.Description.substring(0,10)         );     } }   }  Trigger I'm trying to test:  trigger deleteAccountSharesOnUpdate on Account (after update)  {    Set&lt;String&gt; accountIds = new Set&lt;String&gt;();  // Gather the account Ids being updated for (Account acct : trigger.new) {     // Only remove shares for accounts being updated by data loader.     // Loader script will insert new shares after this job.     if(acct.Is_Script_Update__c)     {         String terrCode = acct.Territory_Code_String__c;          if(terrCode != null &amp;&amp; terrCode.length() == 5)         {                accountIds.add(acct.id);         }     } }  if(accountIds.size() &gt; 0) {     // Remove the shares associated with these accounts     delete      [         select id          from AccountShare          where RowCause = 'TerritoryManual' AND          AccountId IN : accountIds     ];      // Reset flag that indicates this update is from a data loader.     // Data loader will set this checkbox as true on update.     // This prevents the trigger on UI update.     //     List&lt;Account&gt; accountsList =      [         SELECT Id, Is_Script_Update__c          FROM Account          WHERE Id IN: accountIds     ];      for (Account acct : accountsList)     {         acct.Is_Script_Update__c = False;     }      update accountsList; }   }  Degub log shows no rows returned for the first query:  14:47:14.461 (3461430000)|SOQL_EXECUTE_BEGIN|[8]|Aggregations:0|select Id,       Is_Script_Update__c, Description from Account 14:47:14.483 (3483545000)|SOQL_EXECUTE_END|[8]|Rows:0  Any help is greatly appreciated!
53086
I have written a trigger for before update and after insert function  trigger EstimateBudgetPerMonth on Opportunity__c(after insert, before update) {     Date startDate = Date.newInstance(2008, 1, 1);     Date endDate = Date.newInstance(2008, 1, 30);     Set &lt; Id &gt; oppId = new Set &lt; Id &gt; ();     Integer totalBudget;     for (Opportunity__c opp: Trigger.new) {         startDate = opp.Campaign_Start_Date1__c;         endDate = opp.Campaign_End_Date1__c;         totalBudget = Integer.valueOf(opp.Budget1__c);         oppId.add(opp.Id);     }      InsertBudgetOpp insertRec = new InsertBudgetOpp();     InsertBudgetOpp updateRec = new InsertBudgetOpp();        if (Trigger.isInsert) {         System.debug('--===Insert==--#--===Insert==--#--===Insert==--');          List &lt; Budget_Allocation__c &gt; baList = insertRec.insertChild(oppId, startDate, endDate, totalBudget);          insert baList;      } else if (Trigger.isUpdate) {         System.debug('--===Update==--#--===Update==--#--===Update==--');          Map &lt; String, Budget_Allocation__c &gt; baNewMap = updateRec.updateChild(oppId, startDate, endDate, totalBudget);          upsert baNewMap.values();     }    }    Its throwing the below error.     Error: Invalid Data.  Review all error messages below to correct your   data. Apex trigger EstimateBudgetPerMonth caused an unexpected   exception, contact your administrator: EstimateBudgetPerMonth:   execution of BeforeUpdate caused by: System.DmlException: Upsert   failed. First exception on row 0 with id a0Up00000000FHJEA2; first   error: SELF_REFERENCE_FROM_TRIGGER, Object (id = a06p0000000N3WU) is   currently in trigger EstimateBudgetPerMonth, therefore it cannot   recursively update itself: []: Trigger.EstimateBudgetPerMonth: line   38, column 1
7898
The StackExchange app crashes for me on every start when I click a link in the browser. It seems (based on the StackTrace) that the url parser causes a null pointer exception. I'm using 0.1.90.
45672
This question has been asked before, but none of the answers on those threads have helped so far.  Getting the following error when trying to deploy a test class from the sandbox to production in the Force.com IDE:  System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LeadPerson: execution of AfterInsert caused by: System.Exception: Too many SOQL queries: 101  LeadPerson trigger looks OK, e.g., no SOQL calls inside a loop.  trigger LeadPerson on Lead (after insert) {     Map&lt;Id, Lead&gt; leadMap = new Map&lt;Id, Lead&gt;();     Map&lt;String, Lead&gt; leadEmailMap = new Map&lt;String, Lead&gt;();      for(Lead lead : Trigger.new) {         if (lead.Email != null) {             leadMap.put(lead.Id, lead);             leadEmailMap.put(lead.Email, lead);         }     }      Map&lt;String, Person__c&gt; personMap = new Map&lt;String, Person__c&gt;();     for (Person__c p : [SELECT Id, Email__c FROM Person__c WHERE Email__c IN :leadEmailMap.keySet()]) {         personMap.put(p.Email__c, p);     }      List&lt;Person__c&gt; addPersons = new List&lt;Person__c&gt;();     List&lt;PersonHistory__c&gt; addPersonHistorys = new List&lt;PersonHistory__c&gt;();     List&lt;Lead&gt; addPersonLead = new List&lt;Lead&gt;();     Map&lt;String, String&gt; addPersonEmails = new Map&lt;String, String&gt;();      for(Lead lead : Trigger.new) {         if (lead.Email != null) {             if (personMap.containsKey(lead.Email)) {                 // Create PersonHistory__c record for existing Person__c records                 Person__c getPerson = personMap.get(lead.Email);                 PersonHistory__c newPersonHistory = new PersonHistory__c();                 newPersonHistory.Person__c = getPerson.Id;                 newPersonHistory.RecType__c = 'LEAD';                 newPersonHistory.RecSubType__c = lead.inq_type__c;                 newPersonHistory.SFID__c = lead.Id;                 newPersonHistory.RecTypeStatus__c = 'NEW';                 addPersonHistorys.add(newPersonHistory);             } else {                 // Create Person__c and PersonHistory__c record for NEW Person__c records                 String firstInitial = '';                 if (lead.FirstName != null) {                     firstInitial = lead.FirstName.substring(0, 1);                 }                  if (!addPersonEmails.containsKey(lead.Email)) {                     addPersonEmails.put(lead.Email, 'EMAIL');                     Person__c newPerson = new Person__c();                     newPerson.Email__c = lead.Email;                     newPerson.AltKey__c = firstInitial + lead.LastName + lead.PostalCode;                     newPerson.Current_Status__c = 'NEW';                     addPersons.add(newPerson);                     addPersonLead.add(lead);                 }             }         }     }      // INSERT NEW Person__c records     List&lt;Database.SaveResult&gt; newPersonResult = Database.Insert(addPersons);     for (integer i = 0; i &lt; newPersonResult.size(); i++) {         // Create PersonHistory__c records for new Person__c records         PersonHistory__c newPersonHistory = new PersonHistory__c();         newPersonHistory.Person__c = newPersonResult.get(i).getId();         newPersonHistory.RecType__c = 'LEAD';         newPersonHistory.RecSubType__c = addPersonLead.get(i).inq_type__c;         newPersonHistory.SFID__c = addPersonLead.get(i).Id;         newPersonHistory.RecTypeStatus__c = 'NEW';         addPersonHistorys.add(newPersonHistory);     }     insert addPersonHistorys; }   The debug log doesn't show a transaction having more than 5 out of 100 SOQL queries in the CUMULATIVE_LIMIT_USAGE sections. Not sure where to look next. Any help is appreciated.
121895
I have a trigger and a class that seem to be causing an insert fail in Dataloader.  I am trying to insert 200 records to see if an error is generated before moving these to production. I'm just inserting the mandatory fields such as Name, Owner, Market, Customer_Success_Manager__c, and Business Unit.   Each time I get an error:     UpdateCSMTeam:execution of AfterInsertcaused by: System.DmlException:   Insert failed. First exception on row 0 with id01MJ0000009gXthMAE;   first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an   insert call: [Id]Class.UpdateCSM.updateTeamMem . I've listed the class   and trigger below.   APEX CLASS  public class UpdateCSM {             public static void updateTeamMember(List&lt;Account&gt; accounts) {                     List&lt;AccountShare&gt; ashareLIST = new List&lt;AccountShare&gt;();                     List&lt;AccountTeamMember&gt; ATM = new List&lt;AccountTeamMember&gt;();                    Set&lt;String&gt; rmMember = new Set&lt;String&gt;();                     Map&lt;ID, ID&gt; acctToBRepMap = new Map&lt;ID, ID&gt;();                      for(Account a:accounts){                              AccountShare caSharingRule = new AccountShare();                                caSharingRule.AccountId = a.Id;                                caSharingRule.OpportunityAccessLevel = 'Edit';                                caSharingRule.CaseAccessLevel = 'Edit';                                caSharingRule.AccountAccessLevel = 'Edit';                                caSharingRule.UserOrGroupId = a.Customer_Success_Manager__c;                                ashareLIST.add(caSharingRule);                                    if(a.Customer_Success_Manager__c!= null){                                   AccountTeamMember Teammemberad=new AccountTeamMember();                 Teammemberad.AccountId=a.id;                 Teammemberad.UserId=a.Customer_Success_Manager__c;                 Teammemberad.TeamMemberRole = 'Customer Success Manager';                                   ATM.add(Teammemberad);                             if(!ATM.isEmpty()){                                    insert ATM;                                              insert ashareLIST;                                                         if(a.Customer_Success_Manager__c==null){                                            list&lt;AccountTeamMember&gt; ratm = [SELECT UserId                                                                             FROM AccountTeamMember                                                                             WHERE (TeamMemberRole = 'Customer Success Manager')                                                          AND AccountId =:a.id];                                             if(ratm.size()&gt;0)                                                 delete ratm;                                        }                                    }                                 }                            }                         }                    } ...   APEX TRIGGER  trigger UpdateCSMTeam on Account (After update, After insert){         UpdateCSM.updateTeamMember(trigger.new); }
68276
In my page constructor I call a method isFirstPageLoaded, to  check if the loaded page is the first page of the wizard.   private final PageReference FIRSTPAGE = Page.Maintenance_Lock_1;   private void isFirstPageLoaded() {          if(ApexPages.currentPage()!=this.FIRSTPAGE) {              throw new MaintenanceLockException(this.FIRSTPAGE + ' --- ' + ApexPages.currentPage());          }      }   The problem is: Even if I open the first page of the wizard, the exception is thrown. How can I compare two PageReferences? I would like to avoid to parse the URLs and remove parameters etc...
109620
I used   Runtime.getRuntime().exec("_____")   but it throws a IOException as below:  java.io.IOException: CreateProcess: c:/ error=5   at java.lang.Win32Process.create(Native Method)   at java.lang.Win32Process.&lt;init&gt;(Win32Process.java:63)   at java.lang.Runtime.execInternal(Native Method   I don't know whether I have the problem with specifying the path or something else. Can anyone please help me with the code.
28359
I'm trying to build an Android test application integrated to the SalesForce platform. I have downloaded the SDK from , and imported it to my workspace. Everything works fine except my test app, even the  they have provided along with the SDK work without problem. As a first step, what I tried was to clone the basic features (just login as of now) from the RestExplorer app. The following are my important files.  public class Home extends Activity {  private PasscodeManager passcodeManager; private RestClient client; private TokenRevocationReceiver tokenRevocationReceiver;  RestClient getClient() {     return client; }  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);      passcodeManager = SalesforceSDKManager.getInstance().getPasscodeManager();     tokenRevocationReceiver = new TokenRevocationReceiver(this);     setContentView(R.layout.activity_home);  }  @Override  public void onResume() {     super.onResume();     registerReceiver(tokenRevocationReceiver, new IntentFilter(ClientManager.ACCESS_TOKEN_REVOKE_INTENT));           if (passcodeManager.onResume(this)) {   // Bring up passcode screen if needed         String accountType = SalesforceSDKManager.getInstance().getAccountType();   // Login options         new ClientManager(this, accountType, SalesforceSDKManager.getInstance().getLoginOptions(), SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked()).getRestClient(this, new RestClientCallback() {    // Get a rest client             @Override             public void authenticatedRestClient(RestClient client) {                 if (client == null) {                     SalesforceSDKManager.getInstance().logout(Home.this);                     return;                 }                 Home.this.client = client;                           }         });     } }  @Override protected void onPause() {     passcodeManager.onPause(this);     unregisterReceiver(tokenRevocationReceiver);     super.onPause(); } }   I have added the permissions as required  &lt;permission android:name="com.salesforce.samples.restexplorer.C2D_MESSAGE"     android:protectionLevel="signature" /&gt;  &lt;uses-permission android:name="com.salesforce.samples.restexplorer.C2D_MESSAGE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt; &lt;uses-permission android:name="android.permission.GET_ACCOUNTS"/&gt; &lt;uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/&gt; &lt;uses-permission android:name="android.permission.ACCOUNT_MANAGER"/&gt;   And extended the application object to give a call to init();  public class MyApp extends Application { @Override public void onCreate() {     super.onCreate();     SalesforceSDKManager.initNative(getApplicationContext(), new KeyImpl(), Home.class); } }   Now, I'm getting the error in my Android debug log. The log as I see is attached below. It keep the activity restarting till I forcefully kill the application.  11-08 15:56:23.883: I/ClientManager:getRestClient(9334): No account of type com.salesforce.androisdk found 11-08 15:56:23.898: W/AccMgrCallback:run(9334): android.accounts.AuthenticatorException: bind failure 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.AccountManager.convertErrorToException(AccountManager.java:1726) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.AccountManager.access$400(AccountManager.java:144) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.AccountManager$AmsTask$Response.onError(AccountManager.java:1572) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.IAccountManagerResponse$Stub.onTransact(IAccountManagerResponse.java:69) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.os.Binder.execTransact(Binder.java:388) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at dalvik.system.NativeStart.run(Native Method)   Do anyone have any idea about this isse? It is such a basic app, I was not expecting anything unusual. Did I do anything wrong in my app?
46169
I'm getting an error INACTIVE_OWNER_OR_USER, operation performed with inactive user, and I have been doing a lot of research and the cause that I have found for this is its attempting to assign a my lead to inactive user.  So I understand that part I think the issue is now I don't actually know how to fix it, I didn't write this trigger/test class and I'm not sure how to go forward.  Do I need to create a new Test User?  I've never worked on the Lead object before..  Edit** I added IsActive = True the trigger user query, no luck.  Edit** I just went talking to anyone that might have an idea about UserTypes, and they have no idea what UserType = 'PowerPartner' is.  So I changed it to a different UserType.. didn't work  Edit**  I'm nuking this trigger, I have to re write it..  Test Class  @isTest private class PartnerLeadShare_test { static testMethod void myUnitTest1() { List&lt;Lead&gt; leadList = new List&lt;Lead&gt;(); List&lt;LeadShare&gt; leadShareList = new list&lt;LeadShare&gt;();   Lead ld = new Lead(); ld.lastName = 'Tester';//=/ ld.Company = 'MyCompany'; ld.Status = 'Open'; ld.Program_EAU__c ='11'; insert ld; system.debug('ld****' +ld);  GroupMember groupMemberStore = [select GroupId,UserOrGroupId from GroupMember limit 1];  LeadShare ls = new LeadShare();  ls.LeadId = ld.id; ls.UserOrGroupId = groupMemberStore.UserOrGroupId ; ls.LeadAccessLevel = 'Edit'; leadShareList.add(ls);   if(leadShareList.size()&gt;0){     system.debug('INSIDE LEADSHARE LIST.');      insert leadShareList;  }  } }   Don't know this will help but here is my trigger..  trigger PartnerLeadShare on Lead (after insert,after update) {  Map&lt;id,User&gt;PartnerUsermap = new Map&lt;id,user&gt;([select id,UserType from user where      UserType = 'PowerPartner' and IsActive = True] );    List&lt;GroupMember&gt;GroupMemberList = new List&lt;GroupMember&gt;([select GroupId,UserOrGroupId   from GroupMember]);   System.debug('PartnerUsermap ===  '  +PartnerUsermap); System.debug('GroupMemberList    '+GroupMemberList );  List&lt;LeadShare&gt; leadShareList = new list&lt;LeadShare&gt;();    if(!PartnerUsermap.isEmpty()){ for(Lead ld: trigger.new){      for(GroupMember grpmem : GroupMemberList){         if(grpmem.UserOrGroupId == ld.CreatedById){               LeadShare ldShare = new LeadShare (LeadId = ld.id,UserOrGroupId = grpmem.GroupId,LeadAccessLevel = 'Edit');              leadShareList.add(ldShare );         }     } } } if(!leadShareList.isEmpty()){ Database.SaveResult[] lsr = Database.insert(leadShareList,false);            Integer i=0; for(Database.SaveResult sr : lsr){     if(!sr.isSuccess()){     Database.Error err = sr.getErrors()[0];              if(!(err.getStatusCode() == StatusCode.FIELD_FILTER_VALIDATION_EXCEPTION                                              &amp;&amp;  err.getMessage().contains('AccessLevel'))){                  trigger.newMap.get(leadShareList[i].LeadId).                   addError(                    'Unable to grant sharing access due to following exception: '                    + err.getMessage());             }     }    i++; } }
48842
I'm creating my first full framework using Selenium and TestNG and recently implemented the ability to have logging enabled which will track every action (before and after).  public class CustomLogs {     //Set Logging_Level to "Debug" to enable logging     public String Logging_Level = "OFF";      public void Log(String message) {         if (Logging_Level == "Debug")         {System.out.println(message);         } else {         }     } }   Then, in my page objects, EVERY action method has a log statement before and after EVERY action.  public class LoginPage extends BrowserConfig {      final WebDriver driver;     private static CustomLogs customlogs = new CustomLogs();      //Elements on Page     @FindBy(id = "userId")     private WebElement userNameField;      //Constructor     public LoginPage(WebDriver driver) {         this.driver = driver;     }      //Fill Username     public void FillUsername(String userNameEntry) {         userNameField.clear();         customlogs.Log("Entering Username: "+userNameEntry+"...");         userNameField.sendKeys(userNameEntry);         customlogs.Log("Username entered.");   It seems like this is very beneficial, not only for debugging, but also because you can now print out every single action step, so keeping records or showing others what steps were completed is very straightforward.  But I can also see how this is cluttering the page object code.  Is this a good idea?  And/or is there a better way to do this?
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();