I made a ViewPager/TabLayout app like in this video (everything same, but I don't have AppBarLayout and ImageView):   But if I want to try the app the debugger says:  "Caused by: java.lang.NullPointerException" at line 24  Here's some Code:  MainActivity.java (where the problem is)  TabLayout tablayout; ViewPager viewPager;  @Override     protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     viewPager = (ViewPager)findViewById(R.id.viewPager);     ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());     adapter.addFragment(new FragmentElso(), "Elso");     adapter.addFragment(new FragmentMasodik(), "Masodik");     adapter.addFragment(new FragmentHarmadik(), "Harmadik");      viewPager.setAdapter(adapter);     tablayout.setupWithViewPager(viewPager); *(line 24)* }   }  Fragments(here's one, but all 3 are exactly the same)  View viewelso; public FragmentElso() { }  @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {     viewelso = inflater.inflate(R.layout.elso, container, false);     return viewelso; }   } And here's the ViewPagerAdapter  public final List&lt;Fragment&gt; fragmentList = new ArrayList&lt;&gt;(); public final List&lt;String&gt; FragmentListTitles = new ArrayList&lt;&gt;();  public ViewPagerAdapter(FragmentManager fm) {     super(fm); }  @Override public Fragment getItem(int position) {     return fragmentList.get(position); }  @Override public int getCount() {     return FragmentListTitles.size(); }  @Override public CharSequence getPageTitle(int position) {     return FragmentListTitles.get(position); } public void addFragment(Fragment fragment, String Title){     fragmentList.add(fragment);     FragmentListTitles.add(Title);  }   }  And I have everywhere the import: android.support.v4.app.Fragment;  In advance thanks for every help!
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?
96424
I'm trying to create an activity that presents some data to the user. The data is such that it can be divided into 'words', each being a widget, and sequence of 'words' would form the data ('sentence'?), the ViewGroup widget containing the words. As space required for all 'words' in a 'sentence' would exceed the available horizontal space on the display, I would like to wrap these 'sentences' as you would a normal piece of text.  The following code:  public class WrapTest extends Activity {     /** Called when the activity is first created. */     @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         LinearLayout l = new LinearLayout(this);         LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.FILL_PARENT,                 LinearLayout.LayoutParams.WRAP_CONTENT);         LinearLayout.LayoutParams mlp = new LinearLayout.LayoutParams(                 new ViewGroup.MarginLayoutParams(                         LinearLayout.LayoutParams.WRAP_CONTENT,                         LinearLayout.LayoutParams.WRAP_CONTENT));         mlp.setMargins(0, 0, 2, 0);          for (int i = 0; i &lt; 10; i++) {             TextView t = new TextView(this);             t.setText("Hello");             t.setBackgroundColor(Color.RED);             t.setSingleLine(true);             l.addView(t, mlp);         }          setContentView(l, lp);     } }   yields something like the left picture, but I would want a layout presenting the same widgets like in the right one.        Is there such a layout or combination of layouts and parameters, or do I have to implement my own ViewGroup for this?
20122
I just now  from the Android app (the first I've actually published using it).  After telling me it was successfully submitted (which it was), I was taken to a screen in which I was presumably going to get to view my question. But on that very screen, I got a message saying: 'Loading the question failed.'  (The retry button didn't do anything.)    I'm using app version 1.0.11 on a HTC One running Android 4.3.  Here's what I did exactly:   Added tags to the question: , , then , then . (then removed ) Filled out the title Filled out the body Hit submit, without a preview.
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 ?
57448
So, I've been spending considerable more time on SO recently than I normally have, and one thing that I've noticed is quite a few people saying stuff like "There's a Null Pointer Error in this block of code, please help me fix it", with a huge amount of code posted, and no real clue as to where the NPE is. So my question is, what can we do to accomplish 2 goals?   Help the person asking the question become a better programmer. Help them to solve their problems.
103233
How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.  EDIT: .
8114
I have same exception can please   The previous post issue is resolved.  Exception: :System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out  Visualforce Page   &lt;apex:page controller="Controller" action="{!init}" showHeader="false" sidebar="false"&gt;     &lt;center&gt;         &lt;apex:pageBlock title="Request Listener"&gt;&lt;/apex:pageBlock&gt;               &lt;/center&gt; &lt;/apex:page&gt;   Controller :            PUBLIC with sharing class Controller {        PUBLIC String fromNumber      = ApexPages.currentPage().getParameters().get('From');     PUBLIC String toNumber        = ApexPages.currentPage().getParameters().get('To');     PUBLIC String body            = ApexPages.currentPage().getParameters().get('Body');        PUBLIC PageReference init()     {                    System.debug('From Phone Number :' +fromNumber);         System.debug('To phone NUmber :' + toNumber);         System.debug('Message Body :' + body);          TwilioRestClient Client = TwilioAPI.getDefaultClient();                                                                SYSTEM.DEBUG('FROM AND To  Number is NOT NULL');                      String formattedNumber='+919876543210';                 IF(body != NULL)                 body = body;             ELSE                 body = '';             Case c = NEW Case (Subject = formattedNumber,Description = body,Origin = 'Phone');             INSERT c;                               Map&lt;String,String&gt; params1 = new Map&lt;String,String&gt;             {                'To'   =&gt; fromNumber,                'From' =&gt; '+1908280****',                'Body' =&gt; 'Conformation to customer'             };             TwilioMessage message = client.getAccount().getMessages().create(params1); /* Valid conformation SMS sent to the Customer.*/                                            return null ;     } }   While loin as admin then click preview on visualforce page executed but case is not created.I have checked the the debug log it throw the exception.
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?
107240
Quite often, in programming we get situations where null checks show up in particularly large numbers. I'm talking about things like:  if (doc != null) {   if (doc.Element != null)   {     ... and so on   }   else     throw new Exception("Element cannot be null"); } else {   throw new Exception("document cannot be null"); }   Basically, the whole thing turns into an unreadable nightmare, so I'm wondering: is there an easier way to describe what I'm trying to do above? (In addition to null checks, I get things like string.IsNullOrEmpty from time to time.)  Accepted answer: I accepted the answer that has  because the approach described is innovative, and is precisely what I want. Thanks Shawn!
24554
I have a lookup relationship.  If I just do the following query it works fine:  Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId]; system.debug('c:' + c);   However with the following I get an error:  Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId]; String c2 = (String) r.getSobject('field__r').get('fieldchild__c');   Error message:     FATAL_ERROR System.NullPointerException: Attempt to de-reference a   null object
90464
We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.  Is there a reason why "null" has even been included in the language?  After all, if there were no "null", I would have no bug, right?  In other words, what feature in the language couldn't work without null?
86556
I already looked at related questions, such as , but I am just as baffled as before. MWE:  \documentclass{article} \begin{document} \thepage\par \null\null\null\null\null\null\null\null \null\null\null\null\null\null\null\null \null\null\null\null\null\null\null\null \null\null\null\null\null\null\null\null \null\null\null\null\null\null\null\null \null\null\null\null\null\null \thepage\par \end{document}   The above code produces a two-page document. It prints \thepage as 1 on both pages. Add another \null or two, and the second \thepage correctly shows as 2.  Apparently, \thepage does not kick in until about the third line of the page. I have tried this with more complicated code, and it seems to be the general case.  Bug? Feature? My mistake? Is there any way I can get \thepage correct on the very first line of a page? OK to use LuaTeX.
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?
68352
I read some information about Java layout managers and the recommendation was . My problem is, that I didn't found any tutorial or easy step-by-step documentation.  So I want to know how this all works, but I don't know how.  Hope, it's not to trivial.  Thanks in advance, guerda
95490
Why am I getting an out of memory exception?  So this dies in C# on the first time through:  splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat));   Where splitBitmaps is a List&lt;BitMap&gt; BUT this works in VB for at least 4 iterations:  arlSplitBitmaps.Add(Image.Clone(rectDimensions, Image.PixelFormat))  Where arlSplitBitmaps is a simple array list.  (And yes I've tried arraylist in c#)  This is the fullsection:  for (Int32 splitIndex = 0; splitIndex &lt;= numberOfResultingImages - 1; splitIndex++) {    Rectangle rectDimensions;    if (splitIndex &lt; numberOfResultingImages - 1)    {     rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0,        splitImageWidth, splitImageHeight);    }    else    {     rectDimensions = new Rectangle(splitImageWidth * splitIndex, 0,       sourceImageWidth - (splitImageWidth * splitIndex), splitImageHeight);    }     splitBitmaps.Add(neededImage.Clone(rectDimensions, neededImage.PixelFormat));    }   neededImage is a Bitmap by the way.   I can't find any useful answers on the intarweb, especially not why it works just fine in VB.  Update:  I actually found a reason (sort of) for this working but forgot to post it.  It has to do with converting the image to a bitmap instead of just trying to clone the raw image if I remember.
122028
I have a requirement where I use  in Lightning and I have implemented the same as below code. I created a Lightning Tab from this component and used in Lightning Experience. Component: &lt;aura:component implements=&quot;force:appHostable&quot;&gt;     &lt;ltng:require scripts=&quot;/resource/treeTable/treeTableJS.js&quot; afterScriptsLoaded=&quot;{!c.loadScripts}&quot;/&gt;     &lt;aura:attribute name=&quot;temp&quot; type=&quot;String&quot; default=&quot;none&quot; /&gt;     &lt;aura:attribute name=&quot;content&quot; type=&quot;String[]&quot; default=&quot;item1,item2,item3,item4&quot; /&gt;     &lt;table id=&quot;table&quot;&gt;         &lt;tbody&gt;             &lt;tr data-tt-id=&quot;parent&quot;&gt;                 &lt;td&gt;&lt;ui:button label=&quot;Click&quot; press=&quot;{!c.selectClick}&quot; /&gt;&lt;/td&gt;                 &lt;td&gt;Content&lt;/td&gt;             &lt;/tr&gt;             &lt;aura:iteration items=&quot;{!v.content}&quot; var=&quot;item&quot; indexVar=&quot;index&quot;&gt;                 &lt;tr data-tt-id=&quot;{!'child'+index}&quot; data-tt-parent-id=&quot;parent&quot;&gt;                     &lt;td&gt;&lt;/td&gt;                     &lt;td&gt;{!item}&lt;/td&gt;                 &lt;/tr&gt;             &lt;/aura:iteration&gt;         &lt;/tbody&gt;     &lt;/table&gt; &lt;/aura:component&gt;  Controller: ({     loadScripts : function(component, event, helper) {         $(&quot;#table&quot;).treetable({                 expandable: true             }, {                 force: true             }, {                 initialState: &quot;collapsed&quot;             });     },      selectClick : function(component, event, helper) {         if(component.get(&quot;v.temp&quot;)===&quot;none&quot;){             component.set(&quot;v.temp&quot;,&quot;plus&quot;);             $(&quot;#table&quot;).treetable(&quot;expandNode&quot;, &quot;parent&quot;);         } else{             component.set(&quot;v.temp&quot;,&quot;none&quot;);             $(&quot;#table&quot;).treetable(&quot;collapseNode&quot;, &quot;parent&quot;);          }     }, })  Now about the issue, when I use this in Lightning tab first time it works (meaning straight forward scenario), but now from this page I navigate to any standard record page (be it Accounts record page) or even Home page and come back to this lightning tab, it does not work. We have to refresh the page to make it work again. Any resolve so that we don't need to refresh the page? Please help. Note: Lightning Locker service is disabled.
49049
Error Message:  Oops! Your question couldn't be submitted because: Please add some context to explain the code sections (or check that you have not incorrectly formatted all of your question as code).  How do I fix this issue? It says that I need to explain my code more when I try to post this as google-apps-script. I have explained almost every part of the code. Also, this code was posted previously and I just added a few extra lines with explanations. What do they mean by &quot;context&quot; function doGet() {   var app = UiApp.createApplication();   //Create listBox   var listBox = app.createListBox();   //Add items to listBox   listBox.addItem(&quot;item 1&quot;).addItem(&quot;item 2&quot;).addItem(&quot;item 3&quot;).setName(&quot;myListBox&quot;);   //Create hidden app   var hidden = app.createHidden().setName('hidden').setId('hidden')   //Create button handler   var handler = app.createServerHandler(&quot;buttonHandler&quot;);   // pass the listbox into the handler function as a parameter and the hidden widget as well   handler.addCallbackElement(listBox).addCallbackElement(hidden);    //Create flextable   var table = app.createFlexTable().setId(&quot;myTable&quot;);    //Create flex table style attributes     table.setStyleAttribute(&quot;border-style&quot;, &quot;solid&quot;)     table.setStyleAttribute(&quot;border-width&quot;, &quot;1px&quot;)     table.setCellPadding(1);      //Create flex table headers   table.setWidget(0, 0, app.createLabel(&quot;Product Type&quot;)).setStyleAttribute(&quot;color&quot;, &quot;blue&quot;);   table.setWidget(0, 5, app.createLabel(&quot;Size&quot;));    var button = app.createButton(&quot;+&quot;, handler);    // add all widgets to the app   app.add(table).add(hidden);   app.add(listBox).add(button)   return app; }  function buttonHandler(e) {   var app = UiApp.getActiveApplication();   // get the position (is a string)   var pos = e.parameter.hidden;   // initial condition, hidden widget is empty    if(pos==null){pos='0'};   // convert to number    pos=Number(pos);   var table = app.getElementById(&quot;myTable&quot;);   // add the new item at the right place   table.insertRow(pos).insertCell( pos, 0).setText(pos, 0, e.parameter.myListBox);   // increment position   ++pos;   // save value   app.getElementById('hidden').setValue(pos);   // update app   return app; }