Using Retrofit2 to parse JSON in but getting NULL pointer exception &amp; I don't know why? JSON response:  { "query": {     "count": 1,     "created": "2016-04-29T17:19:45Z",     "lang": "US",     "results": {         "quote": [{             "name": "Talon",             "tix": "50.0000",             "avg": "34757600",                  }]               }         } }   Query class:  public class Query {  @SerializedName("query") private String query = null;  }   Results class:  public class Results {  @SerializedName("results") private String results = null;  @SerializedName("results") private List&lt;Quote&gt; Quotes; public List&lt;Quote&gt; getQuotes() {     return Quotes; } }   Quote class:  public class Quote {  @SerializedName("name") private String Name; public String getName() {     return Name; }  @SerializedName("tix") private String Tix; public String getTix() {     return Tix; }  @SerializedName("avg") private String Avg; public String getAvg() {     return Avg; }  }   Error returned in Android Studio logcat: java.lang.NullPointerException: storage == null at Activity.java:60. That line contains:  data = new ArrayList&lt;&gt;(Arrays.asList(jsonResponse.getQuotes()));   I'm not certain if the NULL is because the model classes aren't correct or something else &amp; uncertain how/where to begin to fix it? I've looked at 4 other questions that have the same error but none were using Retrofit or JSON...
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?
61126
I am getting java.lang.NullPointerException while executing my test case , I am using Page Object Modle with PageFactory ,following are the code snippets  LoginPageObjec.java  public class LoginPageObjects {      @FindBy(xpath=".//*[@id='userName']")     private WebElement email;      @FindBy(xpath=".//*[@id='password']")     private WebElement password;      @FindBy(xpath=".//*[@id='loginFormSubmit']")     private WebElement loginBtn;      public void EnterUserName(String userName)     {         email.sendKeys(userName);     }      public void EnterPassword(String pass)     {         password.sendKeys(pass);     }      public void clickLogin()     {         loginBtn.click();     }   }   LoginTC.java  public class LoginTC extends BasePage{     private WebDriver driver;      @Test     public void login()     {         LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);         loginPage.EnterUserName("test.hr@domin.com.pk");         loginPage.EnterPassword("test");         loginPage.clickLogin();     } public void login1()         {             LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);             loginPage.EnterUserName("test.hr@domin.com.pk");             loginPage.EnterPassword("test");             loginPage.clickLogin();         }  }   BasePage.java  public class BasePage {     private WebDriver driver;      @BeforeMethod       public void initializeBrowser() {      driver=new FirefoxDriver();      driver.navigate().to("https://nexthrm-dev.vteamslabs.com/");      driver.manage().window().maximize();      }     @AfterMethod     public void closeBrowser()     {         driver.close();     }  }   I've extended BasePage class to utilize the (initialBrowser &amp; closeBrowser) functions in my test case but its producing nullpointer exception if I copy both of the functions (initialBrowser &amp; closeBrowser) into my LoginTC (testcase class) it works like charm but I dont want this redundant code i.e((initialBrowser &amp; closeBrowser) for all my testcases class could anyone explain why I am getting nullpointer exception
38193
A type of the body is JSON Blob in a form of:  {"key1":"val1";"key2":"val2"}  I wanted to convert it into a Map&lt;String, String&gt;. Do I have to manually deserialize it or there's a class which can handle that?
34916
I have an issue which I've been struggling with today. The JSON is returned back to me with a project Id as the key, this Project Id is dynamically generated and due to this I have not been able to come up with a way to deserialize this response. Any suggestions?   {      "success":true,    "numRows":5,    "data":{         "23000079":{            "projectId":"23000079",          "name":"Mcdonalds",          "departmentId":"9383",          "responsibleUserId":"7444434"       }    } }
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.
60121
This is what my JSON looks like: {"series":[{,"points":[{"ts":"1473850836254","value":"11.27"},{"ts":"1473851256637","value":"6.44"}]}]}  I am trying to access the values in "points" by calling something like: data.series.points[0].ts       Void Start(){     IncomingData data = IncomingData.CreateFromJSON(jsonResponse.text);     print("Series point length" + data.series.points.Count);     print("Series point 0" + data.series.points.get_Item[0].ts); // error     }   //----------------------------------------- classes -------------------------      [System.Serializable]     public class IncomingData     {         public Series series;         public static IncomingData CreateFromJSON(string json)         {                return JsonUtility.FromJson&lt;IncomingData&gt;(json);          }     }      [System.Serializable]     public class Series     {         public List&lt;Points&gt; points = new List&lt;Points&gt; { };     }       [System.Serializable]     public class Points     {         public int ts;         public int value;     }   My error:  // error CS0021: Cannot apply indexing with [] to an expression of type `method group'
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?
58381
I am using PostgreSQL/PostGIS. I have the following JSON format &quot;{'type': 'Polygon',  'coordinates':  [[[6.69223420722764, 51.1329165124371], [6.69222819326484, 51.1329081193748], [6.69221180776184, 51.1329013203209], [6.69219149698336, 51.1329073049609],   [6.69217949340067, 51.1329244260894], [6.69217956546811, 51.1329430447612], [6.69218526127669, 51.1329578171713], [6.692200130301, 51.1329606289999],   [6.69220511560768, 51.1329581192089], [6.69221372090576, 51.1329518135339], [6.69222707128915, 51.132939215911], [6.69223420722764, 51.1329165124371]]]}&quot;     and I would like to apply the function ST_GeomFromJSON() as shown below in the code, but I am getting the error mentioned in the error section below. How can I fix this? Code: SELECT ST_GeomFromGeoJSON( &quot;{'type': 'Polygon',  'coordinates':  [[[6.69223420722764, 51.1329165124371], [6.69222819326484, 51.1329081193748], [6.69221180776184, 51.1329013203209], [6.69219149698336, 51.1329073049609],   [6.69217949340067, 51.1329244260894], [6.69217956546811, 51.1329430447612], [6.69218526127669, 51.1329578171713], [6.692200130301, 51.1329606289999],   [6.69220511560768, 51.1329581192089], [6.69221372090576, 51.1329518135339], [6.69222707128915, 51.132939215911], [6.69223420722764, 51.1329165124371]]]}&quot;)     Error: NOTE: Identifier &quot;{'type': 'polygon',      'coordinates':      [[[6.69223420722764, 51.1329165124371], [6.69222819326484, 51.1329081193748], [6.69221180776184, 51.1329013203209], [6.69219149698336, 51.1329073049609],       [6.69217949340067, 51.1329244260894], [6.69217956546811, 51.1329430447612], [6.69218526127669, 51.1329578171713], [6.692200130301, 51.1329606289999],       [6.69220511560768, 51.1329581192089], [6.69221372090576, 51.1329518135339], [6.69222707128915, 51.132939215911], [6.69223420722764, 51.1329165124371]]}&quot; is changed to &quot;{'type': 'polygon',      'coordinates':      [[[6.69223420722764, 51.&quot;]]}&quot; will be shortened to &quot;}&quot;.  ERROR: ERROR: Column &quot;{'type': 'polygon',      'coordinates':      [[[6.69223420722764, 51.&quot;&quot; does not exist. LINE 2: &quot;{'type': 'polygon',
17994
How can I deserialize this json object:      {     "response": {         "count": 1,         "benchmark": 0.22567009925842,         "requests": [             {                 "request": {                     "id": 537481,                     "image_thumbnail": "",                     "title": "Request for new bin(s) - residential",                     "description": "Propmain ref  3234-1114",                     "status": "submitted",                     "address": "36 Pine Tree Close",                     "location": "Peterborough, England",                     "zipcode": "PE1 1EJ",                     "user": "",                     "date_created": 1417173208,                     "count_comments": 0,                     "count_followers": 0,                     "count_supporters": 0,                     "lat": 52.599967,                     "lon": -0.233482,                     "user_follows": 0,                     "user_comments": 0,                     "user_request": 1,                     "rank": "0"                 }             }         ],         "status": {             "type": "success",             "message": "Success",             "code": 200,             "code_message": "Ok"         }     } }   What i've tried:   Map&lt;String,Object&gt; rawObj = (Map&lt;String,Object&gt;) JSON.deserializeUntyped(jsonString);     Map&lt;String,Object&gt; responseObj = (Map&lt;String,Object&gt;)rawObj.get('response');     List&lt;Object&gt; reqs = (List&lt;Object&gt;) responseObj.get('requests');     System.debug('Map Size = ' + reqs.size());     Map&lt;String, Object&gt; i = new Map&lt;String, Object&gt; ();     for (Object x : reqs) {          i = (Map&lt;String, Object&gt;)x; }     Map&lt;String,Object&gt; requests = (Map&lt;String,Object&gt;)i.get('request');     System.debug('Map Size = ' + i.size());     for (String field : i.keySet()){          Object id = i.get(field);         Object title = i.get('title');         System.debug('Id : ' + id);         System.debug('title : ' + title);          //System.debug('Title : ' + title);       }
38112
Here's the scenario...    if (entry.Properties["something"].Value != null)   attribs.something = entry.Properties["something"].Value.ToString();   While effective and working correctly, this looks ugly to me.  If I don't check for a null before performing the ToString() then it throws an exception if the property was null.  Is there a better way to handle this scenario?  Much appreciated!
100647
I have a shape layer with an attribute containing NULL values to which I would like to apply a filter for values different from NULL.    Using the available gui for such query construction, one would intuitively try  "obj_art" != NULL     Which means 'give me all the features with attribute "obj_art" different from NULL' (these count definitely more than 0). Testing this query delivers a strange result from my point of view:    So what I've learned so far is that I can achieve this by using  "obj_art" IS NOT NULL   The question is, what is the difference between != NULL and IS NOT NULL?
78597
I keep getting the System.NullPointerException: Attempt to de-reference a null object on my trigger at line 21. I've attempted to add != null to that line and I get an error too. Please see the code below.  trigger UpdateDMAAccount on Account (before insert, before update) { //get set of Postal Codes from leads to be inserted or updated Set&lt;String&gt; BillingpostalCodes = new Set&lt;String&gt;(); for(Account l : trigger.new){ if(l.BillingPostalCode != null){     BillingpostalCodes.add(l.BillingPostalCode);  } } if(BillingpostalCodes.size() &gt; 0){ //create Map of custom object records with Name (PostalCode) as key Map&lt;String,DMA_Value__c&gt; validBillingPostalCode = new Map&lt;String,DMA_Value__c&gt;(); for(DMA_Value__c obj : [SELECT Id, Name, DMA_Value__c FROM DMA_Value__c WHERE Name IN :BillingpostalCodes]){     validBillingPostalCode.put(obj.Name,obj); } for(Account l : trigger.new){     if((Trigger.isInsert || trigger.oldMap.get(l.Id).BillingPostalCode != l.BillingPostalCode) &amp;&amp; validBillingPostalCode.containsKey(l.BillingPostalCode)){          l.DMA__c = validBillingPostalCode.get(l.BillingPostalCode).DMA_Value__c;     }     else if(trigger.oldMap.get(l.Id).BillingPostalCode != NULL || l.BillingPostalCode &amp;&amp; !validBillingPostalCode.containsKey(l.BillingPostalCode)){         //blank value if new PostalCode does not match a record in the Map         l.DMA__c = Null;     }   }  } }
114531
I need to serialize a list of SObject without omission null values. This string I need for a later usage in JavaScript. Structure is crucial, because I need to construct a table out of it. The structure is very dynamic. Different SObjects may lead to different fields and therefore different columns. Missing values will corrupt all the output and are unacceptable.  As it stands, in current versions JSON.serialize() will not output null values. There are already some questions about this raised, but either the answers there are incorrect or I'm doing something wrong to apply them right:       As far as I understand, Apex version 28.0 and newer should have no null values and version 27.0 and older should have them. But I can't make it work. There was an issue that the JSON.serialized() was not versioned right but as to  it should be working now.   So I've created this helper-class:  public class elfApi27 {      public static string dump0(Object o) {         return system.JSON.serializePretty(o);      } }   Setting the version like this in the xml  &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ApexClass xmlns="http://soap.sforce.com/2006/04/metadata"&gt;     &lt;apiVersion&gt;27.0&lt;/apiVersion&gt;     &lt;status&gt;Active&lt;/status&gt; &lt;/ApexClass&gt;   tested it via execute anonymous like this (consider xl.log as system.debug)  Account a = new Account(name='test'); xt.log( elfApi27.dump0(a) );   I have tried all the versions from 32.0 down to 24.0 but the output stays rock-solid like this:  DB Callout Profile Code Escape   32.0 APEX_CODE,WARN;APEX_PROFILING,WARN;CALLOUT,WARN;DB,WARN;SYSTEM,WARN 19:09:02.119 (119823175)|EXECUTION_STARTED 19:09:02.119 (119833395)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex 19:09:02.132 (132802344)|USER_DEBUG|[230]|WARN|"{    "attributes" : {       "type" : "Account"    },    "Name" : "test" }" 19:09:02.132 (132848199)|CODE_UNIT_FINISHED|execute_anonymous_apex 19:09:02.134 (134336841)|EXECUTION_FINISHED    Am I misinterpreting the answers?  Is there any way to have a full verbose serialization of objects?
23661
Context Around this Code: I am making a schedulable class run each Sunday to track a couple of metrics important to the team.   Question: I am looking to consolidate DML operations and a big part of this is understanding pass by reference vs pass by value.  I want to pass the salesOps user object to the method SDREfficiencyLastWeek. I made the return type void, because I figured that I will be passing this by reference and I can make all the updates in the method without having to anything.   Why I am confused:    I read the above article and am thrown off by the following statement:  "Non-primitive data type arguments, such as sObjects, are also passed into methods by value. "   If the object is indeed passed by reference, then the query for the salesOps user in my code should be sufficient enough to edit all fields on that object without actually having to state each field in the query.  global class SDREfficientMetricsSchedulable implements Schedulable  {     global void execute(SchedulableContext sc)      {         User salesOps = [SELECT ID FROM USER WHERE id = '0056A000002Z3p9QAC'];         List&lt;String&gt; queries = new List&lt;String&gt;();          String contactsWorked_lastWeek  = 'select count(id) results from contact where LastActivityDate = last_week';         queries.add(contactsWorked_lastWeek);          String demosSet_lastWeek            = 'select count(id) results from form__c where CreatedDate = last_week';         queries.add(demosSet_lastWeek);          String demosCompleted_lastWeek  = 'select count(id) results from opportunity where (stagename = \'Unqualified Demo Completed\'  OR stagename = \'Qualified Demo Completed\' )  and RecordTypeId = \'0126A000000yudDQAQ\' and CloseDate = last_week';         queries.add(demosCompleted_lastWeek);          String qualifiedDemos_lastWeek  = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and isclosed = false and  SDR_Owner__c != null and CreatedDate = last_week';         queries.add(qualifiedDemos_lastWeek);          String closedWon_lastWeek       = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and iswon = true and  SDR_Owner__c != null and CloseDate = last_week';         queries.add(qualifiedDemos_lastWeek);            SDREfficiencyLastWeek(queries, salesOps);          update salesOps;     }       public void SDREfficiencyLastWeek(List&lt;String&gt; queries, User salesOps )     {        }  }
93419
I am using Structure map like the MVC storefront by Rob Conery does and I have an AdminController and so to get to it I just type:  website/Admin/action   however if I miss spell the controller name I get the error below:  Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: key  There error occurs on this line:  Controller controller = ObjectFactory.GetInstance(controllerType) as Controller;   Does anyone have any ideas on how I can handle this error or not allow it to happen at all and maybe just goto a 404 page??  Cheers in advance
77120
I am trying to implement  and below is my code and debug log - any help is appreciated.  Http httpProtocol = new Http();    HttpRequest request = new HttpRequest(); request.setHeader('Content-Type', 'application/json;'); request.setEndPoint('https://test.salesforce.com/services/oauth2/token'); request.setMethod('POST'); String strbody = '{"grant_type":"Password", "password":"MY PASSWORD + TOKEN", "username":"SANDBOX USER NAME",  "client_secret":"secret",   "client_id":"Client id from remote setttings"}'; request.setBody(strbody); HttpResponse response = httpProtocol.send(request); String jsonInput = response.getBody(); system.debug('jsonInput===&gt;'+jsonInput);   Debug log -   15:55:38.068 (68324000)|SYSTEM_METHOD_ENTRY|[5]|System.HttpRequest.setMethod(String) 15:55:38.068 (68346000)|SYSTEM_METHOD_EXIT|[5]|System.HttpRequest.setMethod(String) 15:55:38.068 (68350000)|STATEMENT_EXECUTE|[6] 15:55:38.068 (68356000)|HEAP_ALLOCATE|[6]|Bytes:357 15:55:38.068 (68381000)|VARIABLE_ASSIGNMENT|[6]|strbody|"{\"grant_type\":\"Passw (337 more) ..." 15:55:38.068 (68387000)|STATEMENT_EXECUTE|[7] 15:55:38.068 (68407000)|SYSTEM_METHOD_ENTRY|[7]|System.HttpRequest.setBody(String) 15:55:38.068 (68440000)|SYSTEM_METHOD_EXIT|[7]|System.HttpRequest.setBody(String) 15:55:38.068 (68445000)|STATEMENT_EXECUTE|[8] 15:55:38.068 (68478000)|SYSTEM_METHOD_ENTRY|[8]|System.Http.send(APEX_OBJECT) 15:55:38.068 (68568000)|CALLOUT_REQUEST|[8]|System.HttpRequest[Endpoint=https://test.salesforce.com/services/oauth2/token, Method=POST] 15:55:38.483 (483258000)|HEAP_ALLOCATE|[EXTERNAL]|Bytes:219 15:55:38.483 (483399000)|CALLOUT_RESPONSE|[8]|System.HttpResponse[Status=Bad Request, StatusCode=400] 15:55:38.483 (483424000)|HEAP_ALLOCATE|[8]|Bytes:96 15:55:38.483 (483444000)|SYSTEM_METHOD_EXIT|[8]|System.Http.send(APEX_OBJECT) 15:55:38.483 (483615000)|VARIABLE_ASSIGNMENT|[8]|response|"System.HttpResponse[Status=Bad Request, StatusCode=400]"|0x1b22c3f1 15:55:38.483 (483627000)|STATEMENT_EXECUTE|[9] 15:55:38.483 (483666000)|SYSTEM_METHOD_ENTRY|[9]|System.HttpResponse.getBody() 15:55:38.483 (483742000)|HEAP_ALLOCATE|[9]|Bytes:81 15:55:38.483 (483751000)|SYSTEM_METHOD_EXIT|[9]|System.HttpResponse.getBody() 15:55:38.483 (483780000)|VARIABLE_ASSIGNMENT|[9]|jsonInput|"{\"error\":\"unsupporte (61 more) ..." 15:55:38.483 (483786000)|STATEMENT_EXECUTE|[10] 15:55:38.483 (483794000)|HEAP_ALLOCATE|[10]|Bytes:13 15:55:38.483 (483980000)|HEAP_ALLOCATE|[10]|Bytes:94 15:55:38.483 (483999000)|SYSTEM_METHOD_ENTRY|[10]|System.debug(ANY) 15:55:38.484 (484025000)|USER_DEBUG|[10]|DEBUG|jsonInput===&gt;{"error":"unsupported_grant_type","error_description":"grant type not supported"}
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